Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 8081

Here's the top of my index.js file:

import "module-alias/register"
import "@/setup"

import "@/setup" does not work whereas require("@/setup") does.

like image 522
A. L Avatar asked Nov 08 '18 02:11

A. L


Video Answer


1 Answers

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.

like image 131
mihai Avatar answered Sep 21 '22 20:09

mihai