为什么作为ES6模块导入时会起作用? [英] Why doesn't 'fs' work when imported as an ES6 module?

查看:19
本文介绍了为什么作为ES6模块导入时会起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试对ES6模块使用新的Node.js支持(例如,通过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)模块都是如此。

令人困惑的是,在类型脚本模块(带有@Types/node和ES5输出)中,import fs from 'fs'会产生错误

error TS1192: Module '"fs"' has no default export
因此,在打印脚本中,默认情况下必须写为import * as fs from 'fs';。似乎可以使用tsconfig.json中的新"esModuleInterop": true option将其更改为与mjs文件的工作方式相匹配。

这篇关于为什么作为ES6模块导入时会起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆