Commit 885a7962 by Jaxon

Merge branch 'dev' of http://192.168.3.233:8090/monorepo/venus into feature/monorepo-config

2 parents 6de93c79 ec59299f
<script setup> <script setup>
import { onMounted, reactive, ref } from 'vue'; import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { GLButton } from '@venus/common-ui-vue'; import { GLButton } from "@venus/common-ui-vue";
import { assistantList, assistantStatus } from '@/api/assistant'; import { assistantList, assistantStatus } from '@/api/assistant';
import { findDeptTree } from '@/api/dept'; import { findDeptTree } from '@/api/dept';
import { ElMessage } from 'element-plus'; import { ElMessage } from 'element-plus';
...@@ -198,7 +198,10 @@ const handleCurrentChange = (val) => { ...@@ -198,7 +198,10 @@ const handleCurrentChange = (val) => {
<!-- <el-button class="search-btn w-[60px] h-8" @click="handleSearch">查询</el-button> <!-- <el-button class="search-btn w-[60px] h-8" @click="handleSearch">查询</el-button>
<el-button class="w-[60px] h-8" @click="handleReset">重置</el-button> --> <el-button class="w-[60px] h-8" @click="handleReset">重置</el-button> -->
<GLButton class="search-btn w-[60px] h-8" @click="handleSearch">查询</GLButton> <GLButton class="search-btn w-[60px] h-8" @click="handleSearch">查询</GLButton>
<GLButton class="w-[60px] h-8" @click="handleReset">重置-</GLButton> <GLButton class="w-[60px] h-8" @click="handleReset">重置</GLButton>
<GLButton>
普通按钮
</GLButton>
<!-- <div <!-- <div
class="search-btn-custom w-[60px] h-8 rounded-[5px] border border-[#8baefe] bg-white flex items-center justify-center cursor-pointer text-[#1956FE] transition-all duration-200" class="search-btn-custom w-[60px] h-8 rounded-[5px] border border-[#8baefe] bg-white flex items-center justify-center cursor-pointer text-[#1956FE] transition-all duration-200"
@click="handleSearch" @click="handleSearch"
......
import type { Plugin } from 'vite';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
...@@ -9,7 +12,38 @@ import qiankun from 'vite-plugin-qiankun'; ...@@ -9,7 +12,38 @@ import qiankun from 'vite-plugin-qiankun';
const PORT = 8081; const PORT = 8081;
const APP_NAME = 'assisant'; // 与基座配置的 name 一致 const APP_NAME = 'assisant'; // 与基座配置的 name 一致
// 获取源码路径
const commonUiSourcePath = resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
);
// 自定义插件:强制解析 @venus/common-ui-vue
function resolveWorkspacePackage(): Plugin {
return {
name: 'resolve-workspace-package',
enforce: 'pre', // 在其他插件之前执行
resolveId(id, importer) {
// 精确匹配包名
if (
id === '@venus/common-ui-vue' ||
id.startsWith('@venus/common-ui-vue/')
) {
// 验证文件是否存在
if (existsSync(commonUiSourcePath)) {
return {
id: commonUiSourcePath,
external: false,
};
}
console.warn(
`[resolve-workspace-package] 文件不存在: ${commonUiSourcePath}`,
);
}
return null;
},
};
}
export default defineConfig(({ mode, command }) => { export default defineConfig(({ mode, command }) => {
const isDev = mode === 'development'; const isDev = mode === 'development';
const isServe = command === 'serve'; const isServe = command === 'serve';
...@@ -19,6 +53,7 @@ export default defineConfig(({ mode, command }) => { ...@@ -19,6 +53,7 @@ export default defineConfig(({ mode, command }) => {
return { return {
base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径 base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径
plugins: [ plugins: [
resolveWorkspacePackage(),
vue(), vue(),
vueJsx(), vueJsx(),
// 自动导入 Vue 相关函数 // 自动导入 Vue 相关函数
...@@ -39,14 +74,30 @@ export default defineConfig(({ mode, command }) => { ...@@ -39,14 +74,30 @@ export default defineConfig(({ mode, command }) => {
}), }),
], ],
resolve: { resolve: {
alias: { alias: [
'@': resolve(__dirname, 'src'), {
'@public': resolve(__dirname, 'public'), find: '@',
replacement: resolve(__dirname, 'src'),
},
{
find: '@public',
replacement: resolve(__dirname, 'public'),
}, },
conditions: ['development', 'browser', 'import'], {
find: '@venus/common-ui-vue',
replacement: resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
),
},
],
// 设置条件导出优先使用 development
conditions: ['development', 'module', 'import', 'default'],
}, },
// 优化依赖预构建,排除 workspace 包
optimizeDeps: { optimizeDeps: {
exclude: ['jiti'], exclude: ['@venus/common-ui-vue', 'jiti'],
include: [],
}, },
server: { server: {
port: PORT, port: PORT,
......
...@@ -41,6 +41,63 @@ function initConfigReadyPromise() { ...@@ -41,6 +41,63 @@ function initConfigReadyPromise() {
* @returns 路由数据 * @returns 路由数据
*/ */
export async function fetchMicroAppRouteConfig(): Promise<any> { export async function fetchMicroAppRouteConfig(): Promise<any> {
if(baseConfig.features.defaultRoute.enabled){
return {
"code": 200,
"message": "success",
"data": {
"microApps": [
{
"name": "home",
"entry": {
"development": "",
"production": "",
"test": "",
"default": ""
},
"container": "#subapp-viewport",
"activeRule": "/home",
"props": {
"routerBase": "/home"
},
"enabled": true,
"routes": {
"path": "/home",
"name": "Home",
"title": "首页",
"level": 1,
"isMicroApp": false,
"requiresAuth": true
},
"routerList": {
"id": "home",
"title": "首页",
"path": "/home",
"icon": "",
"sidebarMenus": [
{
"id": "home-dashboard",
"title": "工作台",
"path": "/home/dashboard",
"icon": "",
"level": 2,
"hidden": false,
"parentId": "home",
"meta": {
"title": "工作台",
"icon": "dashboard",
"noCache": false,
"link": null
},
"children": []
}
]
}
}
]
}
};
}
// 先检查本地缓存 // 先检查本地缓存
const cachedData = localCache.get(ROUTER_CONFIG_CACHE_KEY); const cachedData = localCache.get(ROUTER_CONFIG_CACHE_KEY);
if (cachedData) { if (cachedData) {
...@@ -55,7 +112,6 @@ export async function fetchMicroAppRouteConfig(): Promise<any> { ...@@ -55,7 +112,6 @@ export async function fetchMicroAppRouteConfig(): Promise<any> {
if (result) { if (result) {
localCache.set(ROUTER_CONFIG_CACHE_KEY, result); localCache.set(ROUTER_CONFIG_CACHE_KEY, result);
} }
return result; return result;
} }
......
...@@ -11,7 +11,14 @@ let isConfigLoaded = false; ...@@ -11,7 +11,14 @@ let isConfigLoaded = false;
let configLoadPromise: Promise<void> | null = null; let configLoadPromise: Promise<void> | null = null;
// 默认配置(作为降级方案) // 默认配置(作为降级方案)
const defaultMicroApps: MicroAppConfig[] = []; const defaultMicroApps: MicroAppConfig[] = [
{
name: 'Home',
entry: '', // 主应用页面,无需 entry
container: '#subapp-viewport', // 微应用容器
activeRule: '/home', // 对应路由路径
},
];
/** /**
* 加载并设置微应用配置 * 加载并设置微应用配置
...@@ -32,15 +39,16 @@ export async function loadMicroAppConfig(): Promise<void> { ...@@ -32,15 +39,16 @@ export async function loadMicroAppConfig(): Promise<void> {
configLoadPromise = (async () => { configLoadPromise = (async () => {
try { try {
const remoteConfig = await fetchMicroAppRouteConfig(); const remoteConfig = await fetchMicroAppRouteConfig();
console.log('remoteConfigAAAAAA',JSON.stringify(remoteConfig));
// 获取子应用路由配置,并转换远程配置为 qiankun 配置( // 获取子应用路由配置,并转换远程配置为 qiankun 配置(
// props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa // props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa
microApps = transformToQiankun(remoteConfig.data?.microApps); microApps = transformToQiankun(remoteConfig.data?.microApps);
// 如果远程配置为空,使用默认配置 // 如果远程配置为空,使用默认配置
if (microApps.length === 0) { // if (config.features.defaultRoute.enabled) {
microApps = defaultMicroApps; // microApps = defaultMicroApps;
} // }
isConfigLoaded = true; isConfigLoaded = true;
console.log('[微前端配置] 配置加载完成,共加载', microApps.length, '个微应用'); console.log('[微前端配置] 配置加载完成,共加载', microApps, '个微应用');
} catch (error) { } catch (error) {
microApps = defaultMicroApps; microApps = defaultMicroApps;
isConfigLoaded = true; isConfigLoaded = true;
......
{
"code": 200,
"message": "success",
"data": {
"microApps": [
{
"name": "home",
"entry": {
"development": "",
"production": "",
"test": "",
"default": ""
},
"container": "#subapp-viewport",
"activeRule": "/home",
"props": {
"routerBase": "/home"
},
"enabled": true,
"routes": {
"path": "/home",
"name": "Home",
"title": "首页",
"level": 1,
"isMicroApp": false,
"requiresAuth": true
},
"routerList": {
"id": "home",
"title": "首页",
"path": "/home",
"icon": "",
"sidebarMenus": [
{
"id": "home-dashboard",
"title": "工作台",
"path": "/home/dashboard",
"icon": "",
"level": 2,
"hidden": false,
"parentId": "home",
"meta": {
"title": "工作台",
"icon": "dashboard",
"noCache": false,
"link": null
},
"children": []
}
]
}
}
]
}
}
...@@ -507,6 +507,9 @@ const handleDebounceClick = () => { ...@@ -507,6 +507,9 @@ const handleDebounceClick = () => {
<GLButton type="danger"> <GLButton type="danger">
危险按钮 危险按钮
</GLButton> </GLButton>
<GLButton>
普通按钮
</GLButton>
</div> </div>
</div> </div>
......
export { default, default as VButton } from "./index.vue"; export { default, default as VButton } from "./index.vue";
...@@ -2,156 +2,221 @@ ...@@ -2,156 +2,221 @@
* 自定义构建脚本 * 自定义构建脚本
* 功能: * 功能:
* 1. 清理根目录的 dist 文件夹 * 1. 清理根目录的 dist 文件夹
* 2. 构建指定的项目 * 2. 安装指定项目的依赖(智能检测)
* 3. 将构建产物复制到根目录的 dist 文件夹 * 3. 构建指定的项目
* 4. 将构建产物复制到根目录的 dist 文件夹
*/ */
import { execSync } from "node:child_process"; import { execSync } from "node:child_process";
import { existsSync, mkdirSync, rmSync } from "node:fs"; import { existsSync, mkdirSync, rmSync, statSync } from "node:fs";
import { copyFile, readdir } from "node:fs/promises"; import { copyFile, readdir, readFile } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
// 获取项目根目录 // 常量定义
const rootDir = process.cwd(); const rootDir = process.cwd();
const rootDistDir = join(rootDir, "dist"); const rootDistDir = join(rootDir, "dist");
const PACKAGE_SEARCH_PATHS = [
["apps", "web", "venus-agentic"],
["apps", "web"],
["apps", "frontend-micro"],
["apps", "frontend", "vue"],
["apps"],
["packages"],
["docs"],
];
// ==================== 构建配置开关 ====================
/** /**
* 清理根目录的 dist 文件夹 * 是否在构建前安装依赖
* - true: 启用依赖安装(默认,智能检测)
* - false: 跳过依赖安装步骤
*/ */
function cleanRootDist() { const ENABLE_INSTALL_DEPS = true;
console.log("🧹 清理根目录的 dist 文件夹...");
if (existsSync(rootDistDir)) {
rmSync(rootDistDir, { recursive: true, force: true });
console.log("✅ 根目录 dist 文件夹已清理");
} else {
console.log("ℹ️ 根目录 dist 文件夹不存在,跳过清理");
}
}
/** /**
* 构建指定的项目 * 是否强制安装依赖(仅在 ENABLE_INSTALL_DEPS 为 true 时生效)
* @param {string} packageName - 包名或过滤器 * - true: 强制重新安装依赖,跳过智能检测
* - false: 智能检测依赖是否需要安装(默认)
*/ */
function buildPackage(packageName) { const FORCE_INSTALL_DEPS = false;
console.log(`\n📦 开始构建项目: ${packageName}`); // ====================================================
try {
execSync(`pnpm --filter=${packageName} run build`, { // 公共执行配置
const execConfig = {
stdio: "inherit", stdio: "inherit",
cwd: rootDir, cwd: rootDir,
shell: true,
env: { env: {
...process.env, ...process.env,
NODE_OPTIONS: "--max-old-space-size=8192", NODE_OPTIONS: "--max-old-space-size=8192",
}, },
}); };
console.log(`✅ 项目构建完成: ${packageName}`);
} catch { /**
console.error(`❌ 项目构建失败: ${packageName}`); * 执行命令的统一封装
*/
function execCommand(command, errorMsg) {
try {
execSync(command, execConfig);
} catch (error) {
console.error(errorMsg);
console.error(`错误详情: ${error?.message || String(error)}`);
process.exit(1); process.exit(1);
} }
} }
/** /**
* 递归复制目录 * 清理根目录的 dist 文件夹
* @param {string} src - 源目录
* @param {string} dest - 目标目录
*/ */
async function copyDirectory(src, dest) { function cleanRootDist() {
// 确保目标目录存在 console.log("清理根目录的 dist 文件夹...");
if (!existsSync(dest)) { if (existsSync(rootDistDir)) {
mkdirSync(dest, { recursive: true }); rmSync(rootDistDir, { recursive: true, force: true });
} console.log("根目录 dist 文件夹已清理");
} else {
const entries = await readdir(src, { withFileTypes: true }); console.log("根目录 dist 文件夹不存在,跳过清理");
for (const entry of entries) {
const srcPath = join(src, entry.name);
const destPath = join(dest, entry.name);
await (entry.isDirectory() ? copyDirectory(srcPath, destPath) : copyFile(srcPath, destPath));
} }
} }
/** /**
* 查找包的路径 * 查找包的路径
* @param {string} packageName - 包名
* @returns {string|null} 包的路径
*/ */
async function findPackagePath(packageName) { async function findPackagePath(packageName) {
// 移除 @venus/ 前缀(如果有)
const cleanName = packageName.replace("@venus/", ""); const cleanName = packageName.replace("@venus/", "");
const nameVariants = [packageName, `@venus/${cleanName}`, cleanName];
// 可能的路径 for (const pathSegments of PACKAGE_SEARCH_PATHS) {
const possiblePaths = [ const packagePath = join(rootDir, ...pathSegments, cleanName);
join(rootDir, "apps", "frontend-micro", cleanName), if (!existsSync(packagePath)) continue;
join(rootDir, "apps", "frontend", "vue", cleanName),
join(rootDir, "apps", cleanName), const packageJsonPath = join(packagePath, "package.json");
join(rootDir, "packages", cleanName), if (!existsSync(packageJsonPath)) continue;
join(rootDir, "docs"),
];
// 尝试查找包
for (const path of possiblePaths) {
if (existsSync(path)) {
const packageJsonPath = join(path, "package.json");
if (existsSync(packageJsonPath)) {
try { try {
const packageJson = JSON.parse( const content = await readFile(packageJsonPath, "utf8");
await import("node:fs").then((fs) => fs.promises.readFile(packageJsonPath, "utf8")), const packageJson = JSON.parse(content);
); if (nameVariants.includes(packageJson.name)) {
// 检查包名是否匹配 return packagePath;
if ( }
packageJson.name === packageName || } catch {
packageJson.name === `@venus/${cleanName}` || // 忽略解析错误,继续查找
packageJson.name === cleanName
) {
return path;
} }
}
return null;
}
/**
* 检查是否需要安装依赖
*/
async function shouldInstallDeps(packageName) {
const packagePath = await findPackagePath(packageName);
if (!packagePath) return true;
const nodeModulesPath = join(packagePath, "node_modules");
if (!existsSync(nodeModulesPath)) return true;
const packageJsonPath = join(packagePath, "package.json");
const pnpmLockPath = join(rootDir, "pnpm-lock.yaml");
if (!existsSync(packageJsonPath) || !existsSync(pnpmLockPath)) return true;
try {
const [packageJsonTime, lockTime, nodeModulesTime] = [
statSync(packageJsonPath).mtime,
statSync(pnpmLockPath).mtime,
statSync(nodeModulesPath).mtime,
];
return packageJsonTime > nodeModulesTime || lockTime > nodeModulesTime;
} catch { } catch {
// 忽略 JSON 解析错误 return true;
} }
}
/**
* 安装指定项目的依赖
*/
async function installDeps(packageName, force = false) {
if (!force) {
console.log(`\n📥 检查依赖状态: ${packageName}`);
if (!(await shouldInstallDeps(packageName))) {
console.log("✅ 依赖已是最新,跳过安装");
return;
} }
} }
console.log(`\n📦 开始安装依赖: ${packageName}`);
execCommand(
`pnpm install --filter="${packageName}" --prefer-offline`,
`❌ 依赖安装失败: ${packageName}`,
);
console.log(`✅ 依赖安装完成: ${packageName}`);
}
/**
* 构建指定的项目
*/
function buildPackage(packageName) {
console.log(`\n📦 开始构建项目: ${packageName}`);
execCommand(
`pnpm --filter="${packageName}" run build`,
`❌ 项目构建失败: ${packageName}`,
);
console.log(`✅ 项目构建完成: ${packageName}`);
}
/**
* 递归复制目录
*/
async function copyDirectory(src, dest) {
if (!existsSync(dest)) {
mkdirSync(dest, { recursive: true });
} }
return null; for (const entry of await readdir(src, { withFileTypes: true })) {
const srcPath = join(src, entry.name);
const destPath = join(dest, entry.name);
await (entry.isDirectory() ? copyDirectory(srcPath, destPath) : copyFile(srcPath, destPath));
}
} }
/** /**
* 复制构建产物到根目录 * 复制构建产物到根目录
* @param {string} packageName - 包名
*/ */
async function copyBuildToRoot(packageName) { async function copyBuildToRoot(packageName) {
console.log(`\n📂 查找构建产物...`);
const packagePath = await findPackagePath(packageName); const packagePath = await findPackagePath(packageName);
if (!packagePath) { if (!packagePath) {
console.error(`❌ 无法找到包: ${packageName}`); console.error(`❌ 无法找到包: ${packageName}`);
process.exit(1); process.exit(1);
} }
console.log(`📍 包路径: ${packagePath}`);
const sourceDistDir = join(packagePath, "dist"); const sourceDistDir = join(packagePath, "dist");
if (!existsSync(sourceDistDir)) { if (!existsSync(sourceDistDir)) {
console.error(`❌ 构建产物不存在: ${sourceDistDir}`); console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
process.exit(1); process.exit(1);
} }
console.log(`\n📋 复制构建产物到根目录...`); console.log(`\n复制构建产物到根目录...`);
console.log(` 源目录: ${sourceDistDir}`); console.log(` 源目录: ${sourceDistDir}`);
console.log(` 目标目录: ${rootDistDir}`); console.log(` 目标目录: ${rootDistDir}`);
try { try {
await copyDirectory(sourceDistDir, rootDistDir); await copyDirectory(sourceDistDir, rootDistDir);
console.log("✅ 构建产物已复制到根目录的 dist 文件夹"); console.log("✅ 构建产物已复制到根目录的 dist 文件夹");
// 显示复制的文件统计
const files = await readdir(rootDistDir, { recursive: true });
console.log(`\n📊 共复制 ${files.length} 个文件`);
} catch (error) { } catch (error) {
console.error(`❌ 复制构建产物失败: ${error.message}`); console.error(`❌ 复制构建产物失败: ${error?.message || String(error)}`);
process.exit(1);
}
}
/**
* 验证根目录
*/
function validateRootDir() {
const workspaceFile = join(rootDir, "pnpm-workspace.yaml");
const rootPackageJson = join(rootDir, "package.json");
if (!existsSync(workspaceFile) && !existsSync(rootPackageJson)) {
console.error("❌ 错误:请在项目根目录执行此命令");
console.error(`当前目录: ${rootDir}`);
process.exit(1); process.exit(1);
} }
} }
...@@ -161,35 +226,32 @@ async function copyBuildToRoot(packageName) { ...@@ -161,35 +226,32 @@ async function copyBuildToRoot(packageName) {
*/ */
async function main() { async function main() {
const packageName = process.argv[2]; const packageName = process.argv[2];
if (!packageName) { if (!packageName) {
console.error("❌ 请指定要构建的项目名"); console.error("❌ 请指定要构建的项目名");
console.log("\n使用方法:");
console.log(" pnpm build:filter <package-name>");
console.log("\n示例:");
console.log(" pnpm build:filter @venus/venus-base");
console.log(" pnpm build:filter venus-micro-app");
process.exit(1); process.exit(1);
} }
console.log("🚀 开始自定义构建流程"); validateRootDir();
console.log(`📦 目标项目: ${packageName}\n`);
console.log("开始自定义构建流程");
// 1. 清理根目录 dist
cleanRootDist(); cleanRootDist();
// 2. 构建指定项目 if (ENABLE_INSTALL_DEPS) {
buildPackage(packageName); await installDeps(packageName, FORCE_INSTALL_DEPS);
} else {
console.log("跳过依赖安装步骤\n");
}
// 3. 复制构建产物到根目录 buildPackage(packageName);
await copyBuildToRoot(packageName); await copyBuildToRoot(packageName);
console.log("\n✨ 构建流程完成!"); console.log("\n✅ 构建流程完成!");
console.log(`📁 构建产物位置: ${rootDistDir}`); console.log(`📁 构建产物位置: ${rootDistDir}`);
} }
// 执行主函数 // 执行主函数
main().catch((error) => { main().catch((error) => {
console.error(`❌ 构建过程中出现错误: ${error.message}`); console.error(`构建过程中出现错误: ${error.message}`);
process.exit(1); process.exit(1);
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!