javascriptnode.jses6-modules

Import '.json' extension in ES6 Node.js throws an error


We're trying to use the new ways of exporting and importing modules for ES6 with Node.js. It's important for us to get the version number from the package.json file. The following code should do that:

import {name, version} from '../../package.json'

However, on execution the following error is thrown:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js

Is there something we're missing?
Is the extension .json not supported?
Is there another way to retrieve this information using Node.js 13+?


Solution

  • With Node.js 18.20.0 onward:

    import myToken from './MyToken.json' with {type: "json"};
    

    From Node.js version 17.5.0 onward, importing a JSON file is possible using Import Assertions:

    import packageFile from "../../package.json" assert { type: "json" };
    
    const {
        name,
        version
      } = packageFile;
    

    The dynamic import version looks like this:

    const {
        default: {
          name,
          version
        }
      } = await import("../../package.json", {
        assert: {
          type: "json"
        }
      });
    

    Since import assertions and JSON modules have only recently promoted to stage 3, older versions of Node.js might have supported an older syntax. According to the compatibility tables on MDN for import declarations and dynamic import, older versions of Node.js (16.0.0 – 16.14.0 and 17.0.0 – 17.4.0) had varying support: