08335 / hivui-platform-template
hivui平台项目模板
Newer
Older
hivui-platform-template / build / oldWebpack / webpack3 / build.js
caibinghong on 29 Jun 2021 webpack5
'use strict'
require('./check-versions')()
const fs = require("fs")
const chalk = require('chalk')
const merge = require('webpack-merge')

process.env.NODE_ENV = 'production'
// 用来记录当前打包的模块路径列表
let moduleList = (process.argv[2] || "").replace(/\s*$/g, "")
if (moduleList == "") {
  moduleList = require('./module-conf').moduleList || []
} else {
  moduleList = moduleList.split(',')
}

// 如果有传参时,对传入的参数进行检测,如果参数非法,那么停止打包操作
const checkModule = require('./module-conf').checkModule
for (let i = moduleList.length - 1; i >= 0; i--) {
  if (!checkModule(moduleList[i])) {
    return
  }
}

const path = require('path')
// const ora = require('ora')
const rm = require('rimraf')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpackConfig = require('./webpack.base.conf')
let webpackList = [], rmList = [];

//删除文件
function getRm(pathStr) {
  return new Promise((resolve, reject) => {
    rm(pathStr, err => {
      if (err) {
        reject(pathStr + 'del failed!!');
        throw err;
      }
      resolve();
    });
  }).then(res => {
    //console.log(res)
  });
}

//构建webpack 配置
for (let i = moduleList.length - 1; i >= 0; i--) {
  let MODULE = moduleList[i];
  //构建时要删除的模块目录 
  rmList.push(getRm(path.resolve(__dirname, '../dist', MODULE)));
  //添加每个模块的webpack 配置
  let MODULE_NAME = MODULE.split('/').pop();
  let entry = {};
  entry[MODULE_NAME] = `${moduleList[i]}/index.js`;
  let wpk = merge({}, webpackConfig, {
    entry: entry,
    output: {
      path: path.resolve(__dirname, '../dist', MODULE)
    }
  });
  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 HtmlWebpackPlugin({
      filename: path.resolve(__dirname, '../dist', MODULE, 'index.html'),
      template: htmlTemplate,//如果html 不存在考虑用全局根目录下
      inject: true,
      // 这里要指定把哪些chunks追加到html中,默认会把所有入口的chunks追加到html中,这样是不行的
      chunks: ['vendor', 'manifest', 'elementUI', 'hiui', MODULE_NAME],
      minify: {
        removeComments: true,//去除注释
        collapseWhitespace: true,//是否去除空格
        removeAttributeQuotes: true//去除空属性
      },
      chunksSortMode: 'dependency',
      compile: true
    }))
  webpackList.push(wpk);
}

webpack(webpackList, (err, stats) => {
  if (err) throw err;
  if (stats.hasErrors()) {
    stats.stats.map(item => {
      item.compilation.errors.map(msg => {
        console.log(chalk.red(msg));
      })
    })
    // console.log(chalk.red('  Build failed with errors.\n'));
    process.exit(1);
  }
  // console.log(chalk.cyan('  Build complete.\n'));
});


return;