const path = require("path");
const fs = require("fs");
// const {Chalk} = require('chalk')
const merge = require('webpack-merge');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const baseWebpackConfig = require('./webpack.base.conf');

const packageConfig = require('../package.json');
console.log('---------------------webpack.get-list.js------------', process.env.NODE_ENV)

// 用来记录当前打包的模块路径列表，判断进程参数
let argvs = (process.argv[2] || "").replace(/\s*$/g, "")
let moduleList = require('./webpack.get-module').moduleList || [];
if(argvs){
  console.log('指定模块编译：')
  moduleList = argvs.split(',')
}


let evnConfig = require('./getEnvVar')

let webpackList = [];
//构建webpack 配置
for (let i = 0, l = moduleList.length; i < l; i++) {
  let MODULE = moduleList[i];
  // console.log(i, MODULE);
  //添加每个模块的webpack 配置
  let MODULE_NAME = MODULE.split('/').pop();
  let entry = {};
  let outputPath = path.resolve(__dirname, '../dist', MODULE)
  entry[MODULE_NAME] = ['babel-polyfill', `${MODULE}/index.js`];
  let wpk = merge({
    mode: 'production',
    // devtool: 'source-map',
  }, baseWebpackConfig, {
      entry: entry,
      output: {
        path: outputPath,
        filename: `static/js/[name].js`,
        // publicPath:'./'
        // publicPath: `/${evnConfig.VITE_APP_SERVER.replace(/"/gi,"")}/render/${packageConfig.author}/${MODULE.replace('./', '')}/`
        publicPath: `${evnConfig.VITE_APP_USERPATH.replace(/"/gi,"")}/${MODULE.replace('./', '')}/`
      }
    });
  let htmlTemplate = `${MODULE}/index.html`

  var checkPath = fs.existsSync(htmlTemplate);
  //如果目录存在 返回 true ，如果目录不存在 返回false
  if (checkPath == false) {
    htmlTemplate = path.resolve(__dirname, './index.html')
  }
  wpk.plugins.push(new CleanWebpackPlugin([outputPath], {
    root: path.resolve(__dirname, '../'),   //根目录
    //其他配置按需求添加
  }));
  wpk.plugins.push(
    new MiniCssExtractPlugin({
      filename: 'static/css/[name].[contenthash].css',
      chunkFilename: `static/css/[name].[contenthash].css`
    })
  );
  wpk.plugins.push(
    new HtmlWebpackPlugin({
      filename: path.resolve(__dirname, '../dist', MODULE, 'index.html'),
      template: htmlTemplate,//如果html 不存在考虑用全局根目录下
      inject: true,
      minify: {
        removeComments: true,//去除注释
        collapseWhitespace: true,//是否去除空格
        removeAttributeQuotes: true//去除空属性
      },
      compile: true
    }))
  webpackList.push(wpk);
}

module.exports = webpackList;// [webpackList[4]] ////[webpackList[3]];//27