const path = require("path");
const resolve = dir => path.join(__dirname, dir);
const IS_PROD = process.env.NODE_ENV === "production";

module.exports = {
  chainWebpack: config => {
    config.plugin("html").tap(args => {
      args[0].title = "芒果保险";
      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/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .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"
          }
        };
      });
    // 分包优化
    config.optimization.splitChunks({
      chunks: "all",
      cacheGroups: {
        libs: {
          name: "chunk-libs",
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: "initial" // only package third parties that are initially dependent
        },
        cherryUI: {
          name: "chunk-cherryUI", // split cherryUI into a single package
          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
        },
        // svg: {
        //   name: "chunk-svg",
        //   priority: 15,
        //   test: resolve("src/assets/icons/svg")
        // },
        commons: {
          name: "chunk-commons",
          test: resolve("src/components"), // can customize your rules
          minChunks: 3, //  minimum common number
          priority: 5,
          reuseExistingChunk: true
        }
      }
    });
    // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
    config.optimization.runtimeChunk("single");
    return config;
  },
  lintOnSave: true,
  runtimeCompiler: false, // 是否使用包含运行时编译器的 Vue 构建版本
  productionSourceMap: IS_PROD // 生产环境的 source map
};
