JSON 模块
目前导入 JSON 模块仅支持 commonjs 模式,并且使用 CJS 加载器加载。
WHATWG JSON 模块规范仍在标准化中,并且通过在运行 Node.js 时包含额外的标志 --experimental-json-modules 进行实验性地支持。
当包含 --experimental-json-modules 标志时,commonjs 和 module 模式都使用新的实验性 JSON 加载器。
导入的 JSON 只暴露 default。
不支持命名导出。
在 CommonJS 缓存中创建缓存条目,以避免重复。
如果 JSON 模块已经从同一路径导入,则在 CommonJS 中返回相同的对象。
假设 index.mjs 具有
import packageConfig from './package.json';模块需要 --experimental-json-modules 标志才有效。
node index.mjs # 失败
node --experimental-json-modules index.mjs # 有效Currently importing JSON modules are only supported in the commonjs mode
and are loaded using the CJS loader. WHATWG JSON modules specification are
still being standardized, and are experimentally supported by including the
additional flag --experimental-json-modules when running Node.js.
When the --experimental-json-modules flag is included, both the
commonjs and module mode use the new experimental JSON
loader. The imported JSON only exposes a default. There is no
support for named exports. A cache entry is created in the CommonJS
cache to avoid duplication. The same object is returned in
CommonJS if the JSON module has already been imported from the
same path.
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