const path = require('path');
const resolve = dir => path.join(__dirname, dir);
const IS_PROD = process.env.NODE_ENV === 'production';
const WebpackCosCdnUploadPlugin = require('@qg/webpack-cos-cdn-upload-plugin');
const SentryPlugin = require('@qg/sentry-webpack-plugin');
const SentryConfig = require('./.sentryclirc');
// cdn预加载使用
const externals = {
  vue: 'Vue',
  'vue-router': 'VueRouter',
  vuex: 'Vuex',
  'sa-sdk-javascript': 'sensorsDataAnalytic201505' // 神策js在window下的全局引用会出现两个，这个才是真物
  // axios: "axios"
};
const cdn = {
  // 生产环境
  build: {
    js: [
      'https://activitystatic.lkbang.net/vue/2.6.11/vue.min.js',
      'https://activitystatic.lkbang.net/vue-router/3.2.0/vue-router.min.js',
      'https://activitystatic.lkbang.net/vuex/3.4.0/vuex.min.js',
      'https://activitystatic.lkbang.net/sa-sdk-javascript/1.15.16/sensorsdata.min.js'
    ]
  }
};

module.exports = {
  transpileDependencies: [/[/\\]node_modules[/\\]@qg[/\\]cherry-ui[/\\]/],
  chainWebpack: config => {
    config.plugin('html').tap(args => {
      args[0].title = '';
      if (IS_PROD) {
        args[0].cdn = cdn.build;
      }
      return args;
    });
    // 修复HMR
    config.resolve.symlinks(true);

    // 移除 prefetch 插件(针对生产环境首屏请求数进行优化)
    config.plugins.delete('prefetch');

    // 移除 preload 插件(针对生产环境首屏请求数进行优化)   preload 插件的用途：https://cli.vuejs.org/zh/guide/html-and-static-assets.html#preload
    config.plugins.delete('preload');

    // 添加别名
    config.resolve.alias.set('@', resolve('src'));
    // svg-sprite
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/svg'))
      .end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();
    // 组件静态资源引入
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        return {
          ...options,
          transformAssetUrls: {
            'cr-image': 'src',
            'cr-button': 'icon',
            'cr-icon': 'type',
            'cr-field': ['right-icon', 'left-icon'],
            'cr-cell': ['right-icon', 'icon']
          }
        };
      });
    // 分包优化
    config.optimization.splitChunks({
      chunks: 'all',
      cacheGroups: {
        initial: {
          name: 'chunk-init', // 分离需要在入口加载的依赖
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: 'initial' // only package third parties that are initially dependent
        },
        libs: {
          name: 'chunk-libs', // 分离非在入口加载的，但是引用超过2次的依赖
          test: /[\\/]node_modules[\\/]/,
          priority: 8,
          minChunks: 2,
          chunks: 'all' // only package third parties that are initially dependent
        },
        svg: {
          name: 'chunk-svg',
          priority: 9,
          chunks: 'initial',
          test: resolve('src/assets/svg'),
          reuseExistingChunk: true,
          enforce: true
        },

        cherryUI: {
          name: 'chunk-cherryUI', // 分离组件库
          priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          test: /[\\/]node_modules[\\/]@qg[\\/]_?cherry-ui(.*)/ // in order to adapt to cnpm
        },
        commons: {
          name: 'chunk-commons', // 将src中components|service|mixins|api|config三个文件夹下的引用次数超过2次的js合并
          test: /[\\/]src[\\/](components|service|mixins|api|config)[\\/]/, // can customize your rules
          minChunks: 2, //  minimum common number
          priority: 5,
          reuseExistingChunk: true
        }
      }
    });
    // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
    config.optimization.runtimeChunk('single');
    return config;
  },
  configureWebpack: config => {
    let configObj = null;
    if (IS_PROD) {
      config.externals = externals;
      configObj = {
        plugins: [new SentryPlugin(SentryConfig), new WebpackCosCdnUploadPlugin()]
        // plugins: [new WebpackCosCdnUploadPlugin()]
      };
    }
    return configObj;
  },
  lintOnSave: true,
  runtimeCompiler: false, // 是否使用包含运行时编译器的 Vue 构建版本
  productionSourceMap: IS_PROD, // 生产环境的 source map
  devServer: {
    proxy: 'http://kdsp-vcc.liangkebang.net'
  },
  css: {
    loaderOptions: {
      less: {
        // 若使用 less-loader@5，请移除 lessOptions 这一级，直接配置选项。
        modifyVars: {
          // 直接覆盖变量
          hack: `true; @import "${resolve('./src/style/theme.less')}";`
        }
      }
    }
  }
};
