关于node.js:node如何在ES-modules中导入JSON文件

1次阅读

共计 1021 个字符,预计需要花费 3 分钟才能阅读完成。

Node 14 开始,开始反对 ES module 语法。

JSON 模块工作在 Node.js 版本 >=17.1 中,也能够应用 --experimental-json-modules 标记启用 Experimental JSON 模块

/* 
  Experimental JSON import in Node.js
  $ node index.mjs
*/

// An import assertion in a static import
import info from `./package.json` assert {type: `json`};

// An import assertion in a dynamic import
const {default: info} = await import("./package.json", {
  assert: {type: "json",},
});

我曾经习惯在 node.js 应用 require 导入 json,例如const data = require('./some-file.json'),下面的写法无疑让人感到丧气。

如果你还不想应用这个实验性的性能,这篇文章解释了在 ES 模块中解决 JSON 的办法。

1. 手动读取和解析 JSON 文件

其实就是应用 fs 模块读取文件,而后再用 JSON.parse 解析。

import {readFile} from 'fs/promises';
const json = JSON.parse(
  await readFile(new URL('./some-file.json', import.meta.url)
  )
);

2. 利用 CommonJS 的 require 函数来加载 JSON 文件(举荐)

import {createRequire} from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");

createRequire容许你结构一个 CommonJS require 函数来应用 CommonJS 的典型性能,例如在 Node.js 的 EcmaScript 模块中读取 JSON。

总结

import assertions无疑是将来 ES modules 导入 json 的最佳抉择,但惋惜它目前仍然是试验性功能。至于介绍的 2 种代替计划,其实都不是最佳计划,但不影响你解决问题。

参考文章

  • 厉害了,ECMAScript 新提案:JSON 模块
  • How to import JSON files in ES modules (Node.js)
正文完
 0