GitBucket
4.6.0
Toggle navigation
Sign in
Files
Branches
1
Tags
Issues
Pull Requests
Labels
Milestones
Wiki
08335
/
hivui-platform-template
hivui平台项目模板
Browse code
add 优化编译
master
1 parent
5ada6d3
commit
4538a72e1586293a284767cda5028fe0fb076581
caibinghong
authored
on 28 Jun 2022
Showing
2 changed files
build/webpack.get-list.js
build/webpack.prod.conf.js
Ignore Space
Show notes
View
build/webpack.get-list.js
var fsextra = require('fs-extra'); const path = require("path"); const glob = require('glob') // 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'); const projectName = packageConfig.name=='hi-vui-template'?'project':packageConfig.name // console.log('---------------------webpack.get-list.js------------', process.env.NODE_ENV) function repeat(array) { let map = new Map(); let array1 = []; // 数组用于返回结果 for (let i = 0, leng = array.length; i < leng; i++) { if (map.has(array[i])) { // 判断是否存在key map.set(array[i], true); } else { map.set(array[i], false); array1.push(array[i]); } } return array1; } // 用来记录当前打包的模块路径列表,判断进程参数 let argvs = (process.argv[2] || "").replace(/\s*$/g, "") let moduleList = []; let isBuildAll=true; if (argvs) { isBuildAll=false; moduleList = []; let list = argvs.split(','); for (let i = 0, l = list.length; i < l; i++) { // let checkPath = fs.existsSync(list[i]+'/package.json'); //如果目录存在 返回 true ,如果目录不存在 返回false // if (checkPath == false) continue; let modulePath = list[i]; let pathList = glob.sync(modulePath + '/package.json'); // 这个执行比较快 114.811ms if (pathList.length == 0) { // 查找modulePath目录 // let ls = glob.sync(`${modulePath}/!(dist|node_modules|build)/**/package.json`) // for (let k = 0, l = ls.length; k < l; k++) { // moduleList.push(ls[k].replace('/package.json', '')); // } if(modulePath=='./assets_platform'){ let res = modulePath.replace('./', ''); var isexist = fsextra.existsSync(path.resolve(__dirname, '../', res)); isexist&&fsextra.copy(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), function (err) { // ../project/AnNiu/res if (err){ return console.error('build_error:'+err) } else{ return console.log(res,"拷贝文件成功!") } }) //拷贝模块资源目录 }else if(/\/deploy\/desktop\/[\w,\/,\.]*\/dpdst\/[\w,\/,\.]*(\.json)$/.test(modulePath)){//服务部署环境配置的.json let buildScheme=fsextra.readJsonSync(path.resolve(__dirname, '../', modulePath)); let settingPath=path.resolve(__dirname, '../dist/',projectName+'/setting/desktop/appsetting.js') fsextra.copy(path.resolve(__dirname, '../', buildScheme.appSetting), settingPath, function (err) { if (err){ return console.error('build_error:'+err) } else{ return console.log(settingPath,"拷贝文件成功!") } }) //拷贝模块资源目录 }else{// if(/(\/res)$/.test(modulePath)) let res = modulePath.replace('./', ''); var isexist = fsextra.existsSync(path.resolve(__dirname, '../', res)); isexist&&fsextra.copy(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), function (err) { // ../project/AnNiu/res if (err){ return console.error('build_error:'+err) } else{ return console.log(res,"拷贝文件成功!") } }) //拷贝模块资源目录 }continue } else { moduleList.push(modulePath); } } } else { moduleList = require('./webpack.get-module').moduleList || []; } moduleList = repeat(moduleList); //去重 let evnConfig = require('./getEnvVar') let webpackList = [], resList = []; //构建webpack 配置 for (let i = 0, l = moduleList.length; i < l; i++) { let MODULE = moduleList[i]; if(isBuildAll){ //全部编译时拷资源文件res let res = MODULE.indexOf('/view') > -1 ? MODULE.split('view')[0] + '/res' : ''; if (res) { res = res.replace('./', ''); var isexist = fsextra.existsSync(path.resolve(__dirname, '../', res)); isexist&&fsextra.copy(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), function (err) { if (err) return console.error(err) }) //拷贝模块资源目录 } } //添加每个模块的webpack 配置 let MODULE_NAME = MODULE.split('/').pop(); let entry = {}; let outputPath = path.resolve(__dirname, '../dist', MODULE) entry[MODULE_NAME] = ['babel-polyfill', `${MODULE}/index.js`]; // @babel/polyfill let wpk = merge({ mode: 'production', // mode: 'development', // 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, './template.html') // } let pathList = glob.sync(htmlTemplate); // 这个执行比较快 114.811ms if (pathList.length == 0) htmlTemplate = path.resolve(__dirname, './template.html'); wpk.plugins.push(new CleanWebpackPlugin([outputPath], { root: path.resolve(__dirname, '../'), //根目录 //其他配置按需求添加 verbose: false, //不提示删除 })); 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
const path = require("path"); const glob = require('glob') // 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) function repeat(array) { let map = new Map(); let array1 = []; // 数组用于返回结果 for (let i = 0, leng = array.length; i < leng; i++) { if (map.has(array[i])) { // 判断是否存在key map.set(array[i], true); } else { map.set(array[i], false); array1.push(array[i]); } } return array1; } // 用来记录当前打包的模块路径列表,判断进程参数 let argvs = (process.argv[2] || "").replace(/\s*$/g, "") let moduleList = []; if (argvs) { moduleList = []; let list = argvs.split(','); for (let i = 0, l = list.length; i < l; i++) { // let checkPath = fs.existsSync(list[i]+'/package.json'); //如果目录存在 返回 true ,如果目录不存在 返回false // if (checkPath == false) continue; let pathList = glob.sync(list[i] + '/package.json'); // 这个执行比较快 114.811ms if (pathList.length == 0) { // 查找list[i]目录 let ls = glob.sync(`${list[i]}/!(dist|node_modules|build)/**/package.json`) for (let k = 0, l = ls.length; k < l; k++) { moduleList.push(ls[k].replace('/package.json','')); } continue } else { moduleList.push(list[i]); } } } else { moduleList = require('./webpack.get-module').moduleList || []; } moduleList = repeat(moduleList);//去重 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`]; // @babel/polyfill let wpk = merge({ mode: 'production', // mode: 'development', // 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, './template.html') // } let pathList = glob.sync(htmlTemplate); // 这个执行比较快 114.811ms if (pathList.length == 0) htmlTemplate = path.resolve(__dirname, './template.html'); wpk.plugins.push(new CleanWebpackPlugin([outputPath], { root: path.resolve(__dirname, '../'), //根目录 //其他配置按需求添加 verbose: false, //不提示删除 })); 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
Ignore Space
Show notes
View
build/webpack.prod.conf.js
// 多进程 编译所有 //parallel-webpack允许您并行运行多个Webpack构建,从而将工作分散到各个处理器上,从而有助于显着加快构建速度 // const os = require('os'); // const cpus = os.cpus().length; // console.log(cpus, ' Math.floor(cpus/2)||1', Math.floor(cpus / 2) || 1) const chalk = require('chalk') let webpack = require('webpack') let argvs = (process.argv[2] || "").replace(/\s*$/g, ""); let moduleList = argvs != "" ? argvs.split(',') : []; let isAllBuild = moduleList.length==0; let startTime = new Date().valueOf(); let webpackList = require('./webpack.get-list.js'); let moduleCount = webpackList.length; // 秒数转化为时分秒 function formatSeconds(value) { // 秒 let second = parseInt(value) // 分 let minute = 0 // 小时 let hour = 0 // 天 // let day = 0 // 如果秒数大于60,将秒数转换成整数 if (second > 60) { // 获取分钟,除以60取整数,得到整数分钟 minute = parseInt(second / 60) // 获取秒数,秒数取佘,得到整数秒数 second = parseInt(second % 60) // 如果分钟大于60,将分钟转换成小时 if (minute > 60) { // 获取小时,获取分钟除以60,得到整数小时 hour = parseInt(minute / 60) // 获取小时后取佘的分,获取分钟除以60取佘的分 minute = parseInt(minute % 60) // 如果小时大于24,将小时转换成天 // if (hour > 23) { // // 获取天数,获取小时除以24,得到整天数 // day = parseInt(hour / 24) // // 获取天数后取余的小时,获取小时除以24取余的小时 // hour = parseInt(hour % 24) // } } } let result = '' + parseInt(second) + '秒' if (minute > 0) { result = '' + parseInt(minute) + '分' + result } if (hour > 0) { result = '' + parseInt(hour) + '小时' + result } // if (day > 0) { // result = '' + parseInt(day) + '天' + result // } return result } let timerCtl = setInterval(function () { console.log(chalk.green(`正在编译中,目前已消耗 ${formatSeconds((new Date().valueOf() - startTime) / 1000)} ...`)) }, 1000 * 60 * 5); //----------- 【一般编译,按参数,一个接一个的】 --------------- function DoWebpackBuild(list, start, total, step = 1) { let wpkCfg, isEndAll = false; if (list == null || list.length == 0) { console.log(chalk.yellow(`没有模块可编译!`)); clearInterval(timerCtl); return; } wpkCfg = list.slice(start, start + step); if (wpkCfg == null || wpkCfg.length == 0) { isEndAll = true; clearInterval(timerCtl); console.log(chalk.green(`【总消耗】 ${formatSeconds((new Date().valueOf() - startTime) / 1000)}`)); return; } console.log('****************************************************************\n'); for(let i=0,l=wpkCfg.length;i<l;i++){ console.log(wpkCfg[i].output.path.split('dist')[1]); } if(step==1){ console.log(`【进度 ${start+1}/${total} 】,正在编译模块...\n`); }else{ console.log(`【进度 ${start+1}/${total} 】,正在编译${start+1} - ${total < step ? total : start + step}之间的模块...\n`); } console.log('****************************************************************\n'); let cmper = webpack(wpkCfg); let cmperStep = 5,cmperTotal=5; cmper.apply(new webpack.ProgressPlugin({ handler(percentage, message, ...args) { // console.log(args.length,'...args', args[0],'\n', args[1],'\n', args[2]) let t = (new Date().valueOf() - startTime) / 1000; if(t>cmperTotal){ cmperTotal+=cmperStep; // console.log(` 进度 : ${(percentage*100).toFixed(2)} %`)//,message // console.log(`{"progress":${percentage.toFixed(4)},"message":""}`); } // console.log(`{"progress":${percentage.toFixed(4)},"message":""}`); }, })); cmper.run((err, stats) => { //这个回调一定要写,不然打包不出来 if (err || stats.hasErrors()) {//编译错误不在 err 对象内,而是需要使用 stats.hasErrors() 单独处理 let info = {}; try { info = stats.toJson(); } catch (e) { info = { errors: [] }; console.log('stats.toJson()', err, stats) } // console.error(info.errors); for (let i = 0, l = info.errors.length; i < l; i++) { // console.log(chalk.red(info.errors[i].message)); // console.error(info.errors[i].message) console.error('build_error:'+info.errors[i]) } } // 处理完成 if (isEndAll) { cmperTotal = 10; clearInterval(timerCtl); console.log(chalk.green(`【总消耗】 ${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`)); } else { DoWebpackBuild(list, start + step, total, step); } }) } if (isAllBuild) { //-------- 【用parallel-webpack,全部编译情况下】 ------------ /* moduleList = require('./webpack.get-module').moduleList || []; console.log(`=========进入全模块编译状态(${moduleList.length})模块...=============`) var run = require('parallel-webpack').run; run( require.resolve('./webpack.get-list.js'), { watch: false, maxRetries: 1, stats: false, // defaults to false maxConcurrentWorkers: 1,// use 2 workers cup个数 argv: [argvs] }, ()=>{ //多打包时,如果其中一个模块出错,不知道是哪个模块 console.log('\n--------编译完成------- \n'); }); */ console.log(`【编译所有 共${moduleCount}】============搜索文件耗时:${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`) DoWebpackBuild(webpackList, 0, moduleCount);//, 0, len //以上两种时间上差不多 20s } else { console.log(`【按需编译 共${moduleCount}】============搜索文件耗时:${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`) DoWebpackBuild(webpackList, 0, moduleCount,1)//, 0, len }
// 多进程 编译所有 //parallel-webpack允许您并行运行多个Webpack构建,从而将工作分散到各个处理器上,从而有助于显着加快构建速度 // const os = require('os'); // const cpus = os.cpus().length; // console.log(cpus, ' Math.floor(cpus/2)||1', Math.floor(cpus / 2) || 1) const chalk = require('chalk') let webpack = require('webpack') let argvs = (process.argv[2] || "").replace(/\s*$/g, ""); let moduleList = argvs != "" ? argvs.split(',') : []; let isAllBuild = moduleList.length==0; let startTime = new Date().valueOf(); let webpackList = require('./webpack.get-list.js'); let moduleCount = webpackList.length; // 秒数转化为时分秒 function formatSeconds(value) { // 秒 let second = parseInt(value) // 分 let minute = 0 // 小时 let hour = 0 // 天 // let day = 0 // 如果秒数大于60,将秒数转换成整数 if (second > 60) { // 获取分钟,除以60取整数,得到整数分钟 minute = parseInt(second / 60) // 获取秒数,秒数取佘,得到整数秒数 second = parseInt(second % 60) // 如果分钟大于60,将分钟转换成小时 if (minute > 60) { // 获取小时,获取分钟除以60,得到整数小时 hour = parseInt(minute / 60) // 获取小时后取佘的分,获取分钟除以60取佘的分 minute = parseInt(minute % 60) // 如果小时大于24,将小时转换成天 // if (hour > 23) { // // 获取天数,获取小时除以24,得到整天数 // day = parseInt(hour / 24) // // 获取天数后取余的小时,获取小时除以24取余的小时 // hour = parseInt(hour % 24) // } } } let result = '' + parseInt(second) + '秒' if (minute > 0) { result = '' + parseInt(minute) + '分' + result } if (hour > 0) { result = '' + parseInt(hour) + '小时' + result } // if (day > 0) { // result = '' + parseInt(day) + '天' + result // } return result } let timerCtl = setInterval(function () { console.log(chalk.green(`正在编译中,目前已消耗 ${formatSeconds((new Date().valueOf() - startTime) / 1000)} ...`)) }, 1000 * 60 * 5); //----------- 【一般编译,按参数,一个接一个的】 --------------- function DoWebpackBuild(list, start, total, step = 1) { let wpkCfg, isEndAll = false; if (list == null || list.length == 0) { console.log(chalk.yellow(`没有模块可编译!`)); clearInterval(timerCtl); return; } wpkCfg = list.slice(start, start + step); if (wpkCfg == null || wpkCfg.length == 0) { isEndAll = true; clearInterval(timerCtl); console.log(chalk.green(`【总消耗】 ${formatSeconds((new Date().valueOf() - startTime) / 1000)}`)); return; } console.log('****************************************************************\n'); for(let i=0,l=wpkCfg.length;i<l;i++){ console.log(wpkCfg[i].output.path.split('dist')[1]); } if(step==1){ console.log(`【进度 ${start+1}/${total} 】,正在编译模块...\n`); }else{ console.log(`【进度 ${start+1}/${total} 】,正在编译${start+1} - ${total < step ? total : start + step}之间的模块...\n`); } console.log('****************************************************************\n'); let cmper = webpack(wpkCfg); let cmperStep = 5,cmperTotal=5; cmper.apply(new webpack.ProgressPlugin({ handler(percentage, message, ...args) { // console.log(args.length,'...args', args[0],'\n', args[1],'\n', args[2]) let t = (new Date().valueOf() - startTime) / 1000; if(t>cmperTotal){ cmperTotal+=cmperStep; // console.log(` 进度 : ${(percentage*100).toFixed(2)} %`)//,message console.log(`{"progress":${percentage.toFixed(4)},"message":""}`); } console.log(`{"progress":${percentage.toFixed(4)},"message":""}`); }, })); cmper.run((err, stats) => { //这个回调一定要写,不然打包不出来 if (err || stats.hasErrors()) {//编译错误不在 err 对象内,而是需要使用 stats.hasErrors() 单独处理 let info = {}; try { info = stats.toJson(); } catch (e) { info = { errors: [] }; console.log('stats.toJson()', err, stats) } // console.error(info.errors); for (let i = 0, l = info.errors.length; i < l; i++) { // console.log(chalk.red(info.errors[i].message)); // console.error(info.errors[i].message) console.error('build_error:'+info.errors[i]) } } // 处理完成 if (isEndAll) { cmperTotal = 10; clearInterval(timerCtl); console.log(chalk.green(`【总消耗】 ${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`)); } else { DoWebpackBuild(list, start + step, total, step); } }) } if (isAllBuild) { //-------- 【用parallel-webpack,全部编译情况下】 ------------ /* moduleList = require('./webpack.get-module').moduleList || []; console.log(`=========进入全模块编译状态(${moduleList.length})模块...=============`) var run = require('parallel-webpack').run; run( require.resolve('./webpack.get-list.js'), { watch: false, maxRetries: 1, stats: false, // defaults to false maxConcurrentWorkers: 1,// use 2 workers cup个数 argv: [argvs] }, ()=>{ //多打包时,如果其中一个模块出错,不知道是哪个模块 console.log('\n--------编译完成------- \n'); }); */ console.log(`【编译所有 共${moduleCount}】============搜索文件耗时:${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`) DoWebpackBuild(webpackList, 0, moduleCount);//, 0, len //以上两种时间上差不多 20s } else { console.log(`【按需编译 共${moduleCount}】============搜索文件耗时:${formatSeconds((new Date().valueOf() - startTime) / 1000)}\n`) DoWebpackBuild(webpackList, 0, moduleCount,1)//, 0, len }
Show line notes below