const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyPlugin = require("copy-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const { entrys, htmlPlugin } = require("./config")

module.exports = {
  entry: entrys,
  output: {
    path: path.resolve(__dirname, '../dist')
  },
  optimization: {
    usedExports: true
  },
  module: {
    rules: [
      // 将es6编译成es5
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, '../src'),
        use: [{
          loader: "babel-loader",
          options: {
            presets: [
              [
                "@babel/preset-env",
                {
                  loose: true,
                  useBuiltIns: "usage",
                  corejs: 2,
                  targets: {
                    ie: 8,
                    chrome: "46",
                  },
                },
              ],
            ],
            plugins: [
              [
                "@babel/plugin-transform-runtime",
                {
                  corejs: 2,
                },
              ],
              "@babel/plugin-transform-modules-commonjs",
              "transform-es3-property-literals",
              "transform-es3-member-expression-literals",
            ],
          }
        }]
      },
      {
        test: /\.(png|jpg|svg|ico)$/,
        exclude: /node_modules/,
        use: {
          loader: "file-loader",
          options: {
            name: "[name].[ext]",
            publicPath: "../assets/",
            outputPath: "assets/"
          },
        },
      },
      {
        test: /\.(css|less)$/,
        use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: ''
          }
        }, 'css-loader', 'less-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)/,
        use: {
          loader: "url-loader",
          options: {
            limit: 8192,
            outputPath: 'assets/'
          },
        },
      },
      {
        test: /\.hbs$/i,
        loader: "handlebars-loader",
      },
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyPlugin({
      patterns: [
        { from: './static', to: 'static/' },
        { from: './favicon.ico', to: './favicon.ico' },
      ],
    }),
    ...htmlPlugin,
    new MiniCssExtractPlugin({
      filename: 'css/[name]_[chunkhash].css',
      chunkFilename: 'css/[name]_[chunkhash].chunk.css',
    })
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new TerserWebpackPlugin({
        exclude: /node_modules/,
        terserOptions: {
          compress: { properties: false },
          output: { quote_keys: false },
          mangle: false,
          ie8: true
        }
      })
    ]
  }
}