esm-loader-json
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

esm-loader-json

Node.js ESModule Loader for importing JSON files as modules.

This is an alternative to the Node.js --experimental-json-modules flag. This flag used to work well, but as of node>=17.1, Node.js requires a new import assertion syntax, and will fail without it. If you are trying to load code that does not use this new syntax, you will run into problems. Just use this loader instead of Node's built-in JSON import support, and problems are solved.

Warning! This uses experimental Node.js features and flags, whose API will likely change. This code may be helpful for development and testing, but should not be used in production.

Usage

npm install --save-dev esm-loader-json

You may have code which imports .json files:

// data.json
{
  "name": "Vito"
}
// index.js
import data from './data.json'
console.log(data) // { "name": "Vito" }

Standalone

# node >= 20.7
cat << EOF > ./register.js
import { register } from 'node:module'
register('esm-loader-json', import.meta.url)
EOF
NODE_OPTIONS="--import ./register.js" node index.js

# node < 20.7
NODE_OPTIONS="--loader esm-loader-json" node index.js

Chainable

This loader can be configured, and chained with other loaders, using node-esm-loader.

npm install --save-dev node-esm-loader
// .loaderrc.js
export default {
  loaders: ['esm-loader-json'],
}
# node >= 20.7
NODE_OPTIONS="--import node-esm-loader/register" node index.js

# node < 20.7
NODE_OPTIONS="--loader node-esm-loader" node index.js

Options

Debug
// .loaderrc.js
export default {
  loaders: [
    {
      loader: 'esm-loader-json',
      options: {
        debug: true,
      },
    },
  ],
}

License

MIT

Package Sidebar

Install

npm i esm-loader-json

Weekly Downloads

1

Version

1.0.6

License

MIT

Unpacked Size

6.1 kB

Total Files

4

Last publish

Collaborators

  • brev