Skip to content

Instantly share code, notes, and snippets.

@tanhauhau
Last active January 22, 2020 14:50
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 tanhauhau/b6b355fbbabe224c9242a5257baa4dec to your computer and use it in GitHub Desktop.
Save tanhauhau/b6b355fbbabe224c9242a5257baa4dec to your computer and use it in GitHub Desktop.
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