【问题标题】:How can I import .json files in nodejs using ECMA Modules?如何使用 ECMA 模块在 nodejs 中导入 .json 文件?
【发布时间】:2020-11-12 16:37:39
【问题描述】:

我正在使用 nodejs 14.6.0。在我的 package.json 文件中,我将类型设置为模块。

type: module

在尝试执行以下操作时:

import serviceAccount from 'serviceAccount.json'

我收到以下错误:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for C:\Users\Aditya\youtube-discord-bot\database\serviceAccount.json

现在,网上说我必须像这样更改我的启动脚本:node --experimental-json-modules index.js。但是,即使有了这个,也会发生同样的错误。

有解决办法吗?我想要求使用此功能的 serviceAccountKey,因为在尝试将其导出(作为 .js 文件)时,Firebase 给了我一个错误。

过去,在这样做之前,我一直在使用require('./serviceAccount.json'),并且效果很好。但是,我想改用这些新的 ECMA 模块。

【问题讨论】:

    标签: javascript node.js import module require


    【解决方案1】:

    如果您需要使用无法更改并转换为导出的 .json 文件,您仍然可以使用 require,如下所示:

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

    【讨论】:

      【解决方案2】:
      1. 使用 webpack:https://webpack.js.org/loaders/#json
      2. 将 json 文件传输到 js 对象中:
        config.js
          export default
          {
            // my json here...
          }
      

      那么……

          import config from '../config.js'
      

      【讨论】:

      • 谢谢。你在哪里写了“我的 json...”,我是放实际的 json 还是一个 javascript 对象?
      • 很好的答案,也许 webpack 是唯一的方法,因为节点对 es6 模块的支持有限,支持不太好。
      猜你喜欢
      • 2020-11-10
      • 2020-04-12
      • 2018-10-26
      • 2018-06-25
      • 2021-12-08
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多