Skip to content

Instantly share code, notes, and snippets.

@iamssen
Created June 5, 2024 05:39
Show Gist options
  • Save iamssen/17dccc5324d04ea9e84f99bcdb9f7a05 to your computer and use it in GitHub Desktop.
Save iamssen/17dccc5324d04ea9e84f99bcdb9f7a05 to your computer and use it in GitHub Desktop.
Handling Import Aliases in Node.js ESM without NODE_PATH: A Practical Example
import generateAliasesResolver from 'esm-module-alias';
import { glob } from 'glob';
// TODO Create an aliases map { '@dir/a': 'dist/@dir/a/index.js', '@dir/b': 'dist/@dir/b/index.js', ... }
const aliases = glob
.sync('dist/@*/*/index.js', { cwd: import.meta.dirname })
.reduce((a, jsfile) => {
a[jsfile.substring(13, jsfile.length - 9)] = jsfile;
return a;
}, {});
export const resolve = generateAliasesResolver(aliases);
{
"scripts": {
"start": "NODE_ENV=development node --import=./register.mjs dist/server.js"
}
}
import { register } from 'node:module';
import { pathToFileURL } from 'node:url';
register('./loader.mjs', pathToFileURL('./'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment