Last active
November 25, 2019 00:49
-
-
Save ScriptedAlchemy/594c679111f8b843bbdb13ec25cbdcef to your computer and use it in GitHub Desktop.
Split Chunks cache groups via module api
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
| function hasExternalizedModule(module) { | |
| const moduleSource = module?.originalSource?.()?.source?.() || ''; | |
| // dead simple way to check if the magic export comment is in a file | |
| if (moduleSource?.indexOf('externalize') > -1 || false) { | |
| return moduleSource; | |
| } | |
| return false; | |
| } | |
| const interleaveConfig = test => ({ | |
| // Massive NormalModule API is exposed through the test method | |
| test(module) { | |
| if (module.resource) { | |
| // check the resource is externalized and withing a path i accept (src) | |
| return module.resource.includes(test) && !!hasExternalizedModule(module); | |
| } | |
| }, | |
| name(module, chunks, cacheGroupKey) { | |
| // dont chunk unless we are sure you can | |
| const moduleSource = hasExternalizedModule(module); | |
| if (moduleSource) { | |
| // parse the source with regex and get the name a file was externalized as. Like: externalize: Nav | |
| // Nav becomes the cacheGroup, which splits this file into Nav.chunk.js | |
| return moduleSource.match(/\/\*\s*externalize\s*:\s*(\S+)\s*\*\//)[1]; | |
| } | |
| // returning a chunk name causes problems with mini-css popping chunks off | |
| // return 'main'; | |
| }, | |
| enforce: true, // Forcefully split these files | |
| reuseExistingChunk: false, // force it out of another chunk and into its own | |
| }); | |
| // standard webpack optimization config which is used to reconfigure the webpack chunk splitting under the hood | |
| optimization: { | |
| runtimeChunk: 'multiple', | |
| namedModules: true, | |
| splitChunks: { | |
| chunks: 'all', // dont just split async import()s but also split my interleaved files | |
| cacheGroups: { | |
| interleave: interleaveConfig('src') | |
| }, | |
| }, | |
| }, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment