webpack优化环境配置 - 23.code split(3)
1.文件结构

2.代码
index.js
function sum(...arg) { return arg.reduce((p, c) => p + c, 0); } /* * 通过js代码,让某个文件被单独打包成一个chunk * import 动态导入语法: 能将某个文件单独打包 * */ //webpackChunkName: 指定打包后生成文件的文件名 import (/*webpackChunkName: 'test'*/'./test') .then(({mul, count}) => { //文件打包成功~ // eslint-disable-next-line console.log("mul:", mul(2, 3)) }) .catch(() => { // eslint-disable-next-line console.log('文件打包失败!!!') }) // eslint-disable-next-line console.log(sum(1, 2, 3, 4, 5, 6));
test.js
export function mul(x, y) { return x * y; } export function count(x, y) { return x - y; }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webpack</title> </head> <body> <h5>hello catch</h5> </body> </html>
webpack.config.js
const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
//单入口
entry: './src/js/index.js',
//多入口
// entry:{
// index:'./src/js/index.js',
// test:'./src/js/test.js'
// },
output: {
// [name] 文件名
filename: "js/[name].[contenthash:10].js",
path: resolve(__dirname, "build")
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
minify: {
collapseWhitespace: true,
removeComments: true
}
})
],
/*
* 1. 可以将 node_modules 中的代码,单独打包一个 chunk 最终输出
* 2. 自动分析多入口chunk中,有没有公共的文件。如果有会打包成单独一个chunk
* */
optimization:{
splitChunks: {
chunks: "all"
}
},
mode: 'production',
}
3.打包
$ webpack

end~

浙公网安备 33010602011771号