【问题标题】:Does the ES modules implementation support importing JSON files?ES 模块实现是否支持导入 JSON 文件?
【发布时间】:2020-05-01 11:41:43
【问题描述】:

我在使用新的 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 模块读取文件的选项了吗?

【问题讨论】:

  • 这能回答你的问题吗? How to import a json file in ecmascript 6?
  • 嗯,JSON 不是 Javascript,那么您为什么会认为它会呢?只需读取文件并解析内容。
  • @JustinWorkman 实际上没有,我已经检查了所有答案,但没有一个对我有用,我想检查是否有除了阅读文件之外的解决方案。
  • @Pierre 你有两个选择:读取文件并解析内容,或者使用像 webpack 这样的加载器来处理非 JS 资产(不适合节点项目,obvs)。 Ecmascript 模块适用于,嗯,Ecmascript,JSON 完全不同。

标签: javascript node.js


【解决方案1】:

我在Node.js ES Modules docs 中发现,目前仅在 CommonJS 模式下支持导入 JSON,并且在 ES 模块中导入 JSON 文件需要标志 --experimental-json-modules

假设一个 index.mjs 带有

import packageConfig from './package.json';

模块工作需要 --experimental-json-modules 标志。

node index.mjs # fails
node --experimental-json-modules index.mjs # works

【讨论】:

  • 那是真的很糟糕,对便携性来说真是一记耳光。嗯,看来你得到了答案,+1。
【解决方案2】:

你可以这样导入:

import *  as config from '../config.json'

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2014-04-27
    • 2021-11-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多