科技微讯

Node.js 项目使用 NodeNext 配置 Typescript 的方法

在 Node.js 中配置 Typescript,.tsconfig.json 通常设置为 "module": "CommonJS",这篇文章分享如果设置为 "module": "NodeNext" 需要怎么做,有哪些注意事项。

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "sourceMap": true,
    "outDir": "dist",
    "strict": true
  },
  "include": ["src/**/*"]
}
//这是一个模块 helper.ts
export const name = "科技微讯";
//在 index.ts 引入 helper.ts 模块,需要添加 .js 后缀
import { name } from "./helper.js";

以上是 ESM 的用法,"module": "NodeNext" 允许同时在项目中使用 CommonJS,但要使用 .cts 后缀:

//这是一个模块 helper.cts
module.exports.name2 = "科技微讯";

同时引入 ESM 和 CommonJS 模块,一律用 import

import { name } from "./helper.js";
import myName from "./helper.cjs";
console.log(name); //科技微讯
console.log(myName); //{name2: "科技微讯"}

虽然 Node.js 12 开始就开始逐步支持 ESM,Node.js 16 已经正式支持,但 ESM 其实并没有普及,至少国内的云函数服务都不支持用 ESM 作为 handler 入口函数,这意味着国内的云函数都无法运行纯 ESM 代码。


相关笔记:

thumbsup0
thumbsdown0
暂无评论