首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于导入json文件的ERR_IMPORT_ASSERTION_TYPE_MISSING

用于导入json文件的ERR_IMPORT_ASSERTION_TYPE_MISSING
EN

Stack Overflow用户
提问于 2021-11-25 06:49:05
回答 3查看 29.7K关注 0票数 47

这个代码运行得很好。

我不知道是不是因为我升级到Node 17什么的,但现在我

代码语言:javascript
运行
复制
TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]:
  Module "file:///Users/xxxxx/code/projects/xxxxx/dist/server/data/countries.json" 
  needs an import assertion of type "json"

在我的api.ts中有:

代码语言:javascript
运行
复制
import countryTable from './data/countries.json';

下面是我如何启动由api.ts使用的server.ts

代码语言:javascript
运行
复制
NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --no-warnings server/server.js
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-11-25 06:50:46

您需要使用:

代码语言:javascript
运行
复制
import countryTable from "./data/countries.json" assert { type: "json" };

https://github.com/tc39/proposal-import-assertions

票数 87
EN

Stack Overflow用户

发布于 2022-09-16 16:07:40

对于任何有ESLint验证问题的人(由于assert还不受支持),您可以尝试同步地从文件系统加载JSON:

代码语言:javascript
运行
复制
const loadJSON = (path) => JSON.parse(fs.readFileSync(new URL(path, import.meta.url)));

const countries = loadJSON('./data/countries.json');

参考资料:https://github.com/eslint/eslint/discussions/15305

票数 8
EN

Stack Overflow用户

发布于 2022-11-19 22:07:10

若要在ES模块中导入.json,可以使用

代码语言:javascript
运行
复制
module.createRequire()

https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#no-require-exports-or-moduleexports

因为在node.js的第18.12.1版中断言仍然是实验性的

代码语言:javascript
运行
复制
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

const countryTable = require('./data/countries.json');

https://nodejs.org/dist/latest-v18.x/docs/api/module.html#modulecreaterequirefilename

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70106880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档