Skip to content

Instantly share code, notes, and snippets.

@feedthejim
Created April 10, 2023 20:47
Show Gist options
  • Save feedthejim/43c7b0dd7086cc928e1ff21fda85ce0f to your computer and use it in GitHub Desktop.
Save feedthejim/43c7b0dd7086cc928e1ff21fda85ce0f to your computer and use it in GitHub Desktop.
Webpack Import timing plugin
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
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