Skip to content Skip to sidebar Skip to footer

Esm Does Not Resolve Module-alias

So I'm using the package esm and module-alias, but it seems like esm does not register module-alias's paths. Here's how I'm loading my server file: nodemon -r esm ./src/index.js 8

Solution 1:

The problem is that esm tries to handle all import statements when parsing the file, before any other module gets loaded.

When processing import statements, it uses node's builtin require rather than the modified require created by module-alias

To fix this, you need to first load module-alias and then esm. This way, module-alias will get the chance to modify the require function before esm gets to do anything.

You can achive this by passing multiple -r parameters to node, but make sure module-alias comes first:

node -r module-alias/register -r esm index.js 8081

or with nodemon:

nodemon -r module-alias/register -r esm ./src/index.js 8081

You also need to remove the import "module-alias/register" from your code, since now it's loaded from the command line.

Solution 2:

For me worked the following code:

package.json

"scripts":{"dev":"pkill -f lib/serverIndex.js; NODE_ENV=development node lib/serverIndex.js",

lib/serverIndex.js

require = require('esm')(module/*, options*/);
require('module-alias/register');
module.exports = require("./server.js");

Post a Comment for "Esm Does Not Resolve Module-alias"