vue 多项目

1. 项目结构

.
├── config                                      // 多项目webpack配置入口
├── ├── test1.js                                  // test1项目webpack配置
├── public                                      // 入口html文件
├── src
├── modules
├── ├── test1                                       // 项目test1
│   ├── ├── api                                       // api
│   ├── ├── assets                                    // 静态资源文件夹
│   │   ├── ├── img                                   // 图片
│   │   ├── ├── font                                  // 字体
│   ├── ├── components                  a              // 公共组件
│   │   ├── ├── layout                                // 页面布局相关组件
│   │   │   ├── ├── ...
│   ├── ├── utils                                     // 公用工具
│   ├── ├── router                                    // 路由
│   │   └── ├── router.js
│   ├── ├── store                                     // vuex
│   │   ├── ├── index.js
│   ├── ├── style
│   │    ├── ├── base.scss                             // 公共样式文件&样式初始化
│   │    ├── ├── element-variables.scss                // element ui 主题样式配置、
│   ├── ├── views                                      // 页面组件
│   │    ├── ├── ...
│   ├── ├── App.vue                                    // 页面入口文件
│   └── ├── main.js                                    // 程序入口文件,加载各种公共组件
├── ├── test2                                       // 项目test2
├── ├── ├── ...                                        // 同test1项目结构
.

2. config -> test1.js 配置

module.exports = {
	css: {
		modules: false,
		extract: true,
		sourceMap: false
	},
	publicPath: process.env.NODE_ENV === 'production' ? publicPath : './',
	outputDir: 'dist/workbench',
	productionSourceMap: false,
	devServer: {
		// host: '域名',
		port: 8100,
		open: true,
		// autoOpenBrowser: true,
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		proxy: {
			'/api': {
				target: 'http://baidu.com',
				secure: false,
				changeOrigin: true
			}
		}
	},
	pages: {
		index: {
			// page 的入口
			entry: 'src/modules/test1/main.js',
			// 模板来源
			template: 'public/index.html',
			// 在 dist index.html 的输出
			filename: 'index.html',
			// 当使用 title 选项时,
			// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
			title: '测试页面1',
			// 在这个页面中包含的块,默认情况下会包含
			// 提取出来的通用 chunk 和 vendor chunk。
			chunks: [
				'runtime',
				'chunk-vendors',
				'vue',
				'element-ui',
				'chunk-common',
				'app',
				'index'
			]
		},
	}
};

3. vue.config.js 配置

const path = require('path');
const fs = require('fs');
const TerserPlugin = require('terser-webpack-plugin');
// 获取要加载的模块参数  `module`
const argv = require('minimist')(process.argv.slice(2));
console.log('module----------------', argv); // { _: [ 'serve' ], module: 'test1' }
// 接收不了命令参数 默认 `demo`
argv.module = argv.module || 'demo'; // test1
// 导出配置 获取对应运行项目的webpack配置
let config = require(path.join(__dirname, './config', `${argv.module}.js`));
// 分支名称
let branch = '';
// 分支最新版本号
let branchVersion = '';
try {
	const gitHead = fs.readFileSync('.git/HEAD', 'utf-8').replace(/s+/g, '');
	branch = gitHead.split('refs/heads/')[1];
	branchVersion = fs
		.readFileSync(`./.git/${gitHead.split(':')[1]}`, 'utf-8')
		.replace(/s+/g, '');
	console.log(`${branch}
${branchVersion}`);
} catch (e) {
	console.log('分支信息获取失败
', e);
}
// 修改配置
config.chainWebpack = (con) => {
	//新增环境变量
	con.plugin('define').tap((args) => {
		// 当前git分支
		args[0]['process.env'].NODE_BRANCH = branch;
		// 当前git分支最新版本号
		args[0]['process.env'].NODE_BRANCH_VERSION = branchVersion;
		return args;
	});
};
config.configureWebpack = (con) => {
	let optimization = {
		// runtimeChunk: 'single',
		splitChunks: {
			chunks: 'all',
			// (缺省值5)按需加载时的最大并行请求数
			maxAsyncRequests: 5,
			// (默认值3)入口点上的最大并行请求数
			maxInitialRequests: 6,
			// (默认值:1)分割前共享模块的最小块数
			minChunks: 1,
			// (默认值:30000)块的最小大小
			minSize: 30000,
			// webpack 将使用块的起源和名称来生成名称: `vendors~main.js`,如项目与"~"冲突,则可通过此值修改,Eg: '-'
			automaticNameDelimiter: '-',
			// cacheGroups is an object where keys are the cache group names.
			name: true,
			cacheGroups: {
				default: false,
				vendors: {
					name: 'chunk-vendors',
					test: /[\/]node_modules[\/](?!(vue|element-ui))/,
					priority: 20,
					chunks: 'all'
				},
				vue: {
					name: 'vue',
					test: /[\/]node_modules[\/]vue/,
					chunks: 'all',
					// 默认组的优先级为负数,以允许任何自定义缓存组具有更高的优先级(默认值为0)
					priority: 10
				},
				elementUI: {
					name: 'element-ui',
					test: /[\/]node_modules[\/]element-ui[\/]/,
					chunks: 'all',
					// 默认组的优先级为负数,以允许任何自定义缓存组具有更高的优先级(默认值为0)
					priority: 5
				},
				common: {
					name: 'chunk-common',
					minChunks: 2,
					priority: 0,
					chunks: 'all',
					reuseExistingChunk: true
				}
			}
		}
	};
	// 打包去除console、debugger
	if (process.env.NODE_ENV === 'production') {
		const terserOptions = require('@vue/cli-service/lib/config/terserOptions');
		let opt = terserOptions(config);
		opt.terserOptions.compress.drop_console = true;
		optimization.minimizer = [new TerserPlugin(opt)];
	}
	// 分包配置载入
	con.optimization = optimization;
	// 乾坤微前端框架必备配置
	Object.assign(con.output, {
		// 把子应用打包成 umd 库格式
		library: `${argv.module}-[name]`,
		libraryTarget: 'umd',
		jsonpFunction: `webpackJsonp_${argv.module}`
	});
};
if (
	process.env.NODE_ENV === 'production' &&
	process.env.VUE_APP_ENV === 'stg' &&
	branch !== 'master'
) {
	// eslint-disable-next-line no-constant-condition

	if (config.publicPath) config.publicPath += branch + '/';
	config.outputDir += '/' + branch;
	console.log('publicPath:' + config.publicPath);
	console.log('outputDir:' + config.outputDir);
}
console.log(config.publicPath, config.outputDir);
module.exports = config;

4. package.json

scripts": {
  "serve": "vue-cli-service serve",
  "build": "vue-cli-service build",
  "serve:test1": "vue-cli-service serve --module test1",
  "build:test1": "vue-cli-service build --module test1",
  "build:test1:prd": "vue-cli-service build --mode prd --module test1",
},

5. 启动

npm run serve:test1

6. 期望结果

运行项目test1,如果运行test2,运行test2指令
原文地址:https://www.cnblogs.com/yzyh/p/14263104.html