Search code examples
node.jscommand-line-interfacees6-modulespreload

How to require ES module with node -r options


In some case I need to start a node.js process with the -r option to preload a ESM library mriya. The library can be installed with the command npm i mriya, and the command I want to run is node -r mriya. It works when I require a CommonJS module, but when it is a ES module the command will fail with the following message

[Error [ERR_REQUIRE_ESM]: require() of ES Module mriya-test/node_modules/mriya/dist/mriya.js not supported.
Instead change the require of mriya.js in null to a dynamic import() which is available in all CommonJS modules.] {
  code: 'ERR_REQUIRE_ESM'
}

Is there alternative option for -r to use with the ES Module, or is there any workaround I can use? Thank you.


Solution

  • node --experimental-loader your-esm-module
    

    https://nodejs.org/api/esm.html#loaders


    You can omit experimental- too:

    node --loader your-esm-module
    

    Also, see:

    https://github.com/nodejs/node/issues/40110

    https://github.com/nodejs/node/issues/44094

    https://github.com/nodejs/node/pull/43942