javascript 如何获取 Webpack 中每个块包含的所有文件(或模块)的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29966345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a list of all files (or modules) included per chunk in Webpack
提问by srcspider
Can't seem to find any debug option or plugin in webpack to show what exactly went into a chunk.
似乎无法在 webpack 中找到任何调试选项或插件来显示块中究竟发生了什么。
Why do I need this? I've noticed cases where code splitting literally makes everything much larger then just sticking everything in a single file. This is a bit counter intuitive since I don't believe the bootstrap code from webpack is that significant; I suspect it might be minification/deduping, but with out knowing which modules are actually being chunked togheter it's very hard to do some isolated tests to confirm.
为什么我需要这个?我注意到代码拆分实际上使所有内容变得更大的情况,然后只是将所有内容都放在一个文件中。这有点反直觉,因为我不相信来自 webpack 的引导代码那么重要;我怀疑它可能是缩小/重复数据删除,但不知道哪些模块实际上被分块在一起,很难进行一些孤立的测试来确认。
My build process uses gulp; if that makes any difference.
我的构建过程使用 gulp;如果这有什么不同。
回答by Boopathi Rajaa
You can write a plugin that does this.
您可以编写一个插件来执行此操作。
For example,
例如,
var PrintChunksPlugin = function() {};
PrintChunksPlugin.prototype.apply = function(compiler) {
compiler.plugin('compilation', function(compilation, params) {
compilation.plugin('after-optimize-chunk-assets', function(chunks) {
console.log(chunks.map(function(c) {
return {
id: c.id,
name: c.name,
includes: c.modules.map(function(m) {
return m.request;
})
};
}));
});
});
};
For more details, check this page http://webpack.github.io/docs/plugins.html. It contains documentation for all the places you can hook into. Find the proper hook which gets called with chunks: Chunk[]
or chunk
, and inside this you'll be able to access everything you want.
有关更多详细信息,请查看此页面http://webpack.github.io/docs/plugins.html。它包含所有可以挂钩的地方的文档。找到使用chunks: Chunk[]
or调用的正确钩子,在其中chunk
您将能够访问您想要的所有内容。
Also, the stats object contains all the post-build
information you'd ever need. It's available in the done
plugin.
此外,stats 对象包含post-build
您需要的所有信息。它在done
插件中可用。
回答by Малъ Скрылевъ
It seems that it has the key knows as --display-modules
to show all the modules:
似乎它知道--display-modules
显示所有模块的关键:
$ webpack --display-modules
Then you will get the list of used modules similar the following:
然后您将获得类似于以下的使用模块列表:
Asset Size Chunks Chunk Names
javascripts/webpack/app.js 211 kB 0 [emitted] javascripts/webpack/app
stylesheets/webpack/app.js 4.13 kB 1 [emitted] stylesheets/webpack/app
stylesheets/webpack/app.scss 2.99 kB 1 [emitted] stylesheets/webpack/app
[0] ./app/webpack/js/behaviors/lory-icon-slider.js.coffee 1.1 kB {0} [optional] [built]
[1] ./app/webpack/css/components (\.scss|\.css)$ 160 bytes {1} [built]
[2] ./app/webpack/js/behaviors (\.js|\.js.jsx|\.js.coffee)$ 252 bytes {0} [built]
[3] ./~/pickmeup/css/pickmeup.scss 41 bytes {1} [built]
[4] ./app/webpack/css/app.js 205 bytes {1} [built]
[5] ./app/webpack/js/app.js 250 bytes {0} [built]
[6] ./app/webpack/js/behaviors/pickmeup-fixed-calendar.js 3.47 kB {0} [optional] [built]
[7] ./~/lory.js/dist/jquery.lory.js 25 kB {0} [built]
[8] ./~/pickmeup/js/pickmeup.js 41.4 kB {0} [built]
[9] (webpack)/buildin/global.js 509 bytes {0} [built]
Child extract-text-webpack-plugin:
[0] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
[1] ./~/css-loader!./~/sass-loader/lib/loader.js!./~/pickmeup/css/pickmeup.scss 3.23 kB {0} [built]
回答by Sinisag
And here is also a plugin compatible with webpack4, that outputs all your chunks to a single JSON file.
这里还有一个与 webpack4 兼容的插件,它将所有块输出到一个 JSON 文件中。
https://www.npmjs.com/package/chunks-2-json-webpack-plugin
https://www.npmjs.com/package/chunks-2-json-webpack-plugin
Here is how you can use it:
以下是如何使用它:
1) In your webpack config file, import the plugin (after you've installed it of course :) - npm i --save-dev chunks-2-json-webpack-plugin
) and instantiate it under plugins key.
1) 在你的 webpack 配置文件中,导入插件(当然是在你安装它之后 :) - npm i --save-dev chunks-2-json-webpack-plugin
)并在 plugins 键下实例化它。
const Chunks2JsonPlugin = require('chunks-2-json-webpack-plugin');
const path = require('path');
const publicPath = '/app/';
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
publicPath
},
plugins: [
new Chunks2JsonPlugin({ outputDir: 'dist/', publicPath })
]
};
And that's pretty much it, what you will get as a result is a JSON file, that will look something like this:
差不多就是这样,你会得到一个 JSON 文件,它看起来像这样:
{
"chunk-vendors": {
"js": ["/app/js/chunk-vendors.fc40696c.js"],
"js.map": ["/app/js/chunk-vendors.fc40696c.js.map"]
},
"app": {
"css": ["/app/css/app.eb829ccc.css"],
"js": ["/app/js/app.dd31cdcb.js"],
"js.map": ["/app/js/app.dd31cdcb.js.map"]
}
}
Here, we have all our chunks in a single JSON file.
在这里,我们将所有数据块放在一个 JSON 文件中。
More information you can find on the link itself.
您可以在链接本身上找到更多信息。
回答by srcspider
The solution is to write a script that parses the .js.map files, since they contain a sources
entry which can be used to discern all files that were included in the chunk.
解决方案是编写一个脚本来解析 .js.map 文件,因为它们包含一个sources
条目,可用于识别块中包含的所有文件。
Here is a small gulp script that will get the job done,
这是一个可以完成工作的小 gulp 脚本,
var debugWebpackMapFile = function (file) {
var cleanupRules = {
// executed in order
'/src/client/javascript/node_modules/': '',
'/src/client/javascript/': 'static/'
};
return new Promise(function (resolve, reject) {
var match = /\/([^\/]+).js.map$/.exec(file);
if (match != null) {
var filename = match[1];
console.log("\n " + filename + "\n =======================\n");
var mapjson = JSON.parse(fs.readFileSync(file));
var dependencies = [];
var sourcefiles = [];
_.each(mapjson.sources, function (srcfile) {
srcfile = srcfile.replace('webpack://source-code', '', srcfile);
var match = /^\/node_modules\/([^\/]+)/.exec(srcfile);
if (match == null) {
match = /^(\/src\/.*\.js)(\?.*)?/.exec(srcfile);
if (match != null) {
// project source file
srcfile = match[1];
_.each(cleanupRules, function (to, from) {
srcfile = srcfile.replace(from, to);
});
// the sources are in random order in the map file,
// so we'll need to sort before displaying anything
sourcefiles.push(srcfile);
}
}
else {
// dependency
var pkg = match[1];
if (dependencies.indexOf(pkg) == -1) {
dependencies.push(pkg);
}
}
});
sourcefiles.sort();
_.each(sourcefiles, function (srcfile) {
console.log(" " + srcfile);
});
if (dependencies.length > 0) {
console.log("\n ---- 3rd Party ------------------\n");
dependencies.sort();
_.each(dependencies, function (pkg) {
console.log(" " + pkg);
});
}
}
console.log("\n\n");
resolve();
});
}
gulp.task('js:debug', function (cb) {
var conf = webpackConf.mainjs;
glob(conf.output.path + '/*.map', {}, function (er, files) {
var promises = [];
_.each(files, function (file) {
promises.push(debugWebpackMapFile(file));
});
Promise.all(promises).lastly(cb);
});
});
You'll need to modify the script to meet your own configuration.
您需要修改脚本以满足您自己的配置。
Just in case its not obvious, the webpack://source-code
part is due to the devtool settings in webpack output
settings, namely:
以防万一它不明显,这webpack://source-code
部分是由于 webpack 设置中的 devtooloutput
设置,即:
devtoolModuleFilenameTemplate: "webpack://source-code/[resource-path]",
devtoolFallbackModuleFilenameTemplate: "webpack://source-code/[resource-path]?[hash]",
The webpack/internal
and node_modules
are from the following normalization script (I don't like webpack's "~" replacement feature).
在webpack/internal
和node_modules
来自下列标准化脚本(我不喜欢的WebPack的“〜”替换功能)。
var normalizeMaps = function (conf, cb) {
glob(conf.output.path + '/*.map', {}, function (er, files) {
var promises = [];
_.each(files, function (file) {
promises.push(replaceInFile(file, [
[ /\/~/g, '/node_modules' ],
[ /\.\//g, ''],
[ /source-code\/\(webpack\)/g, 'source-code/webpack/internal' ]
]));
});
Promise.all(promises).lastly(cb);
});
};
回答by Potter
This is an updated version of Boopathi Rajaa's answer that will work for later versions of Webpack
(I'm using 4.37.0)
这是 Boopathi Rajaa 答案的更新版本,适用于Webpack
(我使用的是 4.37.0)的更高版本
This updated version worked for me:
这个更新的版本对我有用:
class PrintChunksPlugin {
apply (compiler) {
compiler.plugin('compilation', compilation => {
compilation.plugin('after-optimize-chunk-assets', chunks => {
console.log(chunks.map(chunk => ({
id: chunk.id,
name: chunk.name,
modules: Array.from(chunk._modules).map(module => module.id)
})))
})
})
}
}
Usage:
用法:
plugins: [
new PrintChunksPlugin(),
]
The big difference is that they now store the module information in _modules
rather than modules
and it isn't a mappable object before the Array.from
. I found module.id
to be closer to what I needed, but module.request
is still there if you need that.
最大的区别是,他们现在的模块信息存储在_modules
,而不是modules
它是不是之前的可映射对象Array.from
。我发现module.id
它更接近我需要的东西,但module.request
如果你需要它,它仍然存在。