This is the 7th day of my participation in Gwen Challenge
Webpack4.x package output directory into folders
- Before optimization
- The optimized
Through the comparison before and after optimization, it is obviously found that the output structure after optimization is clearer. And when I update an application, I can only send the corresponding package folder and entry file, reducing the volume of the package; At the same time, Chrome debugging can also use folders to quickly locate the source file location
The solution
There is very little to do with the WebPack configuration, but this little bit can be exploited! This is my output configuration
output: {
path: path.resolve(__dirname, ""),
filename: "static_dist/cdaPlugin/script/[name].min.js".publicPath: "/mtex/".chunkFilename: `static_dist/cdaPlugin/script/[name].[chunkhash:8].min.js`,},Copy the code
In the above configuration, variables such as name and chunkhash can be used when defining the output location of no Entry Chunk (the corresponding location is chunkFilename), among which the name variable plays a key role in packaging the output by folder! His definition is
As long as we load the component asynchronously, the value of the chunkfilename content passed in the specific format will be replaced by [name] here.
Here’s an example:
import(
/* webpackChunkName: "base/dateTimePicker" */ '.. /plugin2xCom/components/dateTimePicker/DatePicker.vue'
)
Copy the code
Here,webpackChunkName
A value ofbase/dateTimePicker
And replace the one to the exitname
To achieve the effect of path separator (create folder).
The chunk imported can be divided into asynchronous and synchronous. Asynchronous chunk imported can be controlled by using the above method. For synchronous chunk imported, path implementation can be added in the plug-in NamedChunksPlugin, as shown below
new webpack.NamedChunksPlugin((chunk) = > {
if (chunk.name) {
return `base/${chunk.name}`; / / < - here
}
const modules = Array.from(chunk.modulesIterable);
if (modules.length > 1) {
const hash = require("hash-sum");
const joinedHash = hash(modules.map((m) = > m.id).join("_"));
let len = nameLength;
while (seen.has(joinedHash.substr(0, len))) len++;
seen.add(joinedHash.substr(0, len));
return `base/chunk-${joinedHash.substr(0, len)}`; / / < - here
} else {
return `base/${modules[0].id}`; / / < - here}}),Copy the code
This is the end of the principle part, just change the output string writing!!
If webpackage 5.x is used, you can directly set chunkfilename as a function (there is a parameter to obtain chunk information and output the result by chunk information classification. The above method applies to 4.x and below).