在 ES6 Node.js 中导入“.json”扩展会引发错误

Dar*_*te1 43 javascript node.js es6-modules

我们正在尝试使用 Node.js 为 ES6 导出和导入模块的新方法。从package.json文件中获取版本号对我们来说很重要。下面的代码应该这样做:

import {name, version} from '../../package.json'
Run Code Online (Sandbox Code Playgroud)

但是,在执行时抛出以下错误:^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js
Run Code Online (Sandbox Code Playgroud)

有什么我们遗漏的吗?不支持
扩展.json吗?
有没有其他方法可以使用 Node.js 13+ 检索此信息?

小智 66

根据Node.js ES 模块文档 --experimental-json-modules。需要导入 JSON 文件。

包括--experimental-json-modules标志以使模块工作。

node --experimental-json-modules about.js
Run Code Online (Sandbox Code Playgroud)

  • 但每次都添加该标志很烦人。可以永久设置吗? (3认同)

Iva*_*ele 22

2022年

来自 Node.js v16 & v18官方文档:

import SomeJson from './some.json' assert { type: 'json' }
Run Code Online (Sandbox Code Playgroud)

并使用匹配的实验标志运行它:

node --experimental-json-modules ./your-file.js
Run Code Online (Sandbox Code Playgroud)


Car*_*obb 9

你可以require在 Node.js 的 ES6 模块中导入:

import { createRequire } from "module"; // Bring in the ability to create the 'require' method
const require = createRequire(import.meta.url); // construct the require method
const my_json_file = require("path/to/json/your-json-file.json") // use the require method
Run Code Online (Sandbox Code Playgroud)

  • @CAlonsoCOrtega 我们正在我的答案的第 2 行创建“require”。如果未定义,则您必须跳过前几行。 (7认同)
  • Node.Js v15 最新给我这个错误 `ReferenceError: require is not Defined` (4认同)

小智 5

您可以像在 docs node-js 中一样使用它,如下所示:

import { readFile } from 'fs/promises';

const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));
Run Code Online (Sandbox Code Playgroud)

  • 如果您在服务器上执行此操作...我强烈推荐更干净的“fs-extra”,它透明地承诺一切并支持递归目录复制 (2认同)