Skip to content

Instantly share code, notes, and snippets.

@JakobJingleheimer
Last active January 22, 2021 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakobJingleheimer/837e7692dc14d2512330f2f2816fad8f to your computer and use it in GitHub Desktop.
Save JakobJingleheimer/837e7692dc14d2512330f2f2816fad8f to your computer and use it in GitHub Desktop.
import path from 'path';
import { pathToFileURL } from 'url';
const npmPackage = await import(
pathToFileURL(`${process.cwd()}/package.json`).href
).then(({ default: json }) => json);
const aliases = (() => {
const base = process.cwd();
const { aliases } = npmPackage || {};
const absoluteAliases = Object.create(null);
for (
let aliasKeys = Object.keys(aliases),
i = 0,
end = aliasKeys.length;
i < end;
i++
) {
const aliasKey = aliasKeys[i];
const aliasPath = aliases[aliasKey];
if (aliasPath[0] !== '/') {
absoluteAliases[aliasKey] = path.join(base, aliasPath);
}
}
return absoluteAliases;
})();
const aliasKeys = Object.keys(aliases);
const isAliasInSpecifier = (path, alias) => {
const aliasLength = alias.length;
return (
path.indexOf(alias) === 0
&& (
path.length === aliasLength
|| path[aliasLength] === '/'
)
);
};
export const resolve = (
specifier,
parentModuleURL,
defaultResolve,
) => {
const aliasKey = aliasKeys.find((key) => isAliasInSpecifier(specifier, key));
if (aliasKey) {
const url = path.join(aliases[aliasKey], specifier.substr(aliasKey.length));
return { url };
}
return defaultResolve(specifier, parentModuleURL, defaultResolve);
};
@JakobJingleheimer
Copy link
Author

// package.json
{
  "aliases": {
    "~": "./src"
  }
}
$> node --experimental-loader=./alias-loader.mjs ./index.mjs
$> mocha --recursive ./src --experimental-loader=./alias-loader.mjs

@JakobJingleheimer
Copy link
Author

JakobJingleheimer commented Jan 21, 2021

⚠️ This appears to have broken somewhere between node v15.1.0 and v15.6.0. I'm suddenly getting an error:
SyntaxError: Setter must have exactly one formal parameter.
    at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)

however, there is no setter on translators.js:147

The above was due to an error in my own source-code, which node ESM erroneously reported as coming from the alias loader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment