当我尝试使用新的 Node.js 对 ES6 模块的支持(例如使用
node --experimental-modules script.mjs
)时,为什么会出现这样的错误?
// script.mjs
import * as fs from 'fs';
// TypeError: fs.readFile is not a function
fs.readFile('data.csv', 'utf8', (err, data) => {
if (!err) {
console.log(data);
}
});
// TypeError: fs.readdirSync is not a function
fs.readdirSync('.').forEach(fileName => {
console.log(fileName);
});
您必须使用
import fs from 'fs'
,而不是 import * as fs from 'fs'
。
这是因为(至少从mjs文件的角度来看)
'fs'
模块只导出一个东西,称为default
。因此,如果您写 import * as fs from 'fs'
,则 fs.default.readFile
存在,但 fs.readFile
不存在。也许所有 Node.js (CommonJS) 模块都是如此。
令人困惑的是,在 TypeScript 模块(带有 @types/node 和 ES5 输出)中,
import fs from 'fs'
会产生错误
error TS1192: Module '"fs"' has no default export
所以在 TypeScript 中你必须默认编写
import * as fs from 'fs';
。看来可以使用 tsconfig.json 中的新 "esModuleInterop": true
选项 进行更改以匹配 mjs 文件的工作方式。
我们可以像这样简单地在我们的代码中导入它
import * as fs from 'fs';
它对我来说非常有效,请尝试一下
在我的 tsconfig.json 文件中添加 "esModuleInterop": true 解决了问题