webpack配置

32 阅读1分钟

抽离css,并压缩cs

// 不做处理style-loader默认会将样式写到style中,生产中不适合这样

第一步

image.png

第二步抽离css

image.png

第三步压缩css代码

image.png

抽离公共代码

第三方代码是不会变得,如果和业务代码放在一起每次代码变了contenthash跟着变,所以第三方包要跟着打包,所以单独将第三方包拆出来就能解决这个问题,

image.png

   cacheGroups: {
        // 第三方模块
        vendor: {
          name: "vendor", // chunk 名称
          priority: 1, // 权限更高,优先抽离,重要!!!
          test: /node_modules/,
          minSize: 0, // 大小限制 3-5kb
          minChunks: 1, // 第三方代码只要复用一次 第三方包只要
        },

        // 公共的模块
        common: {
          name: "common", // chunk 名称
          priority: 0, // 优先级
          minSize: 0, // 公共模块的大小限制 大小限制 3-5kb
          minChunks: 2, // 公共模块最少复用过几次
        },
      },

一个面试题 module chunk bundle的区别

module: 各个源码文件
chunk:   多模块合并成的,entry import() splitChunk
bundke:  最终生成的文件

contentHash

文件内容没变,打包出来的文件名就不会变

多入口

// 1.入口文件
entry: {
index: path.join(srcPath, 'index.js'),
other: path.join(srcPath, 'other.js')
},
// 2.生成html文件
// 多入口 - 生成 index.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'index.html'),
filename: 'index.html',
// chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
chunks: ['index', 'vendor', 'common'] // 要考虑代码分割
}),
// 多入口 - 生成 other.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'other.html'),
filename: 'other.html',
chunks: ['other', 'common'] // 考虑代码分割
})
]
// output
output: {

// filename: 'bundle.[contentHash:8].js', // 打包代码时,加上 hash 戳

filename: "[name].[contentHash:8].js", // name 即多入口时 entry 的 key

path: distPath,

// publicPath: 'http://cdn.abc.com' // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到

},