Files
test-repo/scripts/build/esbuild-plugins/replace-module.mjs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-02-05 22:51:17 +08:00
import { dirname } from "node:path";
export default function esbuildPluginReplaceModule(replacements = {}) {
return {
name: "replace-module",
setup(build) {
2022-02-05 22:51:17 +08:00
build.onLoad({ filter: /./ }, ({ path, namespace }) => {
let options = replacements[path];
if (!options) {
return;
}
2022-02-05 22:51:17 +08:00
options =
typeof options === "string" ? { path: options } : { ...options };
2022-02-05 22:51:17 +08:00
let {
path: file,
resolveDir,
contents,
loader = "js",
external: isExternal,
} = options;
// Make this work with `@esbuild-plugins/node-modules-polyfill` plugin
if (
!resolveDir &&
namespace === "node-modules-polyfills-commonjs" &&
file
) {
resolveDir = dirname(file);
}
2022-02-05 22:51:17 +08:00
if (isExternal) {
if (!file) {
throw new Error("Missing external module path.");
}
// Prevent `esbuild` to resolve
2022-02-05 22:51:17 +08:00
contents = `
const entry = ${JSON.stringify(`${file}`)};
module.exports = require(entry);
`;
} else {
if (file) {
contents = `
module.exports = require(${JSON.stringify(`${file}`)});
`;
}
}
2022-02-05 22:51:17 +08:00
return { contents, loader, resolveDir };
});
},
};
}