
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 HtmlReplaceWebpackPlugin = require('html-replace-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const VconsoleWebpackPlugin = require('vconsole-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',
      http2: false,
      https: $GLOBAL.webConf.isHttps && {
        key: fs.readFileSync(path.join(__dirname, $GLOBAL.webConf.domain + '.key')),
        cert: fs.readFileSync(path.join(__dirname, $GLOBAL.webConf.domain + '.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',
            options: {
              implementation: require('dart-sass')
            }
          }
        ]
      }]
    },
    plugins: [
      new VueLoaderPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath
      }),
      new VconsoleWebpackPlugin({
        filter: [],
        enable: $GLOBAL.isEnableToIphoneDebugger
      })
    ]
  })
} else {
  config = WebpackMerge($GLOBAL.BaseConfig, {
    mode: 'production',
    entry: {
      app: $GLOBAL.EntryPath,
      vendor: ['vue', 'vue-router', 'vue-i18n']
    },
    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',
            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 HtmlReplaceWebpackPlugin([
        {
          pattern: $GLOBAL.RegStrs.regExp_static,
          replacement: '$1' + $GLOBAL.webConf.CDN_PATH + 'static/$2$1'
        }
      ]),
      new CopyWebpackPlugin([
        {
          from: $GLOBAL.EntryStaticPath,
          to: $GLOBAL.OutputStaticPath,
          ignore: ['.*'],
          transform: function (content) {
            return content
          }
        }
      ]),
      new VconsoleWebpackPlugin({
        filter: [],
        enable: $GLOBAL.isEnableToIphoneDebugger
      })
    ],
    optimization: {
      runtimeChunk: {
        name: 'manifest'
      },
      splitChunks: {
        chunks: 'async',
        minSize: 30000,
        maxSize: 400000,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        name: false,
        cacheGroups: {
          vendor: {
            name: 'vendor',
            chunks: 'initial',
            priority: -10,
            reuseExistingChunk: false,
            test: /node_modules\/(.*)\.js/
          },
        }
      }
    }
  })
}

module.exports = config
