webpack-plugin-modify-entrypoints
Version:
webpack plugin to modify entrypoint contents
70 lines (69 loc) • 3.01 kB
JavaScript
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { makeIdent } from './utils.js';
export const PLUGIN_NAME = 'modify-entrypoints';
export class ModifyEntryPoints {
options;
constructor(options) {
this.options = options;
}
apply(compiler) {
const entryPoints = new Map();
const infraLogger = compiler.getInfrastructureLogger(PLUGIN_NAME);
compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => {
Promise.resolve()
.then(() => (typeof entry === 'function' ? entry() : entry))
.then(entryNormalized => {
Object.entries(entryNormalized).forEach(([key, value]) => {
value.import?.forEach((importPath, index, imports) => {
infraLogger.status(`Recording imports: ${key} - ${index + 1} of ${imports.length}`);
entryPoints.set(resolve(context, importPath), {
processed: false,
entryKey: key,
});
});
});
infraLogger.status();
infraLogger.debug({ entryPoints });
})
.catch(error => {
infraLogger.status();
infraLogger.error(error);
});
});
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
const loaderPath = fileURLToPath(new URL('loader.js', import.meta.url));
infraLogger.debug(`Loader path: ${loaderPath}`);
compiler.webpack.NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(PLUGIN_NAME, (loaders, normalModule) => {
const entryDetails = entryPoints.get(normalModule.userRequest);
if (entryDetails?.processed === false) {
const options = {
modify: this.options.modify,
details: {
userRequest: normalModule.userRequest,
entryKey: entryDetails.entryKey,
},
};
const loaderItem = {
loader: loaderPath,
options,
ident: makeIdent(options),
type: 'module',
};
loaders.push(loaderItem);
infraLogger.status(`Loader added to entrypoint: ${entryDetails.entryKey}`);
infraLogger.debug({
loaderItem,
userRequest: normalModule.userRequest,
entryDetails,
});
entryPoints.set(normalModule.userRequest, {
...entryDetails,
processed: true,
});
}
infraLogger.status();
});
});
}
}