Last active
November 25, 2019 00:49
-
-
Save ScriptedAlchemy/06421f21322d82546279aa7402b35e89 to your computer and use it in GitHub Desktop.
[contenthash] for webpack module ids
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 createHash = require('webpack/lib/util/createHash'); | |
| const usedIds = new Set(); | |
| compilation.hooks.beforeModuleIds.tap('URLImportPlugin', (modules) => { | |
| for (const module of modules) { | |
| // if the module has an id, and its got a path to a real file | |
| if (module.id === null && module.resource) { | |
| const hash = createHash(this.opts.hashFunction || 'md4'); | |
| // grab the resource path, without any loader queries | |
| let resourcePath = module.resource; | |
| if (resourcePath.indexOf('?') > -1) { | |
| resourcePath = resourcePath.split('?')[0]; | |
| } | |
| try { | |
| // update the generated hash with the buffer content of the literal file | |
| hash.update(fs.readFileSync(resourcePath)); | |
| } catch (ex) { | |
| // whine and complain | |
| console.error('failed on', module.context, module.resource); | |
| throw ex; | |
| } | |
| const hashId = hash.digest(this.opts.hashDigest); | |
| let len = this.opts.hashDigestLength; | |
| while (usedIds.has(hashId.substr(0, len))) { | |
| len++; | |
| } | |
| // digest and set a shorter version of the hash as the module.id | |
| // React is now require('b3wS6Q') | |
| module.id = hashId.substr(0, len); | |
| usedIds.add(module.id); | |
| } | |
| // if the module contains a magic export | |
| const moduleSource = module?.originalSource?.().source?.() || ''; | |
| if (moduleSource?.indexOf('externalize') > -1 || false) { | |
| // attach a flag to the modules build meta | |
| module.buildMeta = mergeDeep(module.buildMeta, { isExternalized: true }); | |
| try { | |
| // look at refactoring this to use buildMeta not mutate id | |
| // rename the externalized module to a nice name which was parsed off the magic export | |
| // Nav can now be required as require('Nav') | |
| module.id = moduleSource.match(/\/\*\s*externalize\s*:\s*(\S+)\s*\*\//)[1]; | |
| externalModules[module.id] = {}; | |
| } catch (error) { | |
| throw new Error('external-import', error.message); | |
| } | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment