Ris*_*ain 3 javascript import module require node.js
我使用的是nodejs 14.6.0。在我的 package.json 文件中,我将类型设置为 module。
type: module
Run Code Online (Sandbox Code Playgroud)
尝试执行以下操作后:
import serviceAccount from 'serviceAccount.json'
Run Code Online (Sandbox Code Playgroud)
我收到以下错误: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 模块。
小智 6
如果您需要使用无法更改和转换为导出的 .json 文件,您仍然可以使用 require,如下所示:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const serviceAccount = require('./serviceAccount.json');
Run Code Online (Sandbox Code Playgroud)