Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SetModuleTemplatePlugin
const { ConcatSource } = require('webpack-sources');
const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
const JavascriptModulesPlugin = require('webpack/lib/javascript/JavascriptModulesPlugin');
/** @typedef {import("./Compiler")} Compiler */
class SetModuleTemplatePlugin {
/**
* @param {string} moduleMethod the accessor where the library is exported
* @param {boolean} moduleName specify copying the exports
*/
constructor(moduleMethod, moduleName) {
/** @type {string} */
this.moduleMethod = moduleMethod;
/** @type {boolean} */
this.moduleName = moduleName;
}
/**
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const FlagEntryExportAsUsedPlugin = require('webpack/lib/FlagEntryExportAsUsedPlugin');
new FlagEntryExportAsUsedPlugin(true, 'used a library export').apply(
compiler
);
compiler.hooks.thisCompilation.tap(
'SetModuleTemplatePlugin',
compilation => {
compilation.hooks.additionalTreeRuntimeRequirements.tap(
'LibraryTemplatePlugin',
(chunk, set) => {
set.add(RuntimeGlobals.returnExportsFromRuntime);
}
);
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.render.tap(
'SetModuleTemplatePlugin',
(source, { chunk, chunkGraph }) => {
if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return source;
const moduleMethod = compilation.getPath(this.moduleMethod, {
chunk,
});
return new ConcatSource(
`${moduleMethod}('${this.moduleName}',`,
source,
')'
);
}
);
hooks.chunkHash.tap(
'SetModuleTemplatePlugin',
(chunk, hash, { chunkGraph }) => {
if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return;
hash.update('set var');
const moduleMethod = compilation.getPath(this.moduleMethod, {
chunk,
});
hash.update(`${moduleMethod}`);
hash.update(`${this.moduleName}`);
}
);
}
);
}
}
module.exports = SetModuleTemplatePlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment