const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const ProgressBarPlugin = require("progress-bar-webpack-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")

const isDevelopment = process.env.NODE_ENV === "development"

// 清理缓存,避免本地缓存越来越大
if (isDevelopment) {
  const cachePath = path.resolve(__dirname,"../node_modules/.cache")
  new CleanWebpackPlugin().removeFiles([cachePath])
}

const outputPath = (function () {
  return path.resolve(__dirname, "../dist")
})()

let commonConfig = {
  target: ["web", "es5"],
  entry: {
    index: path.resolve(__dirname, "../src/index.jsx")
  },
  output: {
    filename: "static/js/[name]_[chunkhash:4].js",
    path: outputPath,
    clean: true,
  },
  cache: {
    type: "filesystem",
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "../src"),
    },
    extensions: [".jsx", ".js", ".json"],
    symlinks: false,
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: {
          loader: "babel-loader",
        },
        include: [path.resolve(__dirname, "../src")],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        include: [
          path.resolve(__dirname, "../src"),
          path.resolve(__dirname, "../node_modules/leaflet"),
        ],
        use: ["style-loader", "css-loader", "postcss-loader"],
      },
      {
        test: /\.scss$/,
        include: [path.resolve(__dirname, "../src")],
        use: ["style-loader", "css-loader", "postcss-loader", "sass-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|bmp|svg)$/,
        include: [
          path.resolve(__dirname, "../src"),
          path.resolve(__dirname, "../node_modules/leaflet"),
        ],
        type: "asset",
        generator: {
          filename: "static/images/[name]_[hash].[ext]",
        },
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        include: [path.resolve(__dirname, "../src")],
        type: "asset",
        generator: {
          filename: "static/fonts/[name]_[hash].[ext]",
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
      chunks: ["index"],
      baseApi: isDevelopment ? "/PMS" : "/PMS",
    }),
    new ProgressBarPlugin(),
  ],
}

module.exports = commonConfig