Created
June 5, 2024 05:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"scripts": { | |
"start": "NODE_ENV=development node --import=./register.mjs dist/server.js" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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