Created
April 10, 2023 20:47
-
-
Save feedthejim/43c7b0dd7086cc928e1ff21fda85ce0f to your computer and use it in GitHub Desktop.
Webpack Import timing plugin
This file contains 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 { ConcatSource } = require('webpack-sources') | |
class ImportTimingPlugin { | |
constructor(options = {}) { | |
this.options = options | |
} | |
apply(compiler) { | |
compiler.hooks.compilation.tap('ImportTimingPlugin', (compilation) => { | |
compilation.hooks.processAssets.tap( | |
{ | |
name: 'ImportTimingPlugin', | |
stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONS, | |
}, | |
() => { | |
const chunkGraph = compilation.chunkGraph | |
for (const chunk of compilation.chunks) { | |
const entryModulesIterable = | |
chunkGraph.getChunkEntryModulesIterable(chunk) | |
if (!entryModulesIterable || entryModulesIterable.size === 0) | |
continue | |
const asset = compilation.getAsset(chunk.files[0]) | |
if (!asset) continue | |
const wrappedSource = new ConcatSource( | |
` | |
(function() { | |
const originalRequire = require; | |
require = function(moduleId) { | |
const moduleName = typeof moduleId === 'number' ? moduleId : moduleId.toString(); | |
console.time("require: " + moduleName); | |
const result = originalRequire.apply(this, arguments); | |
console.timeEnd("require: " + moduleName); | |
return result; | |
}; | |
})(); | |
`, | |
asset.source | |
) | |
compilation.updateAsset(chunk.files[0], wrappedSource) | |
} | |
} | |
) | |
}) | |
} | |
} | |
module.exports = ImportTimingPlugin |
This file contains 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 ImportTimingPlugin = require('./import-timing-plugin') | |
module.exports = { | |
webpack: (config, { isServer }) => { | |
if (isServer) { | |
config.plugins.push(new ImportTimingPlugin()) | |
} | |
return config | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment