I am trying to write a custom webpack loader.
Webpack documentation mentions that access to the _compiler
, _compilation
and _module
properties on loader context is deprecated (https://webpack.js.org/api/loaders/#this_compilation) and should be avoided.
Is there a newer API that would allow me to access them?
For anyone trying to figure out the same thing. I don't think there is any replacement API. The idea probably is that a loader shouldn't really need access to these objects and if you do need them you should use a plugin instead (or in addition).
In case the properties will get removed in future, here is how you can "add them back" using a plugin:
// custom-plugin.js
const NormalModule = require('webpack/lib/NormalModule')
class CustomPlugin {
apply (compiler) {
compiler.hooks.compilation.tap('CustomPlugin', (compilation) => {
NormalModule.getCompilationHooks(compilation).loader.tap('CustomPlugin', (loader, module) => {
loader._customPlugin = {
module: module,
compiler: compiler,
compilation: compilation,
}
})
});
}
}
module.exports = CustomPlugin
// custom-loader.js
module.exports = function (source) {
console.log({
module: this._customPlugin.module === this._module, // true
compiler: this._customPlugin.compiler === this._compiler, // true
compilation: this._customPlugin.compilation === this._compilation, // true
});
return source;
}