const path = require('path');
const resolve = (dir) => path.join(__dirname, dir);
const CompressionPlugin = require('compression-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const obfuscator = require('./obfuscator');
const obfuscatorFiles = require('./obfuscatorFiles');
const webpack = require('webpack');
const nodeEnv = process.env.NODE_ENV;
const outputDir = 'admin';
module.exports = {
  outputDir: outputDir,
  productionSourceMap: false,
  parallel: false,
  publicPath: '/admin/',
  assetsDir: 'public',
  chainWebpack: (config) => {
    // 兼容浏览器
    config.entry('main').add('babel-polyfill');
    // 配置路径别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@api', resolve('src/api'))
      .set('@assets', resolve('src/assets'))
      .set('@comp', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@utils', resolve('src/utils'));
    if (nodeEnv !== 'development') {
      config.plugin('compressionPlugin').use(
        new CompressionPlugin({
          test: /\.js$|\.html$|\.css$|\.svg$/, // 匹配文件名
          threshold: 102400, // 对超过100k的数据压缩
          deleteOriginalAssets: false // 不删除源文件
        })
      );
      // config.plugin('fileManagerPlugin').use(
      //   new FileManagerPlugin({
      //     events: {
      //       onEnd: {
      //         copy: [
      //           {
      //             source: `./${outputDir}/admin/public`,
      //             destination: `./${outputDir}/public`
      //           }
      //         ]
      //       }
      //     }
      //   })
      // );
    }
    if (nodeEnv === 'production') {
      // 执行混淆器方法生成混淆文件
      obfuscator();
      // 遍历需要混淆的文件列表
      obfuscatorFiles().forEach((item) => {
        // 将需要混淆的源文件更换为混淆后的新文件
        config
          .plugin(item.obfuscatorIndex)
          .use(new webpack.NormalModuleReplacementPlugin(new RegExp(item.resourceRegExp), item.newResource));
      });
      config.plugin('uglifyJs').use(
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              comments: false
            },
            // 生产环境自动删除console
            compress: {
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      );
    }
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, './src/style/variable.less')] // 引入全局样式变量
    }
  },
  // 反向代理
  devServer: {
    // 环境配置
    open: nodeEnv === 'development',
    port: 7999,
    proxy: {
      '/dgapi': {
        target: process.env.VUE_APP_BASE_API,
        changeOrigin: true,
        pathRewrite: {
          '^/dgapi': '/'
        }
      }
    }
  }
};
