webpack打包优化

转载人家的 https://www.cnblogs.com/wulinzi/p/8081531.html

我自己的:webpack.prod.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
      },
      chunksSortMode: 'dependency'
    }),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vue-video-player',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue-video-player')
          ) !== 0
        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'elementuicommon',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/element-ui/lib/element-ui.common')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'pdfjs',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/pdfjs-dist/build/pdf.js')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'video',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/video')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'axios',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/axios')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'GeminiScrollbar',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/GeminiScrollbar')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'element',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/element-ui')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vue-baidu-map',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue-baidu-map')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vue',
      minChunks (module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue')
          ) !== 0

        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: path.join(config.build.assetsSubDirectory, 'static'),
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

module.exports = webpackConfig

 转载的内容↓

// 下面是引入nodejs的路径模块
var path = require('path')
// 下面是utils工具配置文件,主要用来处理css类文件的loader
var utils = require('./utils')
// 下面引入webpack,来使用webpack内置插件
var webpack = require('webpack')
// 下面是config目录下的index.js配置文件,主要用来定义了生产和开发环境的相关基础配置
var config = require('../config')
// 下面是webpack的merger插件,主要用来处理配置对象合并的,可以将一个大的配置对象拆分成几个小的,合并,相同的项将覆盖
var merge = require('webpack-merge')
// 下面是webpack.base.conf.js配置文件,我其他博客文章已经解释过了,用来处理不同类型文件的loader
var baseWebpackConfig = require('./webpack.base.conf')
// copy-webpack-plugin复制文件或者文件夹到指定的目录的
var CopyWebpackPlugin = require('copy-webpack-plugin')
// html-webpack-plugin是生成html文件,可以设置模板
var HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin这个插件是用来将bundle中的css等文件分离到指定.css文件
var ExtractTextPlugin = require('extract-text-webpack-plugin')
// optimize-css-assets-webpack-plugin插件的作用是压缩css代码的,
//还能去掉extract-text-webpack-plugin插件抽离文件产生的重复代码,
//因为同一个css可能在多个模块中出现所以会导致重复代码,换句话说这两个插件是两兄弟 // 详情见(1)
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var ZipPlugin = require('zip-webpack-plugin')

//var env ={NODE_ENV: '"production"'}
var env = config.build.env
// 把当前的配置对象和基础的配置对象合并

var webpackConfig = merge(baseWebpackConfig, {
  module: {
// 下面就是把utils配置好的处理各种css类型的配置拿过来
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
// devtool开发工具,用来生成个sourcemap方便调试,,,没仔细看
  devtool: '#source-map',
  output: {
  // 打包后的文件放在dist目录里面
    path: config.build.assetsRoot,
  // 文件名称使用 static/js/[name].[chunkhash].js, 其中name就是index,chunkhash就是模块的hash值,用于浏览器缓存的
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
  // chunkFilename是非入口模块文件,也就是说filename文件中引用了chunckFilename
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'),
    //publicPath: "https://cdn.chinaclear.cn/siteResource/pop-online-fund-vote-web/"
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
  // 下面是利用DefinePlugin插件,定义process.env环境变量为env
    new webpack.DefinePlugin({
      'process.env': env
    }),
// UglifyJsPlugin插件是专门用来压缩js文件的
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        //删除无用代码时不输出警告  
        warnings: false, // 禁止压缩时候的警告信息,给用户一种vue高大上没有错误的感觉
        //删除console语句
        drop_console: true
      },
      //删除注释
      comments: false,
      mangle: false,
  // 压缩后生成map文件
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
    // 生成独立的css文件,下面是生成独立css文件的名称
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      allChunks: true
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
    // 压缩css文件
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin

  // 生成html页面
    new HtmlWebpackPlugin({
    //生成index.html
      filename: config.build.index,
    // 模板是index.html加不加无所谓
      template: 'index.html',
      favicon: './src/assets/images/favicon.ico',
      excludeChunks: ['admin'],
      chunks: ['manifest','vue','ele','vendor','index'],
    // 将js文件放到body标签的结尾
      inject: true,
      minify: {
    // 压缩产出后的html页面
        removeComments: false,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  // 分类要插到html页面的模块
      chunksSortMode: 'manual'//'dependency'
    }),


    new HtmlWebpackPlugin({
      filename: config.build.adminIndex,
      template: 'admin.html',
      favicon: './static/img/favicon.ico',//'./src/assets/images/favicon.ico',
      excludeChunks: ['index'],
      chunks: ['manifest','vue','ele','vendor','admin'],
      inject: true,
      minify: {
        removeComments: false,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'manual' //'dependency'
    }),

    new webpack.HashedModuleIdsPlugin(),
    
    // split vendor js into its own file
// 下面的插件是将打包后的文件中的第三方库文件抽取出来,便于浏览器缓存,提高程序的运行速度

    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['index', 'admin'],
// 将所有依赖于node_modules下面文件打包到vendor中
      minChunks: function (module, count) {
        return (
          module.resource && 
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 && 
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/element-ui')
          ) !== 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue')
          ) !== 0 
        )
      }
    }),

    //分离element-ui
    new webpack.optimize.CommonsChunkPlugin({
        name: 'ele',
        filename: 'static/js/[name].[chunkhash].js',
        chunks: ['admin','index'] ,
        minChunks: function (module, count) {
          return (
            module.resource &&
            /\.js$/.test(module.resource) && 
            module.resource.indexOf(
              path.join(__dirname, '../node_modules/element-ui')
            ) === 0
          )
        }
    }),

    //分离vue组件
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vue',
      filename: 'static/js/[name].[chunkhash].js',
      chunks: ['index','admin'], 
      minChunks: function (module, count) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue')
          ) === 0 
        )}
    }),

    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated

// 把webpack的runtime代码和module manifest代码提取到manifest文件中,防止修改了代码但是没有修改第三方库文件导致第三方库文件也打包的问题

    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),

    // copy custom static assets
// 下面是复制文件的插件,我认为在这里并不是起到复制文件的作用,而是过滤掉打包过程中产生的以.开头的文件

    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ]),

    new ZipPlugin({
      path: path.join(__dirname,'../dist'),
      filename: 'dist.zip'
    })
  ]
})

if (config.build.productionGzip) {
// 开启Gzi压缩打包后的文件,老铁们知道这个为什么还能压缩吗??,就跟你打包压缩包一样,把这个压缩包给浏览器,浏览器自动解压的 
// 你要知道,vue-cli默认将这个神奇的功能禁用掉的,理由是Surge 和 Netlify 静态主机默认帮你把上传的文件gzip了
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}



if (config.build.bundleAnalyzerReport) {  
// 打包编译后的文件打印出详细的文件信息,vue-cli默认把这个禁用了,个人觉得还是有点用的,可以自行配置
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
(1)optimize-css-assets-webpack-plugin插件
   在生产环境中使用extract-text-webpack-plugin,最好也使用这个插件
   使用方法如下
   安装 npm install --save-dev optimize-css-assets-webpack-plugin
   还要安装 cssnano 这是一个css编译器 npm install --save-dev cssnano 这个vue-cli脚手架并没有使用cssnano,但是这个插件的官方说要安装cssnano,这是不是一个bug??
   new OptimizeCssAssetsPlugin({
        assetNameRegExp: /\.optimize\.css$/g, // 不写默认是/\.css$/g
        cssProcessor: require('cssnano'), // 编译器选项,不写默认是cssnano,所以使用这个插件不管怎样都要cssnano
        cssProcessorOptions: { discardComments: {removeAll: true } }, // 传递给编译器的参数
        canPrint: true // 是否能够输出信息
   })

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值