Commit 232dccee by Jaxon

fix: use sh for node options in lefthook

1 parent ffebac33
Showing 1000 changed files with 348 additions and 2535 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

...@@ -4,15 +4,14 @@ root = true ...@@ -4,15 +4,14 @@ root = true
charset=utf-8 charset=utf-8
end_of_line=lf end_of_line=lf
insert_final_newline=true insert_final_newline=true
indent_style=space indent_style=tab
indent_size=2 indent_size=4
max_line_length = 100
trim_trailing_whitespace = true trim_trailing_whitespace = true
quote_type = single quote_type = double
[*.{yml,yaml,json}] [*.{yml,yaml,json}]
indent_style = space indent_style = tab
indent_size = 2 indent_size = 4
[*.md] [*.md]
trim_trailing_whitespace = false trim_trailing_whitespace = false
ports:
- port: 5555
onOpen: open-preview
tasks:
- init: npm i -g corepack && pnpm install
command: pnpm run dev:play
# Husky Git Hooks
本目录包含项目的 Git hooks 配置,用于在不同的 Git 操作阶段自动执行检查。
## 配置的 Hooks
### pre-commit
在提交代码之前执行:
- 运行代码格式化 (`pnpm format`)
- 运行代码检查 (`pnpm lint`)
这确保了所有提交的代码都符合项目的代码规范。
### commit-msg
在提交信息创建后执行:
- 使用 commitlint 检查提交信息格式
这确保了所有提交信息都遵循约定式提交规范。
### pre-push
在推送代码到远程仓库之前执行:
- 运行类型检查 (`pnpm check:type`)
- 运行单元测试 (`pnpm test:unit`)
这确保了推送的代码通过了所有类型检查和测试。
## 如何跳过 Hooks
如果在特殊情况下需要跳过 hooks,可以使用以下命令:
```bash
# 跳过 pre-commit 和 commit-msg hooks
git commit --no-verify -m "commit message"
# 跳过 pre-push hooks
git push --no-verify
```
**注意**: 请谨慎使用 `--no-verify` 选项,它应该只在特殊情况下使用。
## 临时禁用 Husky
如果需要临时禁用 husky,可以设置环境变量:
```bash
# Windows (PowerShell)
$env:HUSKY=0
# Linux/Mac
export HUSKY=0
```
## 自定义 Hooks
如需添加或修改 hooks,直接编辑对应的文件即可。所有的 hook 文件都需要有执行权限。
#!/bin/sh
if [ "$LEFTHOOK_VERBOSE" = "1" -o "$LEFTHOOK_VERBOSE" = "true" ]; then
set -x
fi
if [ "$LEFTHOOK" = "0" ]; then
exit 0
fi
call_lefthook()
{
if test -n "$LEFTHOOK_BIN"
then
"$LEFTHOOK_BIN" "$@"
elif lefthook.exe -h >/dev/null 2>&1
then
lefthook.exe "$@"
elif lefthook.bat -h >/dev/null 2>&1
then
lefthook.bat "$@"
else
dir="$(git rev-parse --show-toplevel)"
osArch=$(uname | tr '[:upper:]' '[:lower:]')
cpuArch=$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x64/')
if test -f "$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe"
then
"$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/lefthook/bin/index.js"
then
"$dir/node_modules/lefthook/bin/index.js" "$@"
elif go tool lefthook -h >/dev/null 2>&1
then
go tool lefthook "$@"
elif bundle exec lefthook -h >/dev/null 2>&1
then
bundle exec lefthook "$@"
elif yarn lefthook -h >/dev/null 2>&1
then
yarn lefthook "$@"
elif pnpm lefthook -h >/dev/null 2>&1
then
pnpm lefthook "$@"
elif swift package lefthook >/dev/null 2>&1
then
swift package --build-path .build/lefthook --disable-sandbox lefthook "$@"
elif command -v mint >/dev/null 2>&1
then
mint run csjones/lefthook-plugin "$@"
elif uv run lefthook -h >/dev/null 2>&1
then
uv run lefthook "$@"
elif mise exec -- lefthook -h >/dev/null 2>&1
then
mise exec -- lefthook "$@"
elif devbox run lefthook -h >/dev/null 2>&1
then
devbox run lefthook "$@"
else
echo "Can't find lefthook in PATH"
fi
fi
}
call_lefthook run "commit-msg" "$@"
#!/bin/sh
if [ "$LEFTHOOK_VERBOSE" = "1" -o "$LEFTHOOK_VERBOSE" = "true" ]; then
set -x
fi
if [ "$LEFTHOOK" = "0" ]; then
exit 0
fi
call_lefthook()
{
if test -n "$LEFTHOOK_BIN"
then
"$LEFTHOOK_BIN" "$@"
elif lefthook.exe -h >/dev/null 2>&1
then
lefthook.exe "$@"
elif lefthook.bat -h >/dev/null 2>&1
then
lefthook.bat "$@"
else
dir="$(git rev-parse --show-toplevel)"
osArch=$(uname | tr '[:upper:]' '[:lower:]')
cpuArch=$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x64/')
if test -f "$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe"
then
"$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/lefthook/bin/index.js"
then
"$dir/node_modules/lefthook/bin/index.js" "$@"
elif go tool lefthook -h >/dev/null 2>&1
then
go tool lefthook "$@"
elif bundle exec lefthook -h >/dev/null 2>&1
then
bundle exec lefthook "$@"
elif yarn lefthook -h >/dev/null 2>&1
then
yarn lefthook "$@"
elif pnpm lefthook -h >/dev/null 2>&1
then
pnpm lefthook "$@"
elif swift package lefthook >/dev/null 2>&1
then
swift package --build-path .build/lefthook --disable-sandbox lefthook "$@"
elif command -v mint >/dev/null 2>&1
then
mint run csjones/lefthook-plugin "$@"
elif uv run lefthook -h >/dev/null 2>&1
then
uv run lefthook "$@"
elif mise exec -- lefthook -h >/dev/null 2>&1
then
mise exec -- lefthook "$@"
elif devbox run lefthook -h >/dev/null 2>&1
then
devbox run lefthook "$@"
else
echo "Can't find lefthook in PATH"
fi
fi
}
call_lefthook run "post-merge" "$@"
#!/bin/sh
if [ "$LEFTHOOK_VERBOSE" = "1" -o "$LEFTHOOK_VERBOSE" = "true" ]; then
set -x
fi
if [ "$LEFTHOOK" = "0" ]; then
exit 0
fi
call_lefthook()
{
if test -n "$LEFTHOOK_BIN"
then
"$LEFTHOOK_BIN" "$@"
elif lefthook.exe -h >/dev/null 2>&1
then
lefthook.exe "$@"
elif lefthook.bat -h >/dev/null 2>&1
then
lefthook.bat "$@"
else
dir="$(git rev-parse --show-toplevel)"
osArch=$(uname | tr '[:upper:]' '[:lower:]')
cpuArch=$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x64/')
if test -f "$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe"
then
"$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/lefthook/bin/index.js"
then
"$dir/node_modules/lefthook/bin/index.js" "$@"
elif go tool lefthook -h >/dev/null 2>&1
then
go tool lefthook "$@"
elif bundle exec lefthook -h >/dev/null 2>&1
then
bundle exec lefthook "$@"
elif yarn lefthook -h >/dev/null 2>&1
then
yarn lefthook "$@"
elif pnpm lefthook -h >/dev/null 2>&1
then
pnpm lefthook "$@"
elif swift package lefthook >/dev/null 2>&1
then
swift package --build-path .build/lefthook --disable-sandbox lefthook "$@"
elif command -v mint >/dev/null 2>&1
then
mint run csjones/lefthook-plugin "$@"
elif uv run lefthook -h >/dev/null 2>&1
then
uv run lefthook "$@"
elif mise exec -- lefthook -h >/dev/null 2>&1
then
mise exec -- lefthook "$@"
elif devbox run lefthook -h >/dev/null 2>&1
then
devbox run lefthook "$@"
else
echo "Can't find lefthook in PATH"
fi
fi
}
call_lefthook run "pre-commit" "$@"
#!/bin/sh
if [ "$LEFTHOOK_VERBOSE" = "1" -o "$LEFTHOOK_VERBOSE" = "true" ]; then
set -x
fi
if [ "$LEFTHOOK" = "0" ]; then
exit 0
fi
call_lefthook()
{
if test -n "$LEFTHOOK_BIN"
then
"$LEFTHOOK_BIN" "$@"
elif lefthook.exe -h >/dev/null 2>&1
then
lefthook.exe "$@"
elif lefthook.bat -h >/dev/null 2>&1
then
lefthook.bat "$@"
else
dir="$(git rev-parse --show-toplevel)"
osArch=$(uname | tr '[:upper:]' '[:lower:]')
cpuArch=$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x64/')
if test -f "$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe"
then
"$dir/node_modules/lefthook-${osArch}-${cpuArch}/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook/bin/lefthook-${osArch}-${cpuArch}/lefthook.exe" "$@"
elif test -f "$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe"
then
"$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook.exe" "$@"
elif test -f "$dir/node_modules/lefthook/bin/index.js"
then
"$dir/node_modules/lefthook/bin/index.js" "$@"
elif go tool lefthook -h >/dev/null 2>&1
then
go tool lefthook "$@"
elif bundle exec lefthook -h >/dev/null 2>&1
then
bundle exec lefthook "$@"
elif yarn lefthook -h >/dev/null 2>&1
then
yarn lefthook "$@"
elif pnpm lefthook -h >/dev/null 2>&1
then
pnpm lefthook "$@"
elif swift package lefthook >/dev/null 2>&1
then
swift package --build-path .build/lefthook --disable-sandbox lefthook "$@"
elif command -v mint >/dev/null 2>&1
then
mint run csjones/lefthook-plugin "$@"
elif uv run lefthook -h >/dev/null 2>&1
then
uv run lefthook "$@"
elif mise exec -- lefthook -h >/dev/null 2>&1
then
mise exec -- lefthook "$@"
elif devbox run lefthook -h >/dev/null 2>&1
then
devbox run lefthook "$@"
else
echo "Can't find lefthook in PATH"
fi
fi
}
call_lefthook run "prepare-commit-msg" "$@"
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 使用 commitlint 检查提交信息格式
npx --no -- commitlint --edit "$1"
# 运行代码格式化
pnpm format
# 运行 lint 检查
pnpm lint
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 运行类型检查
pnpm check:type
# 运行单元测试
pnpm test:unit
export default { export default {
"*.{js,ts,tsx,jsx,vue}": ["prettier --write", "eslint --fix"], "*.{js,ts,tsx,jsx,vue}": [ "prettier --write", "eslint --fix" ],
"*.{md,json,css,less,scss}": ["prettier --write"] "*.{md,json,css,less,scss}": [ "prettier --write" ]
}; };
...@@ -16,3 +16,12 @@ CODEOWNERS ...@@ -16,3 +16,12 @@ CODEOWNERS
public public
.npmrc .npmrc
*-lock.yaml *-lock.yaml
miniprogram_npm
uni_modules
# 只格式化 wxml
!*.wxml
!*.json
...@@ -2,3 +2,5 @@ dist ...@@ -2,3 +2,5 @@ dist
public public
__tests__ __tests__
coverage coverage
miniprogram_npm
uni_modules
...@@ -6,8 +6,8 @@ ...@@ -6,8 +6,8 @@
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
// Visual Studio Code 的官方 Stylelint 扩展 // Visual Studio Code 的官方 Stylelint 扩展
"stylelint.vscode-stylelint", "stylelint.vscode-stylelint",
// 使用 Prettier 的代码格式化程序 // // 使用 Prettier 的代码格式化程序
"esbenp.prettier-vscode", // "esbenp.prettier-vscode",
// 支持 dotenv 文件语法 // 支持 dotenv 文件语法
"mikestead.dotenv", "mikestead.dotenv",
// 源代码的拼写检查器 // 源代码的拼写检查器
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// workbench // workbench
"workbench.list.smoothScrolling": true, "workbench.list.smoothScrolling": true,
"workbench.startupEditor": "newUntitledFile", "workbench.startupEditor": "newUntitledFile",
"workbench.tree.indent": 10, "workbench.tree.indent": 24,
"workbench.editor.highlightModifiedTabs": true, "workbench.editor.highlightModifiedTabs": true,
"workbench.editor.closeOnFileDelete": true, "workbench.editor.closeOnFileDelete": true,
"workbench.editor.limit.enabled": true, "workbench.editor.limit.enabled": true,
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
"workbench.editor.limit.value": 5, "workbench.editor.limit.value": 5,
// editor // editor
"editor.tabSize": 2, "editor.tabSize": 4,
"editor.detectIndentation": false, "editor.detectIndentation": false,
"editor.cursorBlinking": "expand", "editor.cursorBlinking": "expand",
"editor.largeFileOptimizations": true, "editor.largeFileOptimizations": true,
...@@ -36,32 +36,41 @@ ...@@ -36,32 +36,41 @@
"source.fixAll.stylelint": "explicit", "source.fixAll.stylelint": "explicit",
"source.organizeImports": "never" "source.organizeImports": "never"
}, },
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "dbaeumer.vscode-eslint",
"[html]": { "[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[css]": { "[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[wxss]": {
"editor.defaultFormatter": "stylelint.vscode-stylelint"
},
"[scss]": { "[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[javascript]": { "[less]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[typescript]": { "[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[json]": { "[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[markdown]": { "[markdown]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[jsonc]": { "[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[vue]": { "[vue]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[wxml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
// extensions // extensions
...@@ -107,19 +116,23 @@ ...@@ -107,19 +116,23 @@
"**/.git/subtree-cache/**": true, "**/.git/subtree-cache/**": true,
"**/.vscode/**": true, "**/.vscode/**": true,
"**/node_modules/**": true, "**/node_modules/**": true,
"**/uni_modules/**": true,
"**/miniprogram_npm/**": true,
"**/tmp/**": true, "**/tmp/**": true,
"**/bower_components/**": true, "**/bower_components/**": true,
"**/dist/**": true, "**/dist/**": true,
"**/yarn.lock": true "**/yarn.lock": true
}, },
"typescript.tsserver.exclude": ["**/node_modules", "**/dist", "**/.turbo"], "typescript.tsserver.exclude": ["**/node_modules", "**/dist", "**/.turbo", "**/uni_modules", "**/miniprogram_npm"],
// search // search
"search.searchEditor.singleClickBehaviour": "peekDefinition", "search.searchEditor.singleClickBehaviour": "peekDefinition",
"search.followSymlinks": false, "search.followSymlinks": false,
// 在使用搜索功能时,将这些文件夹/文件排除在外 // 在使用搜索功能时,将这些文件夹/文件排除在外
"search.exclude": { "search.exclude": {
"**/uni_modules": true,
"**/miniprogram_npm":true,
"**/node_modules": true, "**/node_modules": true,
"**/*.log": true, "**/*.log": true,
"**/*.log*": true, "**/*.log*": true,
...@@ -146,7 +159,7 @@ ...@@ -146,7 +159,7 @@
}, },
"debug.onTaskErrors": "debugAnyway", "debug.onTaskErrors": "debugAnyway",
"diffEditor.ignoreTrimWhitespace": true, "diffEditor.ignoreTrimWhitespace": false,
"npm.packageManager": "pnpm", "npm.packageManager": "pnpm",
"css.validate": false, "css.validate": false,
...@@ -162,9 +175,11 @@ ...@@ -162,9 +175,11 @@
"stylelint.enable": true, "stylelint.enable": true,
"stylelint.packageManager": "pnpm", "stylelint.packageManager": "pnpm",
"stylelint.validate": ["css", "less", "postcss", "scss", "vue"], "stylelint.validate": ["css", "less", "postcss", "scss", "vue", "wxss"],
"stylelint.customSyntax": "postcss-html", "stylelint.snippet": ["css", "less", "postcss", "scss", "vue", "wxss"],
"stylelint.snippet": ["css", "less", "postcss", "scss", "vue"], "stylelint.reportInvalidScopeDisables": true,
"stylelint.reportNeedlessDisables": true,
"stylelint.runtimeEnvironment": "node",
"typescript.inlayHints.enumMemberValues.enabled": true, "typescript.inlayHints.enumMemberValues.enabled": true,
"typescript.preferences.preferTypeOnlyAutoImports": true, "typescript.preferences.preferTypeOnlyAutoImports": true,
...@@ -180,12 +195,13 @@ ...@@ -180,12 +195,13 @@
"markdown", "markdown",
"json", "json",
"jsonc", "jsonc",
"json5" "json5",
"wxml"
], ],
"tailwindCSS.experimental.classRegex": [ "eslint.format.enable": true,
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
], "tailwindCSS.experimental.classRegex": [["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]],
"github.copilot.enable": { "github.copilot.enable": {
"*": true, "*": true,
...@@ -217,9 +233,9 @@ ...@@ -217,9 +233,9 @@
"*.ts": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx, $(capture).d.ts", "*.ts": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx, $(capture).d.ts",
"*.tsx": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx,$(capture).d.ts", "*.tsx": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx,$(capture).d.ts",
"*.env": "$(capture).env.*", "*.env": "$(capture).env.*",
"README.md": "README*,CHANGELOG*,LICENSE,CNAME", "package.json": "pnpm-lock.yaml,pnpm-workspace.yaml,.npmrc,.browserslistrc,.node-version,.tazerc.json",
"package.json": "pnpm-lock.yaml,pnpm-workspace.yaml,.gitattributes,.gitignore,.gitpod.yml,.npmrc,.browserslistrc,.node-version,.git*,.tazerc.json", "eslint.config.mjs": ".editorconfig,.eslintignore,.prettierignore,.stylelintignore,.commitlintrc.*,.prettierrc.*,stylelint.config.*,.lintstagedrc.mjs,cspell.json",
"eslint.config.mjs": ".eslintignore,.prettierignore,.stylelintignore,.commitlintrc.*,.prettierrc.*,stylelint.config.*,.lintstagedrc.mjs,cspell.json,lefthook.yml", ".gitignore": ".gitconfig,.gitattributes",
"tailwind.config.mjs": "postcss.*" "tailwind.config.mjs": "postcss.*"
}, },
"commentTranslate.hover.enabled": false, "commentTranslate.hover.enabled": false,
...@@ -237,5 +253,5 @@ ...@@ -237,5 +253,5 @@
"nolebase", "nolebase",
"rollup", "rollup",
"vitest" "vitest"
] ],
} }
MIT License
Copyright (c) 2024-present, venus
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 🔧 快速修复指南
## 问题诊断
✅ **问题已确认**:`@venus/venus-agentic-base` 项目的 vite 依赖符号链接损坏
```
Error: Cannot find module '.../venus-agentic-base/node_modules/vite/bin/vite.js'
```
vite 文件夹存在但是空的!
## 🚀 解决方案(三选一)
### 方案 1:使用修复脚本(推荐,最简单)
在项目根目录执行:
```cmd
fix-dependencies.bat
```
### 方案 2:手动执行命令
```cmd
# 1. 进入问题项目目录
cd apps\frontend\venus-agentic\venus-agentic-base
# 2. 删除 node_modules
rmdir /s /q node_modules
# 3. 返回根目录
cd ..\..\..\..\
# 4. 重新安装所有依赖
pnpm install
```
### 方案 3:只重装问题项目
```cmd
pnpm --filter=@venus/venus-agentic-base install --force
```
## ✅ 验证修复
修复后执行:
```cmd
pnpm dev
```
选择 `@venus/venus-agentic-base`,应该能正常启动。
## 📊 预期结果
启动成功后会看到:
```
VITE v7.x.x ready in xxx ms
➜ Local: http://localhost:8080/
➜ Network: http://192.168.x.x:8080/
```
## 🔍 如果还有问题
### 检查 1:确认 vite 已正确安装
```cmd
cd apps\frontend\venus-agentic\venus-agentic-base\node_modules\vite\bin
dir
```
应该能看到 `vite.js` 文件。
### 检查 2:查看根目录的 vite
```cmd
cd node_modules\.pnpm
dir vite@* /s /b
```
应该能看到 vite 相关的包。
### 检查 3:完全清理重装(终极方案)
```cmd
# 删除所有 node_modules 和 lockfile
pnpm clean
del pnpm-lock.yaml
# 重新安装
pnpm install
```
## ⚠️ 常见原因
1. **pnpm 版本问题** - 升级 pnpm:`corepack use pnpm@latest`
2. **Windows 符号链接权限** - 以管理员身份运行终端
3. **磁盘空间不足** - 清理磁盘空间
4. **杀毒软件干扰** - 临时禁用杀毒软件
5. **路径过长** - 将项目移到较短的路径
## 📝 其他 apps 项目状态
✅ 正常项目:
- @venus/venus-base
- @venus/venus-micro-app
- @venus/docs
❌ 需要修复:
- @venus/venus-agentic-base (当前问题)
- @venus/venus-agentic-assisant (可能也需要检查)
## 💡 预防措施
1. 始终在项目根目录执行 `pnpm install`
2. 不要手动修改 node_modules
3. 使用 `pnpm store prune` 定期清理缓存
4. 提交代码时不要包含 node_modules
console.log("hello world");
// const test = 100;
// const duyia = 1000;
// console.log(duyia);
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"lib": ["ESNext"]
}
}
console.log("hello world");
window.addEventListener("DOMContentLoaded", () => {
console.log("DOMContentLoaded");
});
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>scrm-app-vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
{
"name": "scrm-app-vue",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 5174",
"build": "vue-tsc -b && vite build",
"preview": "vite preview --port 5174"
},
"dependencies": {
"vue": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vue/tsconfig": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:",
"vite-plugin-qiankun": "^1.0.15"
}
}
\ No newline at end of file \ No newline at end of file
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const global = ref<any>(null)
const msg = ref('')
onMounted(() => {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.onGlobalStateChange?.((s: any) => {
global.value = s
}, true)
})
function broadcast() {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ ...(global.value || {}), msg: msg.value })
}
</script>
<template>
<div style="padding: 24px">
<h2 style="margin-bottom: 12px;">SCRM 子应用(Vue)</h2>
<div style="display:flex; gap:12px; align-items:center; margin-bottom: 12px;">
<input
v-model="msg"
placeholder="向基座广播消息"
style="padding:6px; border:1px solid #ccc; border-radius:4px;"
/>
<button @click="broadcast" style="padding:6px 10px;">广播</button>
</div>
<div>当前全局消息:{{ global?.msg }}</div>
</div>
</template>
<style scoped></style>
\ No newline at end of file \ No newline at end of file
/*
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-11 15:39:04
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 19:17:19
* @FilePath: \venus\apps\frontend\micro-vue\scrm-app-vue\src\main.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { createApp } from 'vue'
import App from './App.vue'
let app: ReturnType<typeof createApp> | null = null
let mountEl: Element | null = null
function ensureContainerEl(container?: Element | null) {
if (!container) return document.getElementById('app')
const id = 'app'
let el = container.querySelector('#' + id)
if (!el) {
el = document.createElement('div')
el.id = id
container.appendChild(el)
}
return el
}
function render(props: any = {}) {
const { container } = props
mountEl = ensureContainerEl(container)
if (!mountEl) throw new Error('Micro app mount element not found')
// 若已存在旧实例(可能由 HMR 或重复挂载造成),先安全卸载并清空容器
if (app) {
try {
app.unmount()
} catch {}
;(mountEl as HTMLElement).innerHTML = ''
app = null
}
app = createApp(App)
app.mount(mountEl)
}
export async function bootstrap() {
// 可在此进行应用初始化逻辑
console.log("bootstrap");
}
export async function mount(props: any) {
console.log("mount",props);
return new Promise((resolve, reject) => {
// Always reject with an Error.
reject(new Error('hi'));
});
// render(props)
}
export async function unmount(_props: any) {
try {
app?.unmount()
} finally {
if (mountEl) {
// 清空容器,确保二次挂载不会触发 HMR 卸载异常
;(mountEl as HTMLElement).innerHTML = ''
}
app = null
mountEl = null
}
}
// 独立运行(本地开发直接访问)
if (!(window as any).__POWERED_BY_QIANKUN__) {
render()
}
\ No newline at end of file \ No newline at end of file
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
\ No newline at end of file \ No newline at end of file
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import qiankun from 'vite-plugin-qiankun'
// 子应用名称需与基座 registerMicroApps 中保持一致
const appName = 'scrm-app-vue'
export default defineConfig({
base: './',
plugins: [
vue(),
qiankun(appName, { useDevMode: true }),
],
server: {
port: 5174,
cors: true,
origin: 'http://localhost:5174',
},
})
\ No newline at end of file \ No newline at end of file
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>scrm-base</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "scrm-base",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"qiankun": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:",
"@venus/common-ui": "workspace:*",
"pinia": "catalog:",
"pinia-plugin-persistedstate": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vue/tsconfig": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:"
}
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
\ No newline at end of file \ No newline at end of file
<script setup lang="ts"></script>
<template>
<router-view />
</template>
<style scoped></style>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
\ No newline at end of file \ No newline at end of file
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
<script setup lang="ts">
import { ref } from 'vue'
import Topbar from './components/Topbar.vue'
import Sidebar from './components/Sidebar.vue'
import appsManifest from '../mfe/apps.json'
const collapsed = ref(false)
const keepAliveNames = appsManifest.apps.map(m => `Micro_${m.dir}`)
</script>
<template>
<div class="base-layout">
<Topbar @toggleSidebar="collapsed = !collapsed" />
<div class="layout-body">
<Sidebar :collapsed="collapsed" />
<main class="content">
<router-view v-slot="{ Component }">
<KeepAlive :include="keepAliveNames">
<component :is="Component" />
</KeepAlive>
</router-view>
</main>
</div>
</div>
</template>
<style scoped>
.base-layout {
height: 100vh;
display: flex;
flex-direction: column;
background: #f3f4f6;
}
.layout-body {
display: flex;
flex: 1;
min-height: 0;
}
.content {
flex: 1;
min-width: 0;
overflow: auto;
padding: 16px;
}
</style>
\ No newline at end of file \ No newline at end of file
<script setup lang="ts">
import appsManifest from '../../mfe/apps.json'
const props = defineProps<{ collapsed: boolean }>()
</script>
<template>
<aside :class="['sidebar', { collapsed: props.collapsed }]">
<div class="brand" title="SCRM">S</div>
<nav class="menu">
<router-link to="/">首页</router-link>
<div style="margin-top:8px;">
<div style="opacity:.8; font-size:12px; margin-bottom:6px;">子应用</div>
<div style="display:flex; flex-direction:column; gap:6px;">
<router-link
v-for="m in appsManifest.apps"
:key="m.dir"
:to="m.route"
>{{ m.displayName }}</router-link>
</div>
</div>
</nav>
</aside>
</template>
<style scoped>
.sidebar {
width: 240px;
min-width: 240px;
background: #111827;
color: #fff;
height: calc(100vh - 56px);
display: flex;
flex-direction: column;
}
.collapsed {
width: 64px;
min-width: 64px;
}
.brand {
height: 56px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
border-bottom: 1px solid #1f2937;
}
.menu {
padding: 8px 0;
}
.menu a {
display: block;
padding: 10px 16px;
color: #cbd5e1;
text-decoration: none;
}
.menu a.router-link-active {
background: #1f2937;
color: #fff;
}
</style>
\ No newline at end of file \ No newline at end of file
<script setup lang="ts">
import { useRouter } from 'vue-router'
const emit = defineEmits<{ (e: 'toggleSidebar'): void }>()
const router = useRouter()
function logout() {
localStorage.removeItem('token')
router.push('/login')
}
</script>
<template>
<header class="topbar">
<button class="icon-btn" @click="emit('toggleSidebar')">☰</button>
<div class="title">SCRM Base</div>
<div class="spacer" />
<div class="actions">
<button class="text-btn" @click="logout">退出</button>
</div>
</header>
</template>
<style scoped>
.topbar {
height: 56px;
display: flex;
align-items: center;
padding: 0 12px;
background: #ffffff;
border-bottom: 1px solid #e5e7eb;
}
.title {
font-weight: 600;
margin-left: 8px;
}
.spacer {
flex: 1;
}
.actions {
display: flex;
align-items: center;
gap: 8px;
}
.icon-btn {
width: 32px;
height: 32px;
border: 1px solid #e5e7eb;
background: #fff;
border-radius: 6px;
cursor: pointer;
}
.text-btn {
border: 1px solid #e5e7eb;
background: #fff;
border-radius: 6px;
padding: 6px 10px;
cursor: pointer;
}
.icon-btn:hover, .text-btn:hover { background: #f9fafb; }
</style>
\ No newline at end of file \ No newline at end of file
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index.ts'
// import { setupCommonUI } from '@venus/common-ui'
import { registerMicroApps, start, initGlobalState } from 'qiankun'
import appsManifest from './mfe/apps.json'
import pinia from './stores'
import { useAuthStore } from './stores/auth'
// import { usePermissionStore } from './stores/permission'
const app = createApp(App)
app.use(pinia)
app.use(router)
// setupCommonUI(app)
app.mount('#app')
// ------- qiankun 集成与全局状态通信 -------
const actions = initGlobalState({
user: { name: 'BaseUser' },
msg: '',
})
;(window as any).__QIANKUN_ACTIONS__ = actions
// 同步全局状态到 Pinia(在组件外使用 store,需要显式传入 pinia 实例)
const auth = useAuthStore(pinia)
// const perm = usePermissionStore(pinia)
actions.onGlobalStateChange((s: any) => {
auth.setFromGlobal(s.user, s.token)
// perm.setupByRoles(s.user?.roles || [])
}, true)
registerMicroApps(
appsManifest.apps.map((m) => ({
name: m.name,
entry: m.entry,
container: m.container,
// 按路由匹配激活,容器将在路由页面渲染后可用
activeRule: (location) => location.pathname.startsWith(m.route),
// 注入渲染所需的全局 actions
props: { actions: (window as any).__QIANKUN_ACTIONS__ },
}))
)
router.isReady().then(() => {
// 开发阶段关闭 sandbox,但开启资源预取以加快首次进入
start({
sandbox: false,
prefetch: true,
})
})
{
"apps": [
{
"name": "scrm-app-vue",
"dir": "scrm-app-vue",
"route": "/mfe/scrm-app-vue",
"container": "#mfe-scrm-app-vue",
"entry": "http://localhost:5174/",
"displayName": "scrm-app-vue"
}
]
}
\ No newline at end of file \ No newline at end of file
<!--
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-10 17:56:50
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 16:19:06
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\pages\Home.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import appsManifest from '../mfe/apps.json'
const text = ref('')
function handleClick() {
alert(`当前输入:${text.value || '(空)'}`)
}
// ------- 主应用 -> 子应用:通过 qiankun 全局状态广播 -------
const hostMsg = ref('')
const globalState = ref<any>(null)
onMounted(() => {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.onGlobalStateChange?.((s: any) => {
globalState.value = s
}, true)
})
// ------- 监听子应用挂载完成事件 -------
const lastMountedApp = ref('')
function handleMounted(e: any) {
const detail = e?.detail || {}
lastMountedApp.value = detail.appName || ''
}
onMounted(() => {
window.addEventListener('mfe:mounted', handleMounted as EventListener)
})
onBeforeUnmount(() => {
window.removeEventListener('mfe:mounted', handleMounted as EventListener)
})
function broadcastToMicro() {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ ...(globalState.value || {}), msg: hostMsg.value })
}
function syncUserToMicro() {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({
...(globalState.value || {}),
user: { name: 'HostUser', roles: ['admin'] },
})
}
</script>
<template>
<div style="padding: 24px">
<h2 style="margin-bottom: 12px;">示例:公共基础样式组件</h2>
<div style="display:flex; gap:12px; align-items:center;">
<VInput v-model="text" placeholder="请输入内容" style="max-width: 240px;" />
<VButton type="primary" @click="handleClick">提交</VButton>
</div>
<h2 style="margin: 24px 0 12px;">主应用向子应用广播示例</h2>
<div style="display:flex; gap:12px; align-items:center;">
<input
v-model="hostMsg"
placeholder="向子应用广播消息"
style="padding:6px; border:1px solid #ccc; border-radius:4px; max-width: 240px;"
/>
<button @click="broadcastToMicro" style="padding:6px 10px;">广播到子应用</button>
<button @click="syncUserToMicro" style="padding:6px 10px;">同步用户信息</button>
<span>当前全局消息:{{ globalState?.msg }}</span>
<span style="margin-left:8px;">子应用列表:</span>
<router-link
v-for="m in appsManifest.apps"
:key="m.dir"
:to="m.route"
style="margin-right:8px;"
>打开 {{ m.displayName }}</router-link>
<span v-if="lastMountedApp" style="margin-left:8px; color:#059669;">最近挂载:{{ lastMountedApp }}</span>
</div>
</div>
</template>
<style scoped></style>
\ No newline at end of file \ No newline at end of file
<!--
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-10 17:56:58
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 14:40:21
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\pages\Login.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const username = ref('')
const password = ref('')
function handleLogin() {
// 占位登录逻辑:设置一个 token 即视为登录成功
if (username.value && password.value) {
localStorage.setItem('token', 'mock-token')
router.push('/')
}
}
</script>
<template>
<div style="display:flex; align-items:center; justify-content:center; height:100vh;">
<div style="width:320px; padding:24px; border:1px solid #e5e7eb; border-radius:8px; background:#fff;">
<h2 style="margin:0 0 16px;">登录</h2>
<div style="display:flex; flex-direction:column; gap:12px;">
<input v-model="username" placeholder="用户名" style="padding:8px; border:1px solid #ccc; border-radius:4px;" />
<input v-model="password" type="password" placeholder="密码" style="padding:8px; border:1px solid #ccc; border-radius:4px;" />
<button @click="handleLogin" style="padding:10px; border:none; border-radius:4px; background:#646cff; color:#fff; cursor:pointer;">登录</button>
</div>
</div>
</div>
</template>
<style scoped></style>
\ No newline at end of file \ No newline at end of file
<!--
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-11 17:12:31
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 18:14:05
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\pages\MicroHost.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import appsManifest from '../mfe/apps.json'
const route = useRoute()
const meta = computed(() => {
return appsManifest.apps.find((a) => route.path.startsWith(a.route))
})
const containerId = computed(() => {
const c = meta.value?.container || ''
return c.startsWith('#') ? c.slice(1) : c || `mfe-${(route.path.split('/').pop() || '').trim()}`
})
const loading = ref(true)
let observer: MutationObserver | null = null
function checkReady(el: Element | null) {
if (!el) return
const appRoot = el.querySelector('#app')
if (appRoot && appRoot.childNodes.length > 0) {
loading.value = false
observer?.disconnect()
observer = null
}
}
onMounted(() => {
const el = document.getElementById(containerId.value)
if (!el) return
// 初次检查
checkReady(el)
// 监听容器变化以检测子应用挂载完成
observer = new MutationObserver(() => checkReady(el))
observer.observe(el, { childList: true, subtree: true })
// 自动注册模式下,qiankun 将根据 activeRule 与容器自动挂载
})
onBeforeUnmount(() => {
observer?.disconnect()
observer = null
// 自动注册模式下无需手动卸载
})
</script>
<template>
<div style="padding: 12px;">
<div style="margin-bottom: 8px; font-size: 12px; color: #6b7280;">
<span>当前子应用:</span>
<strong>{{ meta?.displayName || '未知' }}</strong>
<span style="margin-left:8px;">入口:</span>
<code>{{ meta?.entry || '-' }}</code>
<span style="margin-left:8px;">容器:</span>
<code>#{{ containerId }}</code>
</div>
<div v-if="loading" class="mfe-loading">子应用加载中…</div>
<div :id="containerId"></div>
</div>
</template>
<style scoped>
.mfe-loading {
padding: 8px 12px;
margin-bottom: 8px;
font-size: 13px;
color: #374151;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 4px;
}
</style>
\ No newline at end of file \ No newline at end of file
<!--
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-11 11:52:02
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 19:30:18
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\pages\ScrmApp.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const hostMsg = ref('')
const global = ref<any>(null)
onMounted(() => {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.onGlobalStateChange?.((s: any) => {
global.value = s
}, true)
})
function broadcast() {
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ ...(global.value || {}), msg: hostMsg.value })
}
</script>
<template>
<div>
<div style="margin-bottom:12px; display:flex; gap:8px; align-items:center;">
<input
v-model="hostMsg"
placeholder="向子应用广播消息"
style="padding:6px; border:1px solid #ccc; border-radius:4px;"
/>
<button @click="broadcast" style="padding:6px 10px;">广播</button>
<span>当前全局消息:{{ global?.msg }}</span>
</div>
<div id="mfe-scrm-app"></div>
</div>
</template>
<style scoped></style>
\ No newline at end of file \ No newline at end of file
/*
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-10 17:56:22
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 19:22:32
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\router\index.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import appsManifest from '../mfe/apps.json'
const routes: RouteRecordRaw[] = [
{
path: '/login',
name: 'Login',
component: () => import('../pages/Login.vue'),
},
{
path: '/',
component: () => import('../layout/BaseLayout.vue'),
meta: { requiresAuth: true },
children: [
{
path: '',
name: 'Home',
meta: { requiresAuth: true },
component: () => import('../pages/Home.vue'),
},
...appsManifest.apps.map((m) => ({
path: m.route,
name: `Micro_${m.dir}`,
meta: { requiresAuth: true },
component: () => import('../pages/MicroHost.vue'),
})),
],
},
]
const router = createRouter({
history: createWebHistory(),
routes,
})
router.beforeEach((to, _from, next) => {
const token = localStorage.getItem('token')
if (to.path === '/login') {
if (token) return next('/')
return next()
}
if (to.meta && (to.meta as any).requiresAuth && !token) {
return next('/login')
}
next()
})
export default router
\ No newline at end of file \ No newline at end of file
import { defineStore } from 'pinia'
export interface UserInfo {
id: string
name: string
roles: string[]
}
interface AuthState {
token: string | null
user: UserInfo | null
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
token: null,
user: null,
}),
getters: {
isAuthenticated: (s) => !!s.token,
roleSet: (s) => new Set(s.user?.roles || []),
},
actions: {
async login(username: string, password: string) {
if (!username || !password) return false
// Mock: 基于用户名设定角色
const roles = username === 'admin' ? ['admin'] : ['user']
this.token = 'mock-token'
this.user = { id: 'u-' + username, name: username, roles }
// 同步到 qiankun 全局态(如存在)
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ user: { name: username, roles }, token: this.token })
return true
},
logout() {
this.token = null
this.user = null
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ user: null, token: null })
},
setFromGlobal(user?: any, token?: string | null) {
if (typeof token !== 'undefined') this.token = token || null
if (user) {
const roles = Array.isArray(user.roles) ? user.roles : []
this.user = { id: 'global', name: user.name || 'User', roles }
}
},
},
persist: {
paths: ['token', 'user'],
},
})
\ No newline at end of file \ No newline at end of file
/*
* @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @Date: 2025-11-11 14:38:18
* @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
* @LastEditTime: 2025-11-11 15:22:33
* @FilePath: \venus\apps\frontend\micro-vue\scrm-base\src\stores\index.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { createPinia } from 'pinia'
import createPersistedState from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(createPersistedState)
export default pinia
\ No newline at end of file \ No newline at end of file
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
height: 100vh;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
})
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"types": [],
"lib": ["ESNext", "DOM"]
}
}
VITE_APP_VERSION=1.0.0
VITE_MICRO_APP_NAME=assisant
VITE_API_TIMEOUT=30000
VITE_BASE_URL=/assisant
VITE_ROUTER_BASE=/assisant
VITE_USE_MOCK=false
VITE_DEBUG=true
# Vue3 微前端子应用模板
> 基于 qiankun + Vue3 + Vite + TypeScript 构建的微前端子应用模板
## 📋 目录
- [功能特性](#功能特性)
- [技术栈](#技术栈)
- [快速开始](#快速开始)
- [项目结构](#项目结构)
- [与基座联调](#与基座联调)
- [配置说明](#配置说明)
- [开发指南](#开发指南)
## ✨ 功能特性
- 🚀 **快速启动** - 使用 Vite 构建,HMR 响应迅速
- 🎯 **独立运行** - 支持独立开发和集成运行两种模式
- 🔧 **开箱即用** - 集成路由、状态管理、自动导入等功能
- 💡 **TypeScript** - 完整的类型支持,开发更安全
- 🎨 **现代化 UI** - 精心设计的用户界面和交互体验
- 🔌 **qiankun 集成** - 完整实现 qiankun 生命周期钩子
## 🛠️ 技术栈
- **Vue 3** - 渐进式 JavaScript 框架
- **TypeScript** - 类型安全的 JavaScript 超集
- **Vite** - 新一代前端构建工具
- **Vue Router** - 官方路由管理器
- **Pinia** - 新一代状态管理库
- **qiankun** - 微前端框架
- **vite-plugin-qiankun** - Vite 的 qiankun 插件
## 🚀 快速开始
### 安装依赖
```bash
pnpm install
```
### 启动开发服务器
```bash
pnpm dev
```
访问 `http://localhost:8081` 即可查看应用(独立运行模式)
### 构建生产版本
```bash
pnpm build
```
### 预览生产构建
```bash
pnpm preview
```
## 📁 项目结构
```
micro-app-template/
├── src/
│ ├── views/ # 页面组件
│ │ ├── Home.vue # 首页
│ │ ├── About.vue # 关于页
│ │ ├── User.vue # 用户管理
│ │ ├── Settings.vue # 系统设置
│ │ └── NotFound.vue # 404 页面
│ ├── router/ # 路由配置
│ │ └── index.ts # 路由定义
│ ├── App.vue # 根组件
│ ├── main.ts # 入口文件(包含 qiankun 生命周期)
│ └── style.css # 全局样式
├── index.html # HTML 模板
├── vite.config.ts # Vite 配置(qiankun 集成)
├── tsconfig.json # TypeScript 配置
├── package.json # 项目配置
└── README.md # 项目文档
```
## 🔗 与基座联调
### ⚠️ 重要提示
在启动前,请确保配置正确(已在本次更新中修复):
**子应用配置检查:**
- ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/`
- ✅ `src/router/index.ts` - 导出 `createRouter` 函数
- ✅ `src/main.ts` - 动态创建路由实例
**基座配置检查:**
- ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081`
- ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>`
### 1. 启动子应用
```bash
cd apps/frontend-micro/micro-app-template
pnpm dev
```
子应用会在 `http://localhost:8081` 启动
**验证:**
- 访问 `http://localhost:8081` 应显示子应用
- 控制台显示 "独立运行模式"
### 2. 启动基座应用
```bash
cd apps/frontend-micro/scrm-base
pnpm dev
```
基座会在 `http://localhost:8080` 启动
**验证:**
- 控制台显示 "[qiankun] 微前端框架已启动"
### 3. 在基座中访问子应用
访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用
**预期结果:**
- 看到子应用内容(紫色渐变背景)
- 控制台显示生命周期日志
- 运行模式显示 "🔗 基座模式"
**详细测试步骤:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
## ⚙️ 配置说明
### 修改子应用端口
在 `vite.config.ts` 中修改 `PORT` 常量:
```typescript
const PORT = 8081; // 修改为你想要的端口
```
### 修改子应用名称
1. 在 `vite.config.ts` 中修改 `APP_NAME`:
```typescript
const APP_NAME = 'your-app-name';
```
2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置:
```typescript
{
name: 'your-app-name',
entry: '//localhost:8081',
container: '#subapp-container',
activeRule: '/your-app-name',
props: {
routerBase: '/your-app-name',
},
}
```
### 路由配置
子应用路由会自动添加基座传递的 `routerBase` 前缀。在独立运行时,路由base为 `/`;在基座中运行时,路由base为基座配置的 `routerBase`(如 `/subapp-vue`)。
## 📝 开发指南
### 独立开发模式
子应用支持完全独立开发,无需启动基座:
```bash
pnpm dev
```
访问 `http://localhost:8081` 进行开发调试
### 集成开发模式
需要测试与基座的集成时:
1. 启动子应用:`pnpm dev`
2. 启动基座:在 scrm-base 目录执行 `pnpm dev`
3. 通过基座访问:`http://localhost:8080/subapp-vue`
### qiankun 生命周期说明
子应用实现了以下 qiankun 生命周期钩子:
- `bootstrap` - 应用初始化,只执行一次
- `mount` - 应用挂载,每次进入都会执行
- `unmount` - 应用卸载,每次离开都会执行
- `update` - 应用更新(可选),主应用下发新 props 时触发
### 环境判断
使用以下方式判断应用是否在 qiankun 环境中运行:
```typescript
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('在基座中运行');
} else {
console.log('独立运行');
}
```
## 🔍 常见问题
### 1. 子应用无法加载(白屏)
**原因:**
- 子应用未启动
- entry 地址配置错误
- 容器 ID 不存在
**解决:**
```bash
# 确认子应用运行
curl http://localhost:8081
# 检查基座配置
# scrm-base/src/qiankun/apps.ts
entry: 'http://localhost:8081' // ✅ 使用完整 URL
# 检查容器存在
# scrm-base/src/views/MicroApp.vue
<div id="subapp-container"></div> // ✅ 必须存在
```
### 2. CORS 错误
**控制台显示:**
```
Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
```
**解决:**
- 确认子应用 `vite.config.ts` 中 `cors: true`
- 确认 headers 配置正确
- 重启子应用服务
### 3. 路由跳转异常
**原因:**
- 路由 base 配置错误
- `routerBase` 未正确传递
**解决:**
```typescript
// ✅ 已修复:子应用动态创建路由
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? (props.routerBase || '/subapp-vue')
: '/';
const router = createRouter(routerBase);
```
### 4. 样式冲突
- qiankun 默认开启了样式隔离
- 建议使用 scoped 样式
- 可以在基座的 `start` 配置中调整样式隔离策略
### 5. 生命周期未触发
**原因:**
- 应用名称不一致
- 生命周期钩子未正确导出
**解决:**
```typescript
// vite.config.ts
qiankun('subapp-vue') // 必须与基座配置一致
// main.ts
export async function bootstrap() { }
export async function mount(props) { }
export async function unmount(props) { }
```
**详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
## 📄 License
MIT
## 🤝 贡献
欢迎提交 Issue 和 Pull Request!
# **APP_NAME**
该项目由 Venus CLI 脚手架生成,使用 Vite + Vue 3 + TypeScript。
# 子应用使用 GSC Request 指南
## 概述
子应用可以通过基座下发的 GSC Request 实例来发起请求,无需重复配置。所有请求都会使用基座从配置中心获取的统一配置。
## 快速开始
### 1. 在组件中使用(推荐方式)
#### 方式一:使用封装的工具函数(最简单)
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { gscPost, gscGet } from '@/utils/gscRequest';
import { ElMessage } from 'element-plus';
const loading = ref(false);
const data = ref(null);
// 发起 POST 请求
const fetchData = async () => {
try {
loading.value = true;
const response = await gscPost('/api/data', {
name: 'test',
page: 1,
});
data.value = response;
ElMessage.success('获取数据成功');
} catch (error) {
console.error('请求失败:', error);
ElMessage.error('获取数据失败');
} finally {
loading.value = false;
}
};
// 发起 GET 请求
const getUserInfo = async () => {
try {
const response = await gscGet('/user/info');
console.log('用户信息:', response);
} catch (error) {
console.error('获取用户信息失败:', error);
}
};
onMounted(() => {
fetchData();
});
</script>
<template>
<div>
<el-button :loading="loading" @click="fetchData">获取数据</el-button>
<pre>{{ data }}</pre>
</div>
</template>
```
#### 方式二:使用全局属性(在 Options API 中)
```vue
<script>
export default {
data() {
return {
loading: false,
data: null,
};
},
methods: {
async fetchData() {
try {
this.loading = true;
// 通过全局属性访问
const request = await this.$gscRequest.getRequest();
const response = await request.post('/api/data', { name: 'test' });
this.data = response;
} catch (error) {
console.error('请求失败:', error);
} finally {
this.loading = false;
}
},
},
mounted() {
this.fetchData();
},
};
</script>
```
#### 方式三:直接获取 Request 实例(高级用法)
```vue
<script setup lang="ts">
import { onMounted } from 'vue';
import { getGscRequest } from '@/utils/gscRequest';
onMounted(async () => {
try {
const request = await getGscRequest();
// 直接使用 request 实例的所有方法
const response = await request.post('/api/data', {});
console.log('响应:', response);
} catch (error) {
console.error('请求失败:', error);
}
});
</script>
```
### 2. 在 API 文件中使用
创建 `src/api/user.ts`:
```typescript
import { gscPost, gscGet } from '@/utils/gscRequest';
/**
* 用户登录
*/
export async function login(username: string, password: string) {
return gscPost('/login', {
username,
password,
});
}
/**
* 获取用户信息
*/
export async function getUserInfo() {
return gscGet('/user/info');
}
/**
* 更新用户信息
*/
export async function updateUserInfo(data: any) {
return gscPost('/user/update', data);
}
```
在组件中使用:
```vue
<script setup lang="ts">
import { login, getUserInfo } from '@/api/user';
const handleLogin = async () => {
try {
const response = await login('admin', '123456');
console.log('登录成功:', response);
} catch (error) {
console.error('登录失败:', error);
}
};
</script>
```
### 3. 带配置的请求
```typescript
import { gscPost } from '@/utils/gscRequest';
// 带配置的 POST 请求
const response = await gscPost(
'/api/data',
{ name: 'test' },
{
returnAll: true, // 返回完整响应(包括 headers 等)
timeout: 10000, // 超时时间(毫秒)
},
);
```
## 完整示例
### 示例:在列表页面中使用
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { gscPost, gscGet } from '@/utils/gscRequest';
import { ElMessage, ElMessageBox } from 'element-plus';
interface ListItem {
id: number;
name: string;
status: boolean;
}
const loading = ref(false);
const tableData = ref<ListItem[]>([]);
const searchForm = ref({
name: '',
status: '',
});
// 获取列表数据
const fetchList = async () => {
try {
loading.value = true;
const response = await gscPost('/api/list', {
...searchForm.value,
page: 1,
pageSize: 10,
});
tableData.value = response.data || [];
} catch (error) {
console.error('获取列表失败:', error);
ElMessage.error('获取列表失败');
} finally {
loading.value = false;
}
};
// 删除数据
const handleDelete = async (id: number) => {
try {
await ElMessageBox.confirm('确定要删除这条数据吗?', '提示', {
type: 'warning',
});
await gscPost('/api/delete', { id });
ElMessage.success('删除成功');
await fetchList(); // 刷新列表
} catch (error) {
if (error !== 'cancel') {
console.error('删除失败:', error);
ElMessage.error('删除失败');
}
}
};
// 更新状态
const handleStatusChange = async (id: number, status: boolean) => {
try {
await gscPost('/api/updateStatus', { id, status });
ElMessage.success('状态更新成功');
} catch (error) {
console.error('更新状态失败:', error);
ElMessage.error('更新状态失败');
}
};
onMounted(() => {
fetchList();
});
</script>
<template>
<div>
<el-table :data="tableData" :loading="loading">
<el-table-column prop="name" label="名称" />
<el-table-column prop="status" label="状态">
<template #default="{ row }">
<el-switch
:model-value="row.status"
@change="(val) => handleStatusChange(row.id, val)"
/>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="{ row }">
<el-button
type="danger"
size="small"
@click="handleDelete(row.id)"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
```
## 错误处理
### 基本错误处理
```typescript
import { gscPost } from '@/utils/gscRequest';
try {
const response = await gscPost('/api/data', {});
// 处理成功响应
} catch (error) {
// 处理错误
if (error instanceof Error) {
console.error('错误信息:', error.message);
}
// 可以根据错误类型进行不同处理
}
```
### 统一错误处理(推荐)
创建 `src/utils/requestErrorHandler.ts`:
```typescript
import { ElMessage } from 'element-plus';
export function handleRequestError(error: any) {
if (error?.response) {
// HTTP 错误
const status = error.response.status;
switch (status) {
case 401:
ElMessage.error('未授权,请重新登录');
// 可以跳转到登录页
break;
case 403:
ElMessage.error('没有权限访问');
break;
case 404:
ElMessage.error('请求的资源不存在');
break;
case 500:
ElMessage.error('服务器错误');
break;
default:
ElMessage.error(error.response.data?.message || '请求失败');
}
} else if (error?.message) {
// 其他错误
ElMessage.error(error.message);
} else {
ElMessage.error('网络错误,请稍后重试');
}
}
```
使用:
```typescript
import { gscPost } from '@/utils/gscRequest';
import { handleRequestError } from '@/utils/requestErrorHandler';
const fetchData = async () => {
try {
const response = await gscPost('/api/data', {});
return response;
} catch (error) {
handleRequestError(error);
throw error;
}
};
```
## 注意事项
1. **环境检查**:GSC Request 只在 qiankun 环境中可用,独立运行时无法使用
2. **异步初始化**:Request 实例是异步获取的,确保在使用前已初始化
3. **错误处理**:建议对所有请求添加错误处理
4. **类型安全**:虽然使用了类型断言,但实际运行时 Request 实例确实有 post/get 等方法
## 与基座 API 的对比
基座应用中的使用方式:
```typescript
// 基座:config/gscrequest.ts
import gscPost from '@/config/gscrequest';
const response = await gscPost('/api/data', {});
```
子应用中的使用方式:
```typescript
// 子应用:utils/gscRequest.ts
import { gscPost } from '@/utils/gscRequest';
const response = await gscPost('/api/data', {});
```
**使用方式完全一致!** 这样可以保持代码风格统一。
## 常见问题
### Q: 为什么在独立运行时无法使用?
A: GSC Request 实例是通过基座的配置中心获取的,只有在 qiankun 环境中才能通过 props 获取。独立运行时需要自己配置请求工具。
### Q: 如何判断 Request 是否已初始化?
A: 使用 `gscRequestManager.isInitialized()` 方法:
```typescript
import { gscRequestManager } from '@/utils/gscRequest';
if (gscRequestManager.isInitialized()) {
// Request 已初始化,可以安全使用
}
```
### Q: 请求失败时如何获取详细错误信息?
A: 错误对象中通常包含 `response` 属性,可以从中获取详细信息:
```typescript
try {
await gscPost('/api/data', {});
} catch (error: any) {
console.error('状态码:', error.response?.status);
console.error('错误信息:', error.response?.data);
console.error('请求配置:', error.config);
}
```
// / <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
// qiankun 相关类型
declare global {
interface Window {
__INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
__POWERED_BY_QIANKUN__?: boolean;
}
}
export {};
<!doctype html>
<html lang="zh-CN" sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<meta name="description" content="" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "@venus/venus-agentic-assisant",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
"postbuild": "node ../../../../scripts/copy-dist-to-root.mjs",
"preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vue-office/docx": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/excel": "catalog:",
"@js-preview/excel": "catalog:",
"@vue-office/pptx": "catalog:",
"@js-preview/pdf": "catalog:",
"@js-preview/docx": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@venus/tailwind-config": "workspace:*",
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"axios": "catalog:",
"element-plus": "catalog:",
"pinia": "catalog:",
"tailwindcss": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:",
"glsk-oss-jssdk": "catalog:",
"sass": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:"
}
}
export { default } from '@venus/tailwind-config/postcss';
<script setup lang="ts">
import { onMounted } from 'vue';
onMounted(() => {
// console.log('Vue3 微应用已挂载');
});
</script>
<template>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</main>
</template>
<style scoped>
.app-main {
flex: 1;
}
/* 路由过渡动画 */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
import { gscPost} from '@/utils/gscRequest';
/**
* 质检规则列表查询
*/
export async function inspectionRuleList(data: any) {
try {
const response = await gscPost('/inspectionRule/findPageInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则新增
*/
export async function addInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/addInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则列表修改
*/
export async function updateInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/updateInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则列表删除
*/
export async function deleteInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/deleteInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版列表查询
*/
export async function inspectionTemplateList(data: any) {
try {
const response = await gscPost('/inspectionTemplate/findPageInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版新增
*/
export async function addInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/saveInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版修改
*/
export async function updateInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/updateInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版删除
*/
export async function deleteInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/deleteInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体列表查询
*/
export async function trainingPlanList(data: any) {
try {
const response = await gscPost('/trainingPlan/findPageTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体新增
*/
export async function addTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/addTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体修改
*/
export async function updateTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/updateTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体删除
*/
export async function deleteTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/deleteTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体详情
*/
export async function ftrainingPlanDetail(data: any) {
try {
const response = await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
return response;
} catch (error) {
throw error;
}
}
/**
* 通用知识分类列表
*/
export async function generalKnowledgeList(data: any) {
try {
const response = await gscPost('/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList', data);
return response;
} catch (error) {
throw error;
}
}
/*
* 复盘智能体提示词模板查询
*/
export async function getPromptTemplate(data: any) {
try {
const response = await gscPost('/reviewAgentPromptTemplate/findPromptTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/*
* 复盘智能体提示词模板更新
*/
export async function updatePromptTemplate(data: any) {
try {
const response = await gscPost('/reviewAgentPromptTemplate/updatePromptTemplate', data);
return response;
} catch (error) {
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 岗位助理列表
*/
export async function assistantList(data: any) {
try {
const response = await gscPost('/jobAgentInfo/findPageAgentInfo', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理详情
*/
export async function assistantDetail(data: any) {
try {
const response = await gscPost('/jobAgentDetail/detailById', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理创建
*/
export async function assistantCreate(data: any) {
try {
const response = await gscPost('/jobAgentInfo/create', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理更新
*/
export async function assistantUpdate(data: any) {
try {
const response = await gscPost('/jobAgentInfo/update', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理状态修改
*/
export async function assistantStatus(data: any) {
try {
const response = await gscPost('/jobAgentInfo/forbiddenOrEnable', data);
return response;
} catch (error) {
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 企微部门模块树
*/
export async function findDeptTree(data: any) {
try {
const response = await gscPost('/entmicroDepartment/findDeptTree', data);
return response;
} catch (error) {
throw error;
}
}
/**
* API 使用示例
* 展示如何在子应用中使用 GSC Request 发起请求
*/
import { gscPost, gscGet } from '@/utils/gscRequest';
/**
* 示例:用户登录
*/
export async function login(username: string, password: string) {
try {
const response = await gscPost('/login', {
username,
password,
});
return response;
} catch (error) {
console.error('登录失败:', error);
throw error;
}
}
/**
* 示例:获取用户信息
*/
export async function getUserInfo() {
try {
const response = await gscGet('/user/info');
return response;
} catch (error) {
console.error('获取用户信息失败:', error);
throw error;
}
}
/**
* 示例:带配置的 POST 请求
*/
export async function createData(data: any) {
try {
const response = await gscPost(
'/api/data',
data,
{
returnAll: true, // 返回完整响应
timeout: 10000, // 超时时间
},
);
return response;
} catch (error) {
console.error('创建数据失败:', error);
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 素材分组列表
*/
export async function findCategoryList(data: any) {
try {
const response = await gscPost('/knowledgeCategory/findCategoryList', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 素材分组新增
*/
export async function addCategory(data: any) {
try {
const response = await gscPost('/knowledgeCategory/addCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材分组修改
*/
export async function updateCategory(data: any) {
try {
const response = await gscPost('/knowledgeCategory/updateCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 分组列表包含的素材列表
*/
export async function findCategoryWithMaterialList(data: any) {
try {
const response = await gscPost('/knowledgeCategory/findCategoryWithMaterialList', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 素材列表
*/
export async function findPageKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/findPageKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材编辑
*/
export async function updateKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/updateKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材上传
*/
export async function saveKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/saveKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材删除
*/
export async function deleteKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/deleteKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!