Created
February 20, 2020 00:55
-
-
Save tanhauhau/2dc6cc376fd190e05d14901b984c7fc1 to your computer and use it in GitHub Desktop.
Webpack additional compilation pass
This file contains hidden or 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 PLUGIN_NAME = 'MY_WEBPACK_PLUGIN'; | |
class MyWebpackPlugin { | |
constructor() { | |
this.cssReady = false; | |
this.cssFiles = []; | |
} | |
apply(compiler) { | |
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => { | |
this.cssReady = false; | |
}); | |
compiler.hooks.compilation.tap( | |
PLUGIN_NAME, | |
(compilation, { normalModuleFactory }) => { | |
// copied from DefinePlugin | |
compilation.dependencyFactories.set(ConstDependency, new NullFactory()); | |
compilation.dependencyTemplates.set( | |
ConstDependency, | |
new ConstDependency.Template() | |
); | |
const handler = parser => { | |
parser.hooks.expression | |
.for('CSS_FILES') | |
.tap(PLUGIN_NAME, expr => { | |
return ParserHelpers.toConstantDependency( | |
parser, | |
JSON.stringify(this.cssFiles) | |
)(expr); | |
}); | |
}; | |
normalModuleFactory.hooks.parser | |
.for('javascript/auto') | |
.tap(PLUGIN_NAME, handler); | |
normalModuleFactory.hooks.parser | |
.for('javascript/dynamic') | |
.tap(PLUGIN_NAME, handler); | |
normalModuleFactory.hooks.parser | |
.for('javascript/esm') | |
.tap(PLUGIN_NAME, handler); | |
// END copied from DefinePlugin | |
compilation.hooks.needAdditionalPass.tap(PLUGIN_NAME, () => { | |
if (!this.cssReady) { | |
this.cssReady = true; | |
return true; | |
} | |
}); | |
} | |
); | |
compiler.hooks.emit.tap(PLUGIN_NAME, compilation => { | |
if (!this.cssReady) { | |
this.cssFiles = Object.keys(compilation.assets) | |
.filter(file => file.endsWith('.css')) | |
.map(file => compilation.options.output.publicPath + file); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment