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

问题描述 投票:0回答:6

我们正在尝试使用 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 13+ 检索此信息?

javascript node.js es6-modules
6个回答
164
投票

从 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
    之类的解构
  • JSON文件的内容是默认导出的,所以需要从
    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
    语法


61
投票

您仍然可以在 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

28
投票

您可以按照文档node-js中的方式使用它,如下所示:

import { readFile } from 'fs/promises';

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

22
投票

2022

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

import SomeJson from './some.json' assert { type: 'json' }

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

node --experimental-json-modules ./your-file.js

0
投票

我在使用Vite编译时也遇到了同样的问题。甚至将

with
更改为
asset
对我来说都不起作用,我必须将文件从
.json
更改为
.js
并在文件开头添加
export default
才能导入数据。

对我来说,这就是解决方案。


-15
投票

尝试使用

process.env.npm_package_version

这可能对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.