我找不到关于使用新的 ES 模块实现导入 JSON 文件的任何答案,我在 StackOverflow 上找到的所有答案都是针对使用 Babel 转译的代码,我想导入我的 package.json
文件:
import pkg from '../package.json';
我收到了这个错误:
(node:7863) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/user/files/project/package.json imported from /home/user/files/project/version.js
at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:126:13)
at Loader.resolve (internal/modules/esm/loader.js:72:33)
at Loader.getModuleJob (internal/modules/esm/loader.js:156:40)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
我正在使用最新的 Node.js 13.6.0 ,我只剩下使用
fs
读取文件的选项了吗?模块?
最佳答案
我在 Node.js ES Modules docs 中找到了当前导入 JSON 仅支持 CommonJS 模式和标志 --experimental-json-modules
在 ES 模块中导入 JSON 文件是必需的。
Assuming an index.mjs with
import packageConfig from './package.json';
The --experimental-json-modules flag is needed for the module to work.
node index.mjs # fails
node --experimental-json-modules index.mjs # works
关于javascript - ES 模块实现是否支持导入 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738999/