Rishab Jain
Rishab Jain

Reputation: 333

How can I import .json files in nodejs using ECMA Modules?

I am using nodejs 14.6.0. In my package.json file, I have type set to module.

type: module

Upon trying to do the following:

import serviceAccount from 'serviceAccount.json'

I get the following error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for C:\Users\Aditya\youtube-discord-bot\database\serviceAccount.json

Now, online it says that I must change my start script like so: node --experimental-json-modules index.js. However, even after having this, the same error occurs.

Is there a workaround to this? I want to require the serviceAccountKey using this functionality, as when trying to export it (as a .js file), Firebase gives me an error.

In the past, before doing this, I have simply been using require('./serviceAccount.json'), and this has worked fine. However, I want to switch to use these new ECMA modules.

Upvotes: 3

Views: 7112

Answers (2)

JamesH
JamesH

Reputation: 85

in case you need to use a .json file that you cannot alter and convert to an export, you can still use require as follows:

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

Upvotes: 7

Phymo
Phymo

Reputation: 152

  1. use webpack: https://webpack.js.org/loaders/#json
  2. transfer the json file to a js object:
    config.js
    export default
    {
      // my json here...
    }

then...

    import config from '../config.js'

Upvotes: 1

Related Questions