我们正在尝试使用 Node.js 导出和导入 ES6 模块的新方法。从
package.json
文件中获取版本号对我们来说很重要。以下代码应该可以做到这一点:
import {name, version} from '../../package.json'
但是,执行时会抛出以下错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js
我们还缺少什么吗?
不支持扩展
.json
吗?从 Node.js 版本 17.5.0 开始,可以使用 Import Assertions:
导入 JSON 文件import packageFile from "../../package.json" assert { type: "json" };
const {
name,
version
} = packageFile;
assert { type: "json" }
为必填项{ name, version }
声明中不可能进行诸如 import
之类的解构default
导入。动态导入版本如下所示:
const {
default: {
name,
version
}
} = await import("../../package.json", {
assert: {
type: "json"
}
});
由于 import 断言 和 JSON 模块 最近才升级到第 3 阶段,旧版本的 Node.js 可能支持旧语法。 根据 MDN 上的
import
声明 和 dynamic import
的兼容性表,旧版本的 Node.js(16.0.0 – 16.14.0 和 17.0.0 – 17.4.0)具有不同的支持:
这些版本需要
--experimental-json-modules
标志:
node --experimental-json-modules about.js
某些版本不支持动态导入断言
import
某些版本不支持
"json"
类型,特别是
某些版本依赖于较旧的提案,该提案尚未指定
assert
语法
您仍然可以在 Node.js 的 ES6 模块中导入
require
:
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
您可以按照文档node-js中的方式使用它,如下所示:
import { readFile } from 'fs/promises';
const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));
我在使用Vite编译时也遇到了同样的问题。甚至将
with
更改为 asset
对我来说都不起作用,我必须将文件从 .json
更改为 .js
并在文件开头添加 export default
才能导入数据。
对我来说,这就是解决方案。