webapck插件打包并进行块分离

好了,紧接上一篇,本来想着配置完了,可以加redux实现页面了,结果,通过凯哥的提示,构建后生成的dist需要压缩,并将文件分离出来,所以,开启了这个的配置。
首先,先实现打包后的文件压缩:
使用webpack的js压缩插件uglifyjs-webpack-plugin和css的压缩插件optimize-css-assets-webpack-plugin,在webpack.config.js里这样配置:

optimization: {
    // 打包压缩文件
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          parse: {
            ecma: 8
          },
          compress: {
            ecma: 5,
            warnings: false,
            comparisons: false
          },
          mangle: {
            safari10: true
          },
          output: {
            ecma: 5,
            comments: false,
            ascii_only: true
          }
        },
        parallel: true,
        cache: true,
        sourceMap: true
      }),
      new OptimizeCSSAssetsPlugin()
    ],
    // 分离块打包文件
    splitChunks: {
      chunks: 'all'
    }

再者,需要将css从打包后的文件中提取出来,在plugins添加MiniCssExtractPlugin就行:

plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './public/index.html'), // src文件
      filename: 'index.html'// dist文件
    }),
    new webpack.HotModuleReplacementPlugin(),
    // 打包后提取出css文件
    new MiniCssExtractPlugin({
      filename: 'public/css/[name].[contenthash:8].css',
      chunkFilename: 'public/css/[name].[contenthash:8].chunk.css'
    })
  ]

其次,打包的时候是生产环境,因此不能用style-loader来编译打包,需要用MiniCssExtractPlugin.loader来实现:

webapck插件打包并进行块分离_第1张图片

之前由于没加这个,相当于没把css提取出来,所以打包就没出现css的文件夹,加了之后,有了css打包文件,ok了。

你可能感兴趣的:(webapck插件打包并进行块分离)