【问题标题】:Why doesn't 'fs' work when imported as an ES6 module?为什么“fs”在作为 ES6 模块导入时不起作用?
【发布时间】:2018-11-12 15:55:09
【问题描述】:

当我尝试使用新的 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);
});

【问题讨论】:

    标签: node.js fs es6-modules


    【解决方案1】:

    您必须使用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 option 对其进行更改以匹配 mjs 文件的工作方式。

    【讨论】:

    • fs 是node中的核心模块,完全不需要导入。它一直都在。
    • 导入fs失败会导致ReferenceError: fs is not defined,即使不是.mjs模块。
    • TypeScript 是为了类型安全,所以你应该导入你的类型。它类似于使用var fs = require('fs');,但我们必须为 TS 做一些诡计才能让它恰到好处。我可以使用Import * as fs from 'fs'; 获得它,但不是Import fs from 'fs';。在启用esModuleInteropallowSyntheticDefaultImports 时,我已经能够对大多数节点模块执行后者,但不是 fs :( 这个确实有效,例如:import path from 'path';
    【解决方案2】:

    我们可以像这样在我们的代码中简单地导入它

    import * as fs from 'fs';
    

    它非常适合我,试一试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2020-01-03
      • 2016-12-11
      • 2011-10-29
      相关资源
      最近更新 更多