const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');//------------
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const webpack = require('webpack');
const packageConfig = require('../package.json');

const utils = require('./utils')
const vueLoaderConfig = require('./vue-loader.conf')
let evnConfig = require('./getEnvVar')

// HappyPack
// 原理：每次 webapck 解析一个模块时，HappyPack 会将它及它的依赖分配到worker线程中。
// 提示：由于HappyPack 对file-loader、url-loader 支持的不友好，所以不建议对该loader使用。
// 引入 Happpack 可以在 package.json 找到你下载的
const HappyPack = require('happypack');
// 安装 OS 模块 这个主要是拿到当前电脑的CPU核数
const os = require('os');
/*
	这个是设置共享线程池中的数量
	size 控制设置数量 类型 只能是 整数类型
*/
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

module.exports = {
  // entry: {
  //   'login': ['babel-polyfill', './project/hivuiLogin/index.js'],
  //   'main': ['babel-polyfill','./project/hivuiMain/index.js']
  // },
  // output: {
  //   filename: '[name].[contenthash].js',
  //   chunkFilename: '[name].[contenthash].js',
  //   path: path.resolve(__dirname, 'dist')
  // },
  resolve: {
    extensions: ['.js', '.jsx', '.vue', '.json', '.dtvevt'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      'vuex$': 'vuex/dist/vuex.esm.js',
      '@': path.resolve(__dirname, `${packageConfig.name}`),
      '@main': path.resolve(__dirname, `../${packageConfig.name}/hivuiMain`),
      // '@': path.resolve(__dirname, 'src'),
    }
  },
  externals: {
    'vue': 'Vue',
    'vuex': 'Vuex',
    'vue-router': 'VueRouter',
    "element-ui": "ELEMENT",
  },
  module: {
    rules: [
      ...(utils.styleLoaders({
        sourceMap: false,
        extract: process.env.NODE_ENV === 'production',
        usePostCSS: true
      })),
      {
        test: /\.(js|jsx|dtvevt?|babel|es6)$/,
        loader: 'happypack/loader?id=happy_js_jsx',
        // loader: 'babel-loader',
        // exclude: [path.resolve(__dirname, 'node_modules')]//放开，里头有些也是 可选链操作符
      },
      {
        test: /\.(vue)$/,
        // loader: 'happypack/loader?id=happy-vue-loader'  ???不行，Make sure the rule matching .vue files include vue-loader in its use.
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../img/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/img/"		//生成之后存放的路径
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../img/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/media/"		//生成之后存放的路径
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../fonts/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/fonts/"		//生成之后存放的路径
        }
      }
    ]
  },

  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true
      }),
      new OptimizeCSSAssetsPlugin({
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true } }],
        },
        canPrint: false
      })
    ],
    runtimeChunk: {
      "name": "manifest"
    },
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: false,
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }

      }
    }
  },
  plugins: [
    new VueLoaderPlugin(),
    new HappyPack({
      id: 'happy_js_jsx',
      //共享进程池
      threadPool: happyThreadPool,
      loaders: ['babel-loader']
    }),
    // new HappyPack({
    //   id: 'happy-vue-loader',
    //   loaders: [{
    //     loader: 'vue-loader',
    //     options:vueLoaderConfig 
    //   }],
    //   threadPool: happyThreadPool
    // }),
    new webpack.HashedModuleIdsPlugin(),
    new ProgressBarPlugin(),
    // new CleanWebpackPlugin(['dist']),
    //注入全局变量的插件,通常使用该插件来判别代码运行的环境变量
    new webpack.DefinePlugin({
      'process.env': evnConfig
    }),
    new webpack.DllReferencePlugin({
      context: path.resolve(__dirname),
      manifest: require('../assets_platform/vendor_dll/vendor-manifest.json')
    }),
    //这个主要是将生成的vendor.dll.js文件加上hash值插入到页面中。[也可以手动写到html这里不做处理]
    // new AddAssetHtmlPlugin([{
    //   filepath: path.resolve(__dirname, 'js_dll/comm_vendors.dll.js'),
    //   outputPath: 'js_dll/',
    //   publicPath: 'js_dll/',
    //   includeSourcemap: false,
    //   hash: true,
    // }]),
    // new CopyWebpackPlugin([
    //   {
    //     from: path.resolve(__dirname, 'assets_platform'),
    //     to: path.resolve(__dirname, 'dist/assets_platform')
    //   },
    //   // {
    //   //   from: path.resolve(__dirname, 'js_dll'),
    //   //   to: path.resolve(__dirname, 'dist')
    //   // }
    // ])
  ]

};


