
const fs = require('fs')
const path = require('path')

const webpack = require('webpack')
const WebpackMerge = require('webpack-merge')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const AutoPrefixer = require('autoprefixer')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const $GLOBAL = require('./webpack.base.conf')


let config = null

if ($GLOBAL.isDev === 'development') {
  config = WebpackMerge($GLOBAL.BaseConfig, {
    mode: 'development',
    devtool: '#cheap-module-eval-source-map',
    output: {
      filename: '[name].js'
    },
    devServer: {
      port: $GLOBAL.webConf.serverPort,
      disableHostCheck: false,
      host: $GLOBAL.webConf.domain || 'localhost',
      https: $GLOBAL.webConf.isHttps && {
        key: fs.readFileSync(path.join(__dirname, '../static/cert/dev.ezijing.com.key')),
        cert: fs.readFileSync(path.join(__dirname, '../static/cert/dev.ezijing.com.pem'))
      },
      overlay: {
        errors: true
      },
      historyApiFallback: {
        index: '/index.html'
      },
      proxy: {
        '/api': {
          target: $GLOBAL.webConf.url,
          selfHandleResponse: false,
          secure: false,
          changeOrigin: true,
          followRedirects: true,
          logLevel: 'info',
          headers: {
            'Referer': $GLOBAL.webConf.url
          },
          pathRewrite: {
            '^/api': '/'
          }
        }
      },
      open: true,
      hot: true
    },
    module: {
      rules: [{
        test: /\.(sa|sc|c)ss$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                AutoPrefixer({
                  'overrideBrowserslist': [
                    'cover 99.5%',
                    'ie 6-8',
                    'since 2015',
                    'last 10 iOS versions'
                  ]
                })
              ]
            }
          },
          {
            loader: 'sass-loader', // 不再使用本身默认 node-sass，部分mac安装有问题。
            options: {
              implementation: require('dart-sass')
            }
          }
        ]
      }]
    },
    plugins: [
      new VueLoaderPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath
      })
    ]
  })
} else {
  config = WebpackMerge($GLOBAL.BaseConfig, {
    mode: 'production',
    entry: {
      app: $GLOBAL.EntryPath,
      vendor: ['vue', 'vue-router']
    },
    module: {
      rules: [{
        test: /\.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
            }
          },
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                AutoPrefixer({
                  'overrideBrowserslist': [
                    'cover 99.5%',
                    'ie 6-8',
                    'since 2015',
                    'last 10 iOS versions'
                  ]
                })
              ]
            }
          },
          {
            loader: 'sass-loader', // 不再使用本身默认 node-sass，部分mac安装有问题。
            options: {
              implementation: require('dart-sass')
            }
          }
        ]
      }]
    },
    plugins: [
      new CleanWebpackPlugin(['**/*'], { root: $GLOBAL.OutputPath }),
      new MiniCssExtractPlugin({
        filename: '[name].[contenthash:12].css',
        chunkFilename: $GLOBAL.cssName
      }),
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath,
        minify: {
          removeComments: true,
          collapseWhitespace: true
        }
      }),
      new CopyWebpackPlugin([
        {
          from: $GLOBAL.EntryStaticPath,
          to: $GLOBAL.OutputStaticPath,
          ignore: ['.*'],
          transform: function (content) {
            return content
          }
        }
      ])
    ],
    optimization: {
      runtimeChunk: {
        name: 'manifest'
      },
      splitChunks: {
        chunks: 'async',
        minSize: 30000,
        maxSize: 400000, // 大于400kb 会再进行拆分，可以进行优化时，添加
        minChunks: 1,
        maxAsyncRequests: 5, // 按需加载块时并行请求的最大数量
        maxInitialRequests: 3, // 初始页面加载时并行请求的最大数量
        name: false,
        cacheGroups: {
          vendor: { // 将所有node_modules中模块 js打包到一起，并拆分
            name: 'vendor',
            chunks: 'initial',
            priority: -10,
            reuseExistingChunk: false,
            test: /node_modules\/(.*)\.js/
          },
          // styles: { // 将所有node_modules中模块 css、scss打包到一起，并拆分，暂时没用，还在研究
          //   name: 'styles',
          //   test: /node_modules\/\.(sa|sc|c)ss$/,
          //   chunks: 'all',
          //   minChunks: 1,
          //   reuseExistingChunk: true,
          //   enforce: true
          // }
        }
      }
    }
  })
}

module.exports = config
