Last active
January 22, 2020 14:50
-
-
Save tanhauhau/b6b355fbbabe224c9242a5257baa4dec to your computer and use it in GitHub Desktop.
SetModuleTemplatePlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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