const CopyWebpackPlugin = require("copy-webpack-plugin");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
const StringReplacePlugin = require("string-replace-webpack-plugin");

const ReplaceCssPlugin = require("./script/replaceCssPlugin.js");

const path = require("path");

const isProduction = process.env.NODE_ENV === "production";

// 只需要复制的文件
const copyFiles = [
  {
    from: path.resolve(`src/manifest.json`),
    to: `${path.resolve("dist")}/manifest.json`,
  },
  {
    from: path.resolve("src/assets"),
    to: path.resolve("dist/assets"),
  },
];

const plugins = [
  new CopyWebpackPlugin({
    patterns: copyFiles,
  }),

  new  ReplaceCssPlugin(),
  AutoImport({
    include: [
      /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
      /\.vue$/,
      /\.vue\?vue/, // .vue
    ],
    imports: [
      // 插件预设好包
      "vue",
      // 自定义要自动按需引入的npm包
      {
        axios: [
          // default imports
          ["default", "axios"], // import { default as axios } from 'axios',
        ],
      },
    ],
    dts: false,
    eslintrc: {
      enabled: false, // 默认false, true启用。生成一次就可以,避免每次工程启动都生成
      filepath: "./.eslintrc-auto-import.json", // 生成json文件
      globalsPropValue: true,
    },

    resolvers: [ElementPlusResolver()],
  }),
  Components({
    resolvers: [ElementPlusResolver()],
  }),
];

// 配置页面
const pages = {};
/**
 * popup 和 devtool 都需要html文件
 * 因此 chromeName 还可以添加devtool
 */
const chromeName = ["popup"];

chromeName.forEach((name) => {
  pages[name] = {
    entry: `src/${name}/index.js`,
    template: `src/${name}/index.html`,
    filename: `${name}.html`,
  };
});

module.exports = {
  pages,
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,

  configureWebpack: {
    // 多入口打包
    entry: {
      content: "./src/content/index.js",
      background: "./src/background/index.js",
    },
    output: {
      filename: "js/[name].js",
    },
    plugins,
    optimization: {
      splitChunks: {
        chunks: "async",
        minSize: 20000,
        minRemainingSize: 0,
        minChunks: 1,
        maxAsyncRequests: 30,
        maxInitialRequests: 30,
        enforceSizeThreshold: 50000,
        cacheGroups: {
          defaultVendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            reuseExistingChunk: true,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
    },
  },
  chainWebpack: (config) => {},
  css: {
    extract: {
      filename: "css/[name].css",
    },
  },
};