【问题标题】:ERR_IMPORT_ASSERTION_TYPE_MISSING for import of json fileERR_IMPORT_ASSERTION_TYPE_MISSING 用于导入 json 文件
【发布时间】:2022-11-20 06:45:04
【问题描述】:

这段代码工作正常。

我不知道是因为我升级到 Node 17 还是什么,但现在我明白了

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 我有:

import countryTable from './data/countries.json';

下面是我如何启动 api.ts,它被 server.ts 使用:

NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --no-warnings server/server.js

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您将需要使用:

    import countryTable from "./data/countries.json" assert { type: "json" };
    

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

    【讨论】:

    • 根据this,在节点 v17.1.0 中引入了导入断言,但在 v17.5.0 之后成为必需的(与此更改相关:github.com/nodejs/node/pull/40785)。导入断言解决了关于信任跨源导入的安全问题 (v8.dev/features/import-assertions)。
    • 谢谢!你让我免于理解为什么昨天运行良好的代码突然停止工作!我实际上需要 GitHub 中详细说明的第二个版本,但你救了我一个受伤的世界!
    • 我没有数据文件夹
    • @PhilipRego 这只是原始问题中使用的文件。您只需添加 assert {type: "json"} 部分。
    【解决方案2】:

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

    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

    【讨论】:

      【解决方案3】:

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

      module.createRequire()
      

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

      because assertions are still experimental in v18.12.1 of node.js

      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

      【讨论】:

        猜你喜欢
        • 2019-12-11
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 2018-07-17
        • 2021-12-27
        相关资源
        最近更新 更多