70 %
Chris Biscardi

Bringing module-alias into the native esm world using node's experimental loaders

module-alias is a fantastic package that only works in commonjs require imports. This is particularly useful if you're replacing compatible modules for server side rendering (like preact/compat for react), whereas client-side rendering is usually compiled and already works.

Note that this feature is experimental so it can and will change in the future.

We can write a module with some small constant aliases. We'll call it loader.mjs. It also includes module-aliases because we need that to handle any commonjs requires laying around. The hook we use is the resolve hook, which accepts a specifier, the requesting module, and the default resolver that node executes normally.

loader.mjs
JS
import "./module-aliases.mjs";
const moduleAliases = {
react: "preact/compat",
"react-dom": "preact/compat",
};
export const resolve = (specifier, parentModuleURL, defaultResolve) => {
return defaultResolve(moduleAliases[specifier] || specifier, parentModuleURL);
};

Finally we can use it in the top of a shell script or on the command line.

shell
#!/usr/bin/env node --loader ./src/loader.mjs