3

I use the module-alias package to enable path aliases in a node project. E.g. it let's you:

const accountRepo = require('@app/account/account-repo')

I'd like to transition the project over to use experimental modules (enabled with the --experimental-modules flag). ES Modules will be enabled without a flag when node 12 goes LTS; thought I'd start experimenting before that. Anyway, module-alias doesn't seem to work with ES modules. I tried adding this to the root of my app (this is the method I was using before transitioning to esm):

require('module-alias/register')

I tried changing it to:

import 'module-alias/register'

I tried requiring when starting the server:

node --experimental-modules -r module-alias/register server/app.js

None of those methods work. I'm guessing that module-alias overrides the require function in order to allow for path aliases, and that of course doesn't work with esm.

I know I can do this with Babel, but I'm using --experimental-modules to avoid that.

I also tried a symlink inside the node_modules folder, but it didn't seem to work running the app inside a Docker container. Also, it seems hacky/fragile to me.

Does anyone know how to enable path aliases in node with native ES modules?

Cully
  • 6,427
  • 4
  • 36
  • 58

2 Answers2

4

I posted this as an issue on github. Apparently module-alias does not yet support ES modules. However, I got a reply with a potential workaround. I haven't tried it myself, but the poster says it works.

https://github.com/ilearnio/module-alias/issues/59#issuecomment-500480450

Cully
  • 6,427
  • 4
  • 36
  • 58
0

The best solution references this question and can be solved by using this npm module (that I did).

For instance:

// my-loader.mjs
import generateAliasesResolver from 'esm-module-alias'; 
const aliases = {
  "@root": ".",
  "@deep": "src/some/very/deep/directory/or/file",
  "@my_module": "lib/some-file.js",
  "something": "src/foo"
};
export const resolve = generateAliasesResolver(aliases);

And then add --loader ./my-loader.mjs, like node --loader ./my-loader.mjs myscript.js

EuberDeveloper
  • 874
  • 1
  • 14
  • 38