const CompressionPlugin = require('compression-webpack-plugin');
const path = require('path')
const webpack = require('webpack');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const HappyPack = require('happypack');
// const copy = require('copy-webpack-plugin')

const SpeedMeasurePlugin = require('speed-measure-webpack-plugin')
const smp = new SpeedMeasurePlugin({
  outputFormat: 'human'
})

module.exports = {
  publicPath: '/mvue',
  runtimeCompiler: true,
  parallel: require("os").cpus().length > 1,
  devServer: {
    proxy: 'http://localhost:8080/mvue',
    public: 'http://localhost:8080/mvue'
  },
  // 开启css sourceMap便于查看线上代码样式  关闭extract 否则无效
  css: {
    extract: false,
    sourceMap: true,
  },
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // gzip压缩
      smp.wrap(
        config.plugins = [
          ...config.plugins,
          // new copy([
          //   {from: "static"}
          // ]),
          new CompressionPlugin({
            // 要压缩的文件类型
            test: /\.js$|\.html$|\.css/,
            // 大于该尺寸的文件才压缩（单位byte)
            threshold: 10240,
            // 是否删除原文件
            deleteOriginalAssets: false
          }),
          new webpack.DllReferencePlugin({
            context: process.cwd(),
            manifest: require('./public/js/vendor-manifest.json')
          }),
          // 将 dll 注入到 生成的 html 模板中
          new AddAssetHtmlPlugin({
            // dll文件位置
            filepath: path.resolve(__dirname, './public/js/*.js'),
            // dll 引用路径
            publicPath: '/mvue/js',
            // dll最终输出的目录
            outputPath: './js',
            includeSourcemap: false
          }),
          new HappyPack({
            loaders: ['babel-loader', 'vue-loader', 'url-loader'],
            threads: 4 // 线程数取决于你电脑性能的好坏，好的电脑建议开更多线程
          })
        ]
      );
      // 删除调试语句
      config.optimization.minimizer[0].options.terserOptions.compress.warnings = false;
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true;
      config.optimization.minimizer[0].options.terserOptions.compress.drop_debugger = true;
      config.optimization.minimizer[0].options.terserOptions.compress.pure_funcs = ['console.log'];
    }

  },
  chainWebpack: config => {
    config.devServer.disableHostCheck(true);
    config.entry('index').add('babel-polyfill');
    if (process.env.NODE_ENV === 'production') {
      // 配置打包时分包的数量上限和单个文件的最小尺寸
      config.plugin('chunkPlugin').use(webpack.optimize.LimitChunkCountPlugin, [{
        maxChunks: 10,
        minChunkSize: 10000
      }])
    }
    config.module
      .rule('worker-loader')
      .test(/\.worker\.js$/)
      .use('worker-loader')
      .loader('worker-loader')
      .end()
  },
  // 不生成sourceMap
  productionSourceMap: false,
  parallel: false
}