Skip to content

Instantly share code, notes, and snippets.

@rjgotten
Last active May 18, 2020 13:44
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 rjgotten/d3a6169f8ed6e7127c3fc4bc99568e43 to your computer and use it in GitHub Desktop.
Save rjgotten/d3a6169f8ed6e7127c3fc4bc99568e43 to your computer and use it in GitHub Desktop.
Using a Webpack InjectOptionsPlugin to supply centralized loader configuration to loaders that are added with inline loader!module import syntax
import Worker from "workerize-loader!./worker"
class InjectOptionsPlugin {
constructor( options = {}) {
const { loaders = {}} = options;
this.loaders = new Map();
Object.entries( loaders ).forEach(([ name, options ]) => {
const resolved = require.resolve( name );
this.loaders.set( resolved, options );
});
}
apply( compiler ) {
compiler.hooks.compilation.tap( "inject-options-plugin", compilation => {
compilation.hooks.buildModule.tap( "inject-options-plugin", module => {
if ( !Array.isArray( module.loaders )) return;
module.loaders.forEach( loader => {
const options = this.loaders.get( loader.loader );
if ( options == null ) return;
loader.options = {
...( loader.options || {}),
...options
};
});
});
});
}
}
module.exports = InjectOptionsPlugin;
const path = require( "path" );
const InjectOptionsPlugin = require( "inject-options-plugin" );
module.exports = env => {
const isDev = env === "development";
const hash = isDev ? "" : ".[contenthash]";
return {
mode : isDev ? "development" : "production",
devtool : isDev ? "source-map" : undefined,
output : {
globalObject : "this",
path : path.resolve( "./dist" ),
publicPath : "/dist/",
filename : `scripts/[name]${hash}.js`,
chunkFilename : `scripts/[name]${hash}.js`
},
entry : {
// (...)
},
module : {
rules : [
// (...)
]
},
plugins : [
new InjectOptionsPlugin({
loaders : {
"workerize-loader" : {
name : `[path][name]${hash}`
}
}
}),
// (...)
]
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment