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 ExtReloader = require('webpack-ext-reloader');


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,
  }),
  //仅支持webpack4.x 不支持5.x 需要自己手动改造5.x版本
  /* new ExtReloader({
    port: 9091, // Which port use to create the server
      reloadPage: true, // Force the reload of the page also
      entries: { // The entries used for the content/background scripts or extension pages
        contentScript: 'content',
        background: 'background',
        extensionPage: 'popup',
      },
  }), */
  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,
  /* pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, './src/assets/css/default.less')]
    }
  }, */
  configureWebpack: {
    // 多入口打包
    entry: {
      content: "./src/content/index.js",
      background: "./src/background/index.js",
    },
    resolve: {
      alias: {
        '@': path.resolve('src'),
      }
    },

    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,
          },
        },
      },
    },
  },

  //配置less解析和浏览器自动补全前缀
  chainWebpack: (config) => {
    config.module.rule('less')
      .test(/\.less$/)
      .use('style-loader')
      .loader('style-loader')
      .end()
      .use('css-loader')
      .loader('css-loader')
      .end()
      .use('postcss-loader')
      .loader('postcss-loader')
      .end()
      .use('less-loader')
      .loader('less-loader')
      .end()
  },
  css: {
    extract: {
      filename: "css/[name].css",
    },
  },
  /* devServer: {
    lazy: false,
    // 将 bundle 写到磁盘而不是内存
    writeToDisk: true,
    before(app, serve, compiler) {
      reloadServer(app, compiler);
    }
  } */
};