前几天,我在使用lowdb过程中遇到了一些问题,lowdb是一个纯ESM的package,于是在这篇文档指引下,了解了如何在ts 中使用ES Module特性。那么下面就为大家阐述其中的细节。
正常情况下,import与export被会编译成commonJS
举个例子
// app.ts
import { num } from './utils'
console.log(num)
// utils.ts
export const num = 1
经过tsc编译后
// app.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
console.log(utils_1.num);
// utils.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.num = void 0;
exports.num = 1;
此时如果这样写
// app.ts
console.log(import.meta)
就会得到这样的错误提示
仅当 “--module” 选项为 “es2020”、“es2022”、“esnext”、“system”、“node16” 或 “nodenext” 时,才允许使用 “import.meta” 元属性。ts(1343)
配置tsconfig.json与package.json
- 在
package.json中新增"type": "module" - 修改
tsconfig.json文件,"moduleResolution": "NodeNext""module": "NodeNext"
修改后运行
ts-node app.ts
得到如下错误信息
Unknown file extension ".ts" for e:\Project\node.js\test\demo01\app.ts
改用如下命令执行
ts-node-esm app.ts
或
ts-node --esm app.ts
正常输出
[Object: null prototype] {
url: 'file:///E:/Project/node.js/test/demo01/app.ts'
}
在tsconfig.json中配置ts-node
在tsconfig.json中新增
"ts-node": {
"esm": true
}
此时可以直接执行
ts-node app.ts
ts中使用ES Module注意事项
- 导入ts文件要以.js结尾,例如导入index.ts,
import x from './index.js' - node模块前加上
node:,例如 - 记得安装
@types/node