Last active
May 18, 2020 13:44
-
-
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
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
import Worker from "workerize-loader!./worker" |
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
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; |
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 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