1 Commits

Author SHA1 Message Date
严浩
0678a88131 f
Some checks failed
CI/CD Pipeline / playwright (push) Successful in 2m0s
CI/CD Pipeline / build-and-deploy (push) Failing after 1m30s
2025-12-10 11:30:16 +08:00
60 changed files with 1684 additions and 2160 deletions

View File

@@ -1,31 +1,65 @@
{
"image": "ghcr.io/yanhao98/h-devcontainer:main",
"runArgs": [
"--hostname=devcontainer-host",
"--name=${localWorkspaceFolderBasename}-devcontainer"
],
"forwardPorts": [4730, 4731, 5901],
"runArgs": ["--name=${localWorkspaceFolderBasename}-devcontainer"],
"forwardPorts": [4730, 4731], // vscode://settings/remote.localPortHost -> 默认只监听 localhost
"portsAttributes": {
"4730": { "label": "开发服务器端口", "onAutoForward": "notify" },
"4731": { "label": "预览服务器端口", "onAutoForward": "notify" }
},
"remoteEnv": {
"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}",
"ANTHROPIC_BASE_URL": "${localEnv:ANTHROPIC_BASE_URL}",
"GEMINI_API_KEY": "${localEnv:GEMINI_API_KEY}",
"GOOGLE_GEMINI_BASE_URL": "${localEnv:GOOGLE_GEMINI_BASE_URL}"
},
"containerEnv": {
"NODE_OPTIONS": "--max-old-space-size=4096",
"TZ": "${localEnv:TZ:Asia/Shanghai}"
},
"customizations": {
"vscode": {
"extensions": ["prettier.prettier-vscode", "vue.volar"],
"extensions": [
// AI
"github.copilot-chat",
"anthropic.claude-code",
"google.gemini-cli-vscode-ide-companion",
"vicanent.gcmp",
// >>>>>
// "eamodio.gitlens",
"tu6ge.naive-ui-intelligence",
"gruntfuggly.todo-tree",
"lokalise.i18n-ally",
"vitest.explorer",
"antfu.unocss",
"vue.volar",
// <<<<<
// 代码质量 / 格式化 / Lint
"dbaeumer.vscode-eslint",
"stylelint.vscode-stylelint",
"oxc.oxc-vscode",
"esbenp.prettier-vscode"
],
"settings": {
// "tasks": { "version": "2.0.0", "tasks": [] },
"github.copilot.chat.codeGeneration.instructions": [
{
"text": "This dev container includes a lightweight Fluxbox based desktop that can be accessed using a VNC viewer or the web. GUI-based commands executed from the built-in VS Code terminal will open on the desktop automatically."
}
]
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"chat.extensionUnification.enabled": true,
"chat.tools.terminal.autoApprove": {
"/.*/": true,
"git push": false
},
// * 尽管使用了“/.*/”,但有些还是会失败,因为有几个错误的默认值:
// * https://github.com/microsoft/vscode/issues/266651#issuecomment-3292581459
"chat.tools.terminal.ignoreDefaultAutoApproveRules": true,
"tasks": { "version": "2.0.0", "tasks": [] },
"terminal.integrated.defaultProfile.linux": "zsh"
}
}
},
"mounts": [
// 不挂载还可能会遇到:`Cannot run macOS (Mach-O) executable in Docker: Exec format error`
"source=${localWorkspaceFolderBasename}-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume",
"source=${localWorkspaceFolder}/.devcontainer/lifecycle-scripts.d,target=/usr/local/etc/lifecycle-scripts.d,type=bind,consistency=delegated"
],
@@ -35,5 +69,7 @@
"updateContentCommand": "/usr/local/bin/run-lifecycle-scripts.sh updateContentCommand",
"postCreateCommand": "/usr/local/bin/run-lifecycle-scripts.sh postCreateCommand",
"postStartCommand": "/usr/local/bin/run-lifecycle-scripts.sh postStartCommand",
"postAttachCommand": "/usr/local/bin/run-lifecycle-scripts.sh postAttachCommand"
"postAttachCommand": "/usr/local/bin/run-lifecycle-scripts.sh postAttachCommand",
"waitFor": "updateContentCommand",
"remoteUser": "usr_vscode"
}

View File

@@ -0,0 +1,13 @@
#!/bin/zsh -eu
# 打印带有颜色的欢迎信息
echo -e "\033[1;32m↘ 容器首次创建!\033[0m"
# 修复权限问题(比如 node_modules 目录)
sudo chown -R $(whoami):$(whoami) /workspaces || true
# 调用内置命令 (这些命令在 _build-context/builtin-scripts 目录中的脚本中定义)
h-setup-locale
h-setup-zsh
h-setup-bun-bin
h-setup-pnpm-bin

View File

@@ -0,0 +1,13 @@
#!/bin/bash -eu
# 容器内容更新时的消息和依赖安装
echo '↘️ 容器内容已更新!'
# 安装依赖
if command -v pnpm >/dev/null 2>&1; then
# 跳过: The modules directory at "/workspaces/h-devcontainers/node_modules" will be removed and reinstalled from scratch. Proceed? (Y/n) ·
time pnpm install --config.confirmModulesPurge=false
else
echo '❌错误: pnpm 未安装'
exit 0
fi

View File

@@ -1,14 +0,0 @@
#!/bin/zsh -eu
h-setup-zh-locale
h-setup-bun-bin
h-setup-pnpm-bin
h-setup-chromium
h-setup-desktop-lite
h-install-node-modules
echo "-----------------------------"
echo "开发容器已启动并配置完成!"
echo "-----------------------------"

View File

@@ -14,7 +14,7 @@ on:
jobs:
playwright:
runs-on: ubuntu-latest
container: mcr.microsoft.com/playwright:v1.57.0-noble
container: mcr.microsoft.com/playwright:v1.56.1-noble
steps:
- name: ⚙️ 设置 Node 环境
uses: yanhao98/composite-actions/setup-node-environment@faab20ac2f9c85dfce1a4147fca493bf632bd744

View File

@@ -60,7 +60,7 @@ jobs:
playwright:
runs-on: ubuntu-latest
container: mcr.microsoft.com/playwright:v1.57.0-noble
container: mcr.microsoft.com/playwright:v1.56.1-noble
steps:
- uses: actions/checkout@main
with:

View File

@@ -1,3 +0,0 @@
# VS Code 搜索忽略
pnpm-lock.yaml

View File

@@ -4,6 +4,5 @@
"tabWidth": 2,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all",
"plugins": ["@prettier/plugin-oxc"]
"trailingComma": "all"
}

View File

@@ -5,7 +5,7 @@
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode",
"prettier.prettier-vscode",
"esbenp.prettier-vscode",
"stylelint.vscode-stylelint",
"lokalise.i18n-ally"
]

50
.vscode/settings.json vendored
View File

@@ -1,54 +1,29 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.preferences.autoImportFileExcludePatterns": [
"vue-router$",
"**/src/composables/**",
"**/*-auto-imports.ts",
"**/*-auto-imports.types.ts"
],
"search.exclude": {
"public/report-ui-dist": true
},
// ============================================================
// 代码格式化相关配置
// ============================================================
"prettier.enable": true,
"files.readonlyInclude": {
"dist/**": true
},
"eslint.enable": true,
"oxc.enable": true,
"stylelint.enable": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.fixAll.eslint": "explicit",
"source.fixAll.oxc": "explicit",
"source.fixAll.stylelint": "explicit",
"source.organizeImports": "explicit"
"source.fixAll.oxc": "explicit",
"source.organizeImports": "never"
},
"eslint.enable": true,
"stylelint.enable": true,
"oxc.enable": true,
"editor.formatOnSave": true,
"stylelint.validate": ["css", "less", "postcss", "scss", "vue"],
"scss.lint.unknownAtRules": "ignore",
"css.lint.unknownAtRules": "ignore",
"less.lint.unknownAtRules": "ignore",
"editor.defaultFormatter": "prettier.prettier-vscode",
"[typescript]": {
"editor.defaultFormatter": "prettier.prettier-vscode"
},
"[vue]": {
"editor.defaultFormatter": "prettier.prettier-vscode"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "prettier.prettier-vscode"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "prettier.prettier-vscode"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// ============================================================
// i18n-ally 配置
// ============================================================
"editor.defaultFormatter": "esbenp.prettier-vscode",
// >>>>>
"i18n-ally.readonly": false,
"i18n-ally.namespace": false /* @intlify/unplugin-vue-i18n */,
@@ -59,7 +34,10 @@
"i18n-ally.enabledParsers": ["json"],
"i18n-ally.keystyle": "nested",
"i18n-ally.sourceLanguage": "zh-CN", // 翻译源语言 (源文件) 根据此语言文件翻译其他语言文件的变量和内容
"i18n-ally.displayLanguage": "zh-CN" // 显示语言 (显示文件/翻译文件)
"i18n-ally.displayLanguage": "zh-CN", // 显示语言 (显示文件/翻译文件)
// <<<<<
// https://github.com/copilot/share/8a1a019a-0180-80e7-8141-a40be02c4006
// "iconify.customCollectionJsonPaths": ["https://example.com/my-icons.json", "./local/icons.json"],
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.preferences.autoImportFileExcludePatterns": ["vue-router/auto$"]
}

6
auto-imports.d.ts vendored
View File

@@ -42,7 +42,6 @@ declare global {
const debouncedWatch: typeof import('@vueuse/core').debouncedWatch
const deepFreeze: typeof import('deep-freeze-es6').default
const defineAsyncComponent: typeof import('vue').defineAsyncComponent
const defineBasicLoader: typeof import('unplugin-vue-router/data-loaders/basic').defineBasicLoader
const defineComponent: typeof import('vue').defineComponent
const defineStore: typeof import('pinia').defineStore
const eagerComputed: typeof import('@vueuse/core').eagerComputed
@@ -65,6 +64,7 @@ declare global {
const isRef: typeof import('vue').isRef
const isShallow: typeof import('vue').isShallow
const makeDestructurable: typeof import('@vueuse/core').makeDestructurable
const manualResetRef: typeof import('@vueuse/core').manualResetRef
const mapActions: typeof import('pinia').mapActions
const mapGetters: typeof import('pinia').mapGetters
const mapState: typeof import('pinia').mapState
@@ -222,6 +222,7 @@ declare global {
const useIntervalFn: typeof import('@vueuse/core').useIntervalFn
const useKeyModifier: typeof import('@vueuse/core').useKeyModifier
const useLastChanged: typeof import('@vueuse/core').useLastChanged
const useLink: typeof import('vue-router/auto').useLink
const useLoadingBar: typeof import('naive-ui').useLoadingBar
const useLocalStorage: typeof import('@vueuse/core').useLocalStorage
const useMagicKeys: typeof import('@vueuse/core').useMagicKeys
@@ -387,7 +388,6 @@ declare module 'vue' {
readonly debouncedWatch: UnwrapRef<typeof import('@vueuse/core')['debouncedWatch']>
readonly deepFreeze: UnwrapRef<typeof import('deep-freeze-es6')['default']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineBasicLoader: UnwrapRef<typeof import('unplugin-vue-router/data-loaders/basic')['defineBasicLoader']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly defineStore: UnwrapRef<typeof import('pinia')['defineStore']>
readonly eagerComputed: UnwrapRef<typeof import('@vueuse/core')['eagerComputed']>
@@ -410,6 +410,7 @@ declare module 'vue' {
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly isShallow: UnwrapRef<typeof import('vue')['isShallow']>
readonly makeDestructurable: UnwrapRef<typeof import('@vueuse/core')['makeDestructurable']>
readonly manualResetRef: UnwrapRef<typeof import('@vueuse/core')['manualResetRef']>
readonly mapActions: UnwrapRef<typeof import('pinia')['mapActions']>
readonly mapGetters: UnwrapRef<typeof import('pinia')['mapGetters']>
readonly mapState: UnwrapRef<typeof import('pinia')['mapState']>
@@ -567,6 +568,7 @@ declare module 'vue' {
readonly useIntervalFn: UnwrapRef<typeof import('@vueuse/core')['useIntervalFn']>
readonly useKeyModifier: UnwrapRef<typeof import('@vueuse/core')['useKeyModifier']>
readonly useLastChanged: UnwrapRef<typeof import('@vueuse/core')['useLastChanged']>
readonly useLink: UnwrapRef<typeof import('vue-router/auto')['useLink']>
readonly useLoadingBar: UnwrapRef<typeof import('naive-ui')['useLoadingBar']>
readonly useLocalStorage: UnwrapRef<typeof import('@vueuse/core')['useLocalStorage']>
readonly useMagicKeys: UnwrapRef<typeof import('@vueuse/core')['useMagicKeys']>

View File

@@ -1,11 +1,9 @@
import type { UserConfig } from '@commitlint/types';
const Configuration: UserConfig = {
extends: ['@commitlint/config-conventional'],
formatter: '@commitlint/format',
rules: {
'body-max-line-length': [2, 'always', 500],
},
};
export default Configuration;

View File

@@ -1,4 +1,4 @@
{
"extends": "@tsconfig/node24/tsconfig.json",
"extends": "@tsconfig/node22/tsconfig.json",
"include": ["./**/*"]
}

View File

@@ -10,7 +10,6 @@ import {
import pluginImport from 'eslint-plugin-import';
import pluginJsonc from 'eslint-plugin-jsonc';
import pluginOxlint from 'eslint-plugin-oxlint';
import pluginPerfectionist from 'eslint-plugin-perfectionist';
import pluginPlaywright from 'eslint-plugin-playwright';
import pluginVue from 'eslint-plugin-vue';
import { globalIgnores } from 'eslint/config';
@@ -25,14 +24,7 @@ export default defineConfigWithVueTs(
files: ['**/*.{ts,mts,tsx,vue}'],
},
globalIgnores([
'worker-configuration.d.ts',
'**/dist/**',
'**/dist-ssr/**',
'**/coverage/**',
'**/public/**',
'**/-----TEMP-----/**',
]),
globalIgnores(['worker-configuration.d.ts', '**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
@@ -53,13 +45,6 @@ export default defineConfigWithVueTs(
{
rules: {
'@intlify/vue-i18n/no-raw-text': 'off',
'@intlify/vue-i18n/no-unused-keys': [
'error',
{
src: './src',
extensions: ['.js', '.ts', '.tsx', '.vue'],
},
],
},
settings: {
'vue-i18n': {
@@ -69,7 +54,9 @@ export default defineConfigWithVueTs(
},
},
{
plugins: { import: pluginImport },
plugins: {
import: pluginImport,
},
rules: {
'import/first': 'error',
'import/no-duplicates': 'error',
@@ -83,8 +70,6 @@ export default defineConfigWithVueTs(
},
},
{ plugins: { perfectionist: pluginPerfectionist } },
{
/**
* 启用 sort-keys 规则以强制对象键按字母顺序排序
@@ -117,11 +102,7 @@ export default defineConfigWithVueTs(
'vue/attributes-order': 'error',
'vue/multi-word-component-names': 'off',
'vue/padding-line-between-blocks': ['error', 'always'],
'vue/component-name-in-template-casing': [
'error',
'PascalCase',
{ registeredComponentsOnly: false, ignores: [] },
],
// '@stylistic/padding-line-between-statements': [
// 'error',
// { blankLine: 'always', prev: '*', next: ['const', 'let', 'var'] },

View File

@@ -1,5 +1,5 @@
{
"packageManager": "pnpm@10.25.0",
"packageManager": "pnpm@10.23.0",
"name": "vue-ts-example-2025",
"version": "0.0.0",
"private": true,
@@ -14,7 +14,7 @@
},
"scripts": {
"all": "run-s lint format:prettier build-only type-check test:unit:DisableWatch",
"dev": "nodemon --delay 280ms --watch vite-plugins --ext ts -x vite -- --port 4730 --host --strictPort",
"dev": "vite --port 4730 --host --strictPort",
"build": "run-p type-check \"build-only {@}\" --",
"build-only": "vite build",
"preview": "vite preview --port 4731 --host --strictPort",
@@ -57,8 +57,8 @@
"@commitlint/cli": "^20.1.0",
"@commitlint/config-conventional": "^20.0.0",
"@formkit/auto-animate": "^0.9.0",
"@pinia/colada": "^0.21.0",
"@primeuix/themes": "^2.0.0",
"@pinia/colada": "^0.17.8",
"@primeuix/themes": "^1.2.5",
"@sa/materials": "workspace:*",
"@unhead/vue": "^2.0.19",
"@vueuse/core": "^14.0.0",
@@ -71,7 +71,7 @@
"primelocale": "^2.2.2",
"primevue": "^4.4.1",
"ts-enum-util": "^4.1.0",
"utils4u": "^5",
"utils4u": "^4.2.3",
"vue": "^3.5.24",
"vue-i18n": "^11.2.1",
"vue-memoize-dict": "^1.1.3",
@@ -86,14 +86,14 @@
"@iconify-json/material-symbols": "^1.2.47",
"@intlify/eslint-plugin-vue-i18n": "^4.1.0",
"@intlify/unplugin-vue-i18n": "^11.0.1",
"@playwright/test": "^1.57.0",
"@prettier/plugin-oxc": "^0.1.3",
"@playwright/test": "^1.56.1",
"@prettier/plugin-oxc": "^0.0.5",
"@primevue/auto-import-resolver": "^4.4.1",
"@primevue/metadata": "^4.4.1",
"@stylelint-types/stylelint-order": "^7.0.0",
"@stylelint-types/stylelint-scss": "^6.11.0",
"@stylistic/eslint-plugin": "^5.6.1",
"@tsconfig/node24": "^24.0.0",
"@tsconfig/node22": "^22.0.5",
"@types/html-minifier-terser": "^7.0.2",
"@types/jsdom": "^27.0.0",
"@types/lodash-es": "^4.17.12",
@@ -106,13 +106,11 @@
"@vue/eslint-config-typescript": "^14.6.0",
"@vue/test-utils": "^2.4.6",
"@vue/tsconfig": "^0.8.1",
"boxen": "^8.0.1",
"consola": "^3.4.2",
"eslint": "^9.39.1",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsonc": "^2.21.0",
"eslint-plugin-oxlint": "~1.32.0",
"eslint-plugin-perfectionist": "^5.0.0",
"eslint-plugin-oxlint": "~1.29.0",
"eslint-plugin-playwright": "^2.3.0",
"eslint-plugin-vue": "~10.6.0",
"happy-dom": "^20.0.10",
@@ -120,12 +118,11 @@
"husky": "^9.1.7",
"jsdom": "^27.2.0",
"lint-staged": "^16.2.7",
"nodemon": "^3.1.11",
"npm-run-all2": "^8.0.4",
"nprogress": "^0.2.0",
"oxlint": "~1.29.0",
"postcss-html": "^1.8.0",
"prettier": "3.8.0",
"prettier": "3.6.2",
"rollup": "^4.53.3",
"sass-embedded": "^1.93.3",
"sharp": "^0.34.5",
@@ -141,13 +138,13 @@
"typescript": "~5.9.3",
"unocss": "^66.5.9",
"unocss-preset-animations": "^1.3.0",
"unplugin-auto-import": "^21.0.0",
"unplugin-icons": "^23.0.0",
"unplugin-vue-components": "^31.0.0",
"unplugin-auto-import": "^20.2.0",
"unplugin-icons": "^22.5.0",
"unplugin-vue-components": "^30.0.0",
"unplugin-vue-markdown": "^29.2.0",
"unplugin-vue-router": "^0.19.0",
"vite": "^7.2.4",
"vite-plugin-checker": "^0.12.0",
"vite-plugin-checker": "^0.11.0",
"vite-plugin-fake-server": "^2.2.2",
"vite-plugin-image-optimizer": "^2.0.3",
"vite-plugin-vue-devtools": "^8.0.5",
@@ -157,7 +154,13 @@
"vue-component-type-helpers": "^3.1.4",
"vue-i18n-extract": "^2.0.7",
"vue-macros": "3.1.1",
"vue-tsc": "^3.1.8",
"vue-tsc": "^3.1.4",
"wrangler": "^4.50.0"
}
},
"overrides": {
"vue-tsc": "$vue-tsc"
},
"workspaces": [
"packages/*"
]
}

2734
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,3 @@
packages:
- 'packages/*'
# shamefullyHoist: false # https://pnpm.io/zh/settings#shamefullyhoist
overrides:
vue-tsc: $vue-tsc

View File

@@ -9,10 +9,10 @@ import AppNaiveUIProvider from './AppNaiveUIProvider.vue';
<Toast style="z-index: 5000" />
<AppNaiveUIProvider>
<RouterView v-slot="{ Component }">
<Transition name="fade" mode="out-in">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</Transition>
</RouterView>
</transition>
</router-view>
</AppNaiveUIProvider>
</template>

View File

@@ -42,17 +42,17 @@ declare global {
:theme="appStore.isDark ? darkTheme : null"
abstract
>
<NLoadingBarProvider>
<NMessageProvider>
<NNotificationProvider>
<NModalProvider>
<NDialogProvider>
<n-loading-bar-provider>
<n-message-provider>
<n-notification-provider>
<n-modal-provider>
<n-dialog-provider>
<slot></slot>
<ContextHolder />
</NDialogProvider>
</NModalProvider>
</NNotificationProvider>
</NMessageProvider>
</NLoadingBarProvider>
</n-dialog-provider>
</n-modal-provider>
</n-notification-provider>
</n-message-provider>
</n-loading-bar-provider>
</NConfigProvider>
</template>

View File

@@ -1,5 +1,6 @@
import { createGetRoutes } from '@/plugins/00.router-plugin';
import type { MenuInst, MenuOption } from 'naive-ui';
import { createGetRoutes } from 'virtual:meta-layouts';
import type { Ref } from 'vue';
import type { RouteRecordRaw } from 'vue-router';
import { RouterLink } from 'vue-router';

View File

@@ -25,7 +25,7 @@ function handleSelect(key: string) {
<NDropdown trigger="hover" placement="bottom-end" :options="options" @select="handleSelect">
<NButton quaternary class="flex items-center gap-1">
<template #icon>
<IconClarityLanguageLine w-4.5 h-4.5 />
<icon-clarity-language-line w-4.5 h-4.5 />
</template>
<span>{{ languageLabels[locale] }}</span>
</NButton>

View File

@@ -13,17 +13,17 @@ const themeLabels: Record<AppThemeMode, string> = {
{{ themeLabels[appStore.themeMode] }}
<template #trigger>
<NButton quaternary @click="appStore.cycleTheme()">
<IconLineMdSunnyFilledLoopToMoonFilledLoopTransition
<icon-line-md-sunny-filled-loop-to-moon-filled-loop-transition
v-if="appStore.themeMode === 'light'"
w-4.5
h-4.5
/>
<IconLineMdMoonFilledToSunnyFilledLoopTransition
<icon-line-md-moon-filled-to-sunny-filled-loop-transition
v-else-if="appStore.themeMode === 'dark'"
w-4.5
h-4.5
/>
<IconLineMdComputer v-else w-4.5 h-4.5 />
<icon-line-md-computer v-else w-4.5 h-4.5 />
</NButton>
</template>
</NTooltip>

View File

@@ -15,8 +15,8 @@ function toggleCollapsed() {
{{ appStore.sidebarCollapsed ? '展开菜单' : '收起菜单' }}
<template #trigger>
<NButton ref="buttonRef" quaternary @click="toggleCollapsed">
<IconLineMdMenuFoldRight v-if="appStore.sidebarCollapsed" w-4.5 h-4.5 />
<IconLineMdMenuFoldLeft v-else w-4.5 h-4.5 />
<icon-line-md-menu-fold-right v-if="appStore.sidebarCollapsed" w-4.5 h-4.5 />
<icon-line-md-menu-fold-left v-else w-4.5 h-4.5 />
</NButton>
</template>
</NTooltip>

View File

@@ -39,7 +39,7 @@ function handleSelect(key: string) {
<template>
<NDropdown :options="options" placement="bottom-end" @select="handleSelect">
<NButton quaternary circle>
<IconMaterialSymbolsAccountCircle w-5 h-5 />
<icon-material-symbols-account-circle w-5 h-5 />
</NButton>
</NDropdown>
</template>

View File

@@ -29,11 +29,11 @@ const appStore = useAppStore();
<BaseLayoutSider />
</template>
<!-- <div>GlobalContent</div> -->
<RouterView v-slot="{ Component }">
<Transition name="fade" mode="out-in">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</Transition>
</RouterView>
</transition>
</router-view>
<!-- <div>ThemeDrawer</div> -->
<template #footer>
<div

View File

@@ -4,8 +4,7 @@
*/
import messages from '@intlify/unplugin-vue-i18n/messages';
import { router } from '@/plugins/00.router-plugin';
import { createGetRoutes } from 'virtual:meta-layouts';
import { createGetRoutes, router } from '@/plugins/00.router-plugin';
import { createI18n } from 'vue-i18n';
import { START_LOCATION } from 'vue-router';

View File

@@ -1,12 +1,9 @@
/*eslint perfectionist/sort-objects: "error"*/
/*eslint sort-keys: "error"*/
/**
* 启用 perfectionist/sort-objects 规则以强制对象键按字母顺序排序
* 启用 sort-keys 规则以强制对象键按字母顺序排序
* 原因:
* 1. 减少多人协作时的合并冲突
* 2. 保持代码一致性,提高可维护性
*
* 运行以下命令自动修复排序:
* pnpm exec eslint --fix --no-ignore src/locales-utils/route-messages/
*/
export default {

View File

@@ -1,12 +1,9 @@
/*eslint perfectionist/sort-objects: "error"*/
/*eslint sort-keys: "error"*/
/**
* 启用 perfectionist/sort-objects 规则以强制对象键按字母顺序排序
* 启用 sort-keys 规则以强制对象键按字母顺序排序
* 原因:
* 1. 减少多人协作时的合并冲突
* 2. 保持代码一致性,提高可维护性
*
* 运行以下命令自动修复排序:
* pnpm exec eslint --fix --no-ignore src/locales-utils/route-messages/
*/
export default {

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
definePage({
// name: false,
meta: {
_file: '(layout-group).page.vue',
},
});
</script>
<template>
<div>
<div> b:</div>
<RouterView />
</div>
</template>

View File

@@ -0,0 +1,12 @@
<script setup lang="ts">
definePage({
alias: '/',
meta: {
_file: '(layout)/a.page.vue',
},
});
</script>
<template>
<div>a.page.vue</div>
</template>

View File

@@ -0,0 +1,11 @@
<script setup lang="ts">
definePage({
meta: {
_file: '(layout)/b.page.vue',
},
});
</script>
<template>
<div>b.page.vue</div>
</template>

View File

@@ -0,0 +1,11 @@
<script setup lang="ts">
definePage({
meta: {
_file: '(ccc)/c.page.vue',
},
});
</script>
<template>
<div>c.page.vue</div>
</template>

View File

@@ -0,0 +1,13 @@
<script setup lang="ts">
definePage({
meta: {
_file: '(home).page.vue',
},
});
</script>
<template>
<div>
<n-button @click="$router.push({ name: 'DemosCreate' })">DemosCreate</n-button>
</div>
</template>

7
src/pages/demos.page.vue Normal file
View File

@@ -0,0 +1,7 @@
<script setup lang="ts">
import TheBaseLayout from '@/layouts/base-layout/the-base-layout.vue';
</script>
<template>
<TheBaseLayout></TheBaseLayout>
</template>

View File

@@ -128,7 +128,7 @@ const resetCount = () => {
</button>
<!-- Naive UI 按钮 -->
<NButton
<n-button
type="warning"
size="large"
block
@@ -148,7 +148,7 @@ const resetCount = () => {
</svg>
</template>
点击 +1 (Naive UI)
</NButton>
</n-button>
<!-- 重置按钮 -->
<button

View File

@@ -8,5 +8,5 @@ definePage({
</script>
<template>
<div></div>
<div>create.page.vue</div>
</template>

View File

@@ -9,29 +9,29 @@ function setLocale(newLocale: 'en-US' | 'zh-CN') {
<template>
<div class="p-4">
<NH1>{{ t('page.i18n-demo.title') }}</NH1>
<n-h1>{{ t('page.i18n-demo.title') }}</n-h1>
<NCard :title="t('page.i18n-demo.change-language')">
<NP>
<n-card :title="t('page.i18n-demo.change-language')">
<n-p>
{{ t('page.i18n-demo.current-language') }}:
<span class="font-bold">{{ locale }}</span>
</NP>
</n-p>
<NP>
<n-p>
{{ t('page.i18n-demo.hello', { name: 'Kilo' }) }}
</NP>
</n-p>
<NSpace>
<NButton type="primary" @click="setLocale('en-US')"> English </NButton>
<NButton type="success" @click="setLocale('zh-CN')"> 简体中文 </NButton>
</NSpace>
</NCard>
<n-space>
<n-button type="primary" @click="setLocale('en-US')"> English </n-button>
<n-button type="success" @click="setLocale('zh-CN')"> 简体中文 </n-button>
</n-space>
</n-card>
<!-- 这里响应式有问题: -->
<NP> $route.meta.title: {{ $route.meta.title }} </NP>
<n-p> $route.meta.title: {{ $route.meta.title }} </n-p>
<!-- 这样才正常 -->
<NP>
<n-p>
routeI18nInstance.global.t($route.name): {{ routeI18nInstance.global.t($route.name) }}
</NP>
</n-p>
</div>
</template>

View File

@@ -1,7 +0,0 @@
<script setup lang="ts"></script>
<template>
<div>
<NButton @click="$router.push({ name: 'DemosCreate' })">DemosCreate</NButton>
</div>
</template>

View File

@@ -1,14 +1,13 @@
import { DataLoaderPlugin } from 'unplugin-vue-router/data-loaders';
import { setupLayouts } from 'virtual:meta-layouts';
// import { createGetRoutes, setupLayouts } from 'virtual:generated-layouts';
// import { setupLayouts } from 'virtual:meta-layouts';
import { createRouter, createWebHistory } from 'vue-router';
import type { Router } from 'vue-router';
import { handleHotUpdate, routes } from 'vue-router/auto-routes';
const setupLayoutsResult = setupLayouts(routes);
// const setupLayoutsResult = setupLayouts(routes);
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: /* routes ?? */ setupLayoutsResult,
routes: routes /* ?? setupLayoutsResult */,
scrollBehavior: (_to, _from, savedPosition) => {
return savedPosition ?? { left: 0, top: 0 };
},
@@ -50,6 +49,11 @@ export function install({ app }: { app: import('vue').App<Element> }) {
// <<<
}
export function createGetRoutes(router: Router) {
const routes = router.getRoutes();
return () => routes.filter((route) => !route.meta.isLayout);
}
if (__DEV__) Object.assign(window, { router });
// This will update routes at runtime without reloading the page
@@ -57,4 +61,4 @@ if (import.meta.hot) {
handleHotUpdate(router);
}
export { router, setupLayoutsResult };
export { router };

View File

@@ -20,7 +20,6 @@
},
"vueCompilerOptions": {
"plugins": [
"vue-macros/volar",
"unplugin-vue-router/volar/sfc-route-blocks",
"unplugin-vue-router/volar/sfc-typed-router"
]

View File

@@ -1,5 +1,5 @@
{
"extends": "@tsconfig/node24/tsconfig.json",
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",

72
typed-router.d.ts vendored
View File

@@ -28,6 +28,28 @@ declare module 'vue-router/auto-routes' {
'/',
Record<never, never>,
Record<never, never>,
| 'RootA'
| 'RootB'
>,
'RootA': RouteRecordInfo<
'RootA',
'/a',
Record<never, never>,
Record<never, never>,
| never
>,
'RootB': RouteRecordInfo<
'RootB',
'/b',
Record<never, never>,
Record<never, never>,
| never
>,
'RootC': RouteRecordInfo<
'RootC',
'/c',
Record<never, never>,
Record<never, never>,
| never
>,
'$Path': RouteRecordInfo<
@@ -37,6 +59,20 @@ declare module 'vue-router/auto-routes' {
{ path: ParamValue<false> },
| never
>,
'DemosParent': RouteRecordInfo<
'DemosParent',
'/demos',
Record<never, never>,
Record<never, never>,
| 'Demos'
| 'DemosApiDemo'
| 'DemosCounterDemo'
| 'DemosCreate'
| 'DemosI18nDemo'
| 'DemosNaiveUiDemo'
| 'DemosPrimevueDemo'
| 'DemosWebsocketDemo'
>,
'Demos': RouteRecordInfo<
'Demos',
'/demos',
@@ -120,9 +156,29 @@ declare module 'vue-router/auto-routes' {
* @internal
*/
export interface _RouteFileInfoMap {
'src/pages/index.page.vue': {
'src/pages-with-layout/(layout-group).page.vue': {
routes:
| 'Root'
| 'RootA'
| 'RootB'
views:
| 'default'
}
'src/pages-with-layout/(layout-group)/a.page.vue': {
routes:
| 'RootA'
views:
| never
}
'src/pages-with-layout/(layout-group)/b.page.vue': {
routes:
| 'RootB'
views:
| never
}
'src/pages/(ccc)/c.page.vue': {
routes:
| 'RootC'
views:
| never
}
@@ -132,6 +188,20 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/demos.page.vue': {
routes:
| 'Demos'
| 'DemosApiDemo'
| 'DemosCounterDemo'
| 'DemosCreate'
| 'DemosI18nDemo'
| 'DemosNaiveUiDemo'
| 'DemosParent'
| 'DemosPrimevueDemo'
| 'DemosWebsocketDemo'
views:
| 'default'
}
'src/pages/demos/index.page.vue': {
routes:
| 'Demos'

View File

@@ -1,33 +1,32 @@
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import consola from 'consola';
import { getPascalCaseRouteName } from 'unplugin-vue-router';
import vueRouter from 'unplugin-vue-router/vite';
import type { PluginOption } from 'vite';
import VueMacros from 'vue-macros/vite';
import type { LoadPluginFunction } from './_loadPlugins';
export default [
VueMacros({
plugins: {
vue: vue({ include: [/\.vue$/, /\.md$/] }),
vueJsx: vueJsx(),
export const loadPlugin: LoadPluginFunction = async (_pluginLoadOptions) => {
return [
VueMacros({
plugins: {
vue: vue({ include: [/\.vue$/, /\.md$/] }),
vueJsx: vueJsx(),
// https://uvr.esm.is/guide/configuration.html
// https://github.com/posva/unplugin-vue-router
// ⚠️ Vue must be placed after VueRouter()
vueRouter: vueRouter({
routesFolder: 'src/pages',
extensions: ['.page.vue', '.page.md'],
exclude: ['**/__*', '**/__*/**/*'],
getRouteName: (await import('unplugin-vue-router')).getPascalCaseRouteName,
beforeWriteFiles(rootRoute) {
for (/* 深度优先遍历 */ const route of rootRoute.traverseDFS()) {
route.addToMeta({ _: route.fullPath });
}
},
logs: !true,
}),
},
}),
];
};
// https://uvr.esm.is/guide/configuration.html
// https://github.com/posva/unplugin-vue-router
// ⚠️ Vue must be placed after VueRouter()
vueRouter: vueRouter({
exclude: ['**/__*', '**/__*/**/*'],
extensions: ['.page.vue', '.page.md'],
getRouteName: (routeNode) => getPascalCaseRouteName(routeNode),
logs: true,
routesFolder: ['src/pages', 'src/pages-with-layout'],
extendRoute(route) {
consola.info(`route.name :>> `, route.name);
console.debug(`route.meta :>> `, route.meta);
console.debug(`route.path :>> `, route.path);
},
}),
},
}),
] satisfies PluginOption;

View File

@@ -1,13 +1,10 @@
import type { PluginOption } from 'vite';
import UnoCSS from 'unocss/vite';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
return [
// https://github.com/antfu/unocss
// see uno.config.ts for config
UnoCSS({
checkImport: true,
}),
];
};
export default [
// https://github.com/antfu/unocss
// see uno.config.ts for config
UnoCSS({
checkImport: true,
}),
] satisfies PluginOption;

View File

@@ -1,21 +1,18 @@
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import type { PluginOption } from 'vite';
import type { LoadPluginFunction } from './_loadPlugins';
export default [
// https://github.com/intlify/bundle-tools/tree/main/packages/unplugin-vue-i18n
VueI18nPlugin({
/* options */
// locale messages resource pre-compile option
include: ['src/locales/**'],
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
return [
// https://github.com/intlify/bundle-tools/tree/main/packages/unplugin-vue-i18n
VueI18nPlugin({
/* options */
// locale messages resource pre-compile option
include: ['src/locales/**'],
// https://github.com/intlify/bundle-tools/tree/main/packages/unplugin-vue-i18n#transformi18nblock
// transformI18nBlock(src) {
// console.debug(`src :>> `, src);
// console.debug(`typeof src :>> `, typeof src);
// return src as string;
// },
}),
];
};
// https://github.com/intlify/bundle-tools/tree/main/packages/unplugin-vue-i18n#transformi18nblock
// transformI18nBlock(src) {
// console.debug(`src :>> `, src);
// console.debug(`typeof src :>> `, typeof src);
// return src as string;
// },
}),
] satisfies PluginOption;

View File

@@ -1,12 +1,9 @@
import type { PluginOption } from 'vite';
import Markdown from 'unplugin-vue-markdown/vite';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
return [
// https://github.com/unplugin/unplugin-vue-markdown
Markdown({
headEnabled: true,
}),
];
};
export default [
// https://github.com/unplugin/unplugin-vue-markdown
Markdown({
headEnabled: true,
}),
] satisfies PluginOption;

View File

@@ -0,0 +1,17 @@
import type { PluginOption } from 'vite';
import MetaLayouts from 'vite-plugin-vue-meta-layouts';
export default [
// https://github.com/dishait/vite-plugin-vue-meta-layouts
MetaLayouts({
target: 'src/layouts',
excludes: ['**/!(the-)*.vue'], // 排除非 the- 开头的文件。
metaName: 'layout',
// defaultLayout: 'sakai-vue/AppLayout',
// defaultLayout: 'naive-ui/AppLayout',
defaultLayout: 'base-layout/the-base-layout',
// !⬇️: 当设置为 `sync` 时,注意`import 'virtual:uno.css'`的顺序问题。
// importMode: 'sync', // 默认为自动处理SSG 时为 sync非 SSG 时为 async
skipTopLevelRouteLayout: true, // 打开修复 https://github.com/JohnCampionJr/vite-plugin-vue-layouts/issues/134默认为 false 关闭
}),
] satisfies PluginOption;

View File

@@ -1,20 +0,0 @@
import MetaLayouts from 'vite-plugin-vue-meta-layouts';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
return [
// https://github.com/dishait/vite-plugin-vue-meta-layouts
MetaLayouts({
target: 'src/layouts',
excludes: ['**/!(the-)*.vue'], // 排除非 the- 开头的文件。
metaName: 'layout',
// defaultLayout: 'sakai-vue/AppLayout',
// defaultLayout: 'naive-ui/AppLayout',
defaultLayout: 'base-layout/the-base-layout',
// !⬇️: 当设置为 `sync` 时,注意`import 'virtual:uno.css'`的顺序问题。
// importMode: 'sync', // 默认为自动处理SSG 时为 sync非 SSG 时为 async
skipTopLevelRouteLayout: true, // 打开修复 https://github.com/JohnCampionJr/vite-plugin-vue-layouts/issues/134默认为 false 关闭
}),
];
};

View File

@@ -9,6 +9,7 @@ import Icons from 'unplugin-icons/vite';
import Components from 'unplugin-vue-components/vite';
import { VueRouterAutoImports } from 'unplugin-vue-router';
import { createUtils4uAutoImports } from 'utils4u/auto-imports';
import type { ConfigEnv, PluginOption } from 'vite';
// >>>>>
// eslint-disable-next-line import/no-duplicates
@@ -25,8 +26,6 @@ import { PrimeVueResolver } from '@primevue/auto-import-resolver';
import { VantResolver } from '@vant/auto-import-resolver';
// <<<<<
import type { LoadPluginFunction } from './_loadPlugins';
function _getNaiveUiComponentNames() {
// [dtsTsx](https://github.com/unplugin/unplugin-vue-components/pull/673/files/84e80738885cfe11298f41f070cda94a7a779276)
@@ -56,7 +55,7 @@ function _getNaiveUiComponentNames() {
return [];
}
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
export function loadPlugin(_configEnv: ConfigEnv): PluginOption {
return [
// https://github.com/antfu/unplugin-auto-import
AutoImport({
@@ -77,7 +76,7 @@ export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
createUtils4uAutoImports(['primevue']),
{
'consola/browser': ['consola'],
'unplugin-vue-router/data-loaders/basic': ['defineBasicLoader'],
'vue-router/auto': ['useLink'],
'naive-ui': [
'useModal',
'useDialog',
@@ -142,4 +141,4 @@ export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
},
}),
];
};
}

View File

@@ -1,7 +1,6 @@
import { minify as minifyHtml } from 'html-minifier-terser';
import type { PluginOption } from 'vite';
import type { LoadPluginFunction } from './_loadPlugins';
import { loadEnv } from 'vite';
import type { ConfigEnv, PluginOption } from 'vite';
function IndexHtmlPlugin(): PluginOption {
return {
@@ -92,14 +91,8 @@ function ___(): PluginOption {
};
}
export const loadPlugin: LoadPluginFunction = (pluginLoadOptions) => {
const { mode, env } = pluginLoadOptions;
export function loadPlugin(_configEnv: ConfigEnv): PluginOption {
// return [___()];
if (mode !== 'production') {
return { plugins: [], message: '仅在生产模式下启用' };
}
if (env.VITE_BUILD_MINIFY !== 'true') {
return { plugins: [], message: `已通过环境变量禁用: VITE_BUILD_MINIFY=${env.VITE_BUILD_MINIFY}` };
}
return IndexHtmlPlugin();
};
const env = loadEnv(_configEnv.mode, process.cwd());
if (env.VITE_BUILD_MINIFY === 'true') return IndexHtmlPlugin();
}

View File

@@ -1,16 +1,16 @@
import { consola } from 'consola';
import type { ConfigEnv, PluginOption } from 'vite';
import { vitePluginFakeServer } from 'vite-plugin-fake-server';
import type { LoadPluginFunction } from './_loadPlugins';
// https://github.com/condorheroblog/vite-plugin-fake-server?tab=readme-ov-file#usage
export const loadPlugin: LoadPluginFunction = (pluginLoadOptions) => {
const { mode } = pluginLoadOptions;
if (mode !== 'development') {
return { plugins: [], message: '仅在开发模式下启用' };
export function loadPlugin(_configEnv: ConfigEnv): PluginOption {
if (_configEnv.mode !== 'development') {
consola.info('fake server plugin is disabled in non-development mode.');
return [];
}
return vitePluginFakeServer({
basename: 'fake-api',
enableProd: true,
include: 'fake',
});
};
}

View File

@@ -1,12 +1,9 @@
import type { PluginOption } from 'vite';
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
return [
// https://github.com/FatehAK/vite-plugin-image-optimizer?tab=readme-ov-file#default-configuration
ViteImageOptimizer({
/* pass your config */
}),
];
};
export default [
// https://github.com/FatehAK/vite-plugin-image-optimizer?tab=readme-ov-file#default-configuration
ViteImageOptimizer({
/* pass your config */
}),
] satisfies PluginOption;

View File

@@ -1,27 +1,23 @@
import consola from 'consola';
import type { ConfigEnv, PluginOption } from 'vite';
import vueDevTools from 'vite-plugin-vue-devtools';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
const { mode } = _pluginLoadOptions;
if (mode !== 'development') {
return { plugins: [], message: '仅在开发模式下启用' };
export function loadPlugin(configEnv: ConfigEnv): PluginOption {
if (configEnv.mode !== 'development') {
consola.info('vue-devtools 插件仅在开发模式下使用。');
return [];
}
let launchEditor = 'code';
let message: string | undefined;
if (process.env.TERM_PROGRAM_VERSION?.toLowerCase()?.includes('insider')) {
consola.info('检测到 VSCode Insiders 环境。');
launchEditor = 'code-insiders';
message = '检测到 VSCode Insiders 环境';
}
return {
plugins: [
vueDevTools({
launchEditor: launchEditor,
}),
],
message,
};
};
return [
vueDevTools({
launchEditor: launchEditor,
}),
];
}

View File

@@ -1,17 +1,16 @@
import { cloudflare } from '@cloudflare/vite-plugin';
import { loadEnv } from 'vite';
import type {ConfigEnv, PluginOption} from 'vite';
import type { LoadPluginFunction } from './_loadPlugins';
export const loadPlugin: LoadPluginFunction = (pluginLoadOptions) => {
const { mode, env } = pluginLoadOptions;
if (mode === 'test') {
return { plugins: [], message: '在测试模式下禁用' };
export function loadPlugin(_configEnv: ConfigEnv): PluginOption {
const env = loadEnv(_configEnv.mode, process.cwd());
if (_configEnv.mode === 'test') {
console.log('cloudflare plugin disabled in test mode');
return [];
}
if (env.VITE_CLOUDFLARE_SERVER_ENABLED !== 'true') {
return {
plugins: [],
message: `已通过环境变量禁用: VITE_CLOUDFLARE_SERVER_ENABLED=${env.VITE_CLOUDFLARE_SERVER_ENABLED}`,
};
console.log('cloudflare plugin disabled by env');
return [];
}
return [cloudflare()];
};
}

View File

@@ -1,47 +1,30 @@
import boxen from 'boxen';
import consola from 'consola';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import consola from 'consola';
import { glob } from 'tinyglobby';
import type { ConfigEnv, PluginOption } from 'vite';
import { loadEnv } from 'vite';
export type LoadPluginFunction = (
configEnv: ConfigEnv & {
env: Record<string, string>;
},
) => PluginOption | LoadPluginResult;
export interface LoadPluginResult {
plugins: PluginOption;
message?: string;
}
type LoadPluginFunction = (configEnv: ConfigEnv) => PluginOption;
export async function loadPlugins(configEnv: ConfigEnv): Promise<PluginOption[]> {
const plugins: PluginOption[] = [];
const cwd = path.resolve(import.meta.dirname);
consola.start('开始加载 Vite 插件...');
const pluginEntries = await glob('**/*.ts', {
absolute: true,
cwd,
cwd: path.resolve(import.meta.dirname),
ignore: [
'**/*.d.ts',
'**/*.disabled.ts',
'**/*.x.ts',
'**/*.X.ts',
'**/x-*.ts', // 禁用以 x- 开头的插件文件
'**/*-x.ts', // 禁用以 -x 结尾的插件文件
'**/*-X.ts', // 禁用以 -X 结尾的插件文件
'**/_*',
],
});
const relativeCwd = path.relative(process.cwd(), cwd);
console.time('加载插件');
consola.log(
boxen(`正在加载 Vite 插件... (./${relativeCwd})`, {
borderStyle: 'classic',
borderColor: 'cyan',
}),
);
consola.info(`找到 ${pluginEntries.length} 个插件文件`);
// 计算最长的文件名长度,用于对齐输出
const maxNameLength = Math.max(...pluginEntries.map((entry) => path.basename(entry).length));
@@ -52,39 +35,36 @@ export async function loadPlugins(configEnv: ConfigEnv): Promise<PluginOption[]>
const imported = await import(pathToFileURL(entry).href);
const loadPlugin = imported.loadPlugin as LoadPluginFunction | undefined;
let plugin: PluginOption | undefined;
let loadMethod = '';
if (!loadPlugin || typeof loadPlugin !== 'function') {
consola.warn(`插件未导出 loadPlugin 函数: ${paddedName}`);
continue;
// 优先使用 loadPlugin 函数(接收 configEnv 参数)
if (loadPlugin && typeof loadPlugin === 'function') {
plugin = loadPlugin(configEnv);
loadMethod = 'loadPlugin';
} else if (imported.default) {
plugin = imported.default;
loadMethod = 'default';
} else {
consola.warn(`插件未导出有效内容: ${paddedName}`);
continue; // 跳过无效插件
}
const env = loadEnv(configEnv.mode, process.cwd());
const result = loadPlugin({ ...configEnv, env });
if (plugin) {
const pluginArray = Array.isArray(plugin) ? plugin : [plugin];
const validPlugins = pluginArray.filter(Boolean); // 过滤掉 null/undefined
const pluginCount = validPlugins.length;
// 判断是否是 LoadPluginResult 对象
const isResultObject = (val: unknown): val is LoadPluginResult =>
typeof val === 'object' && val !== null && 'plugins' in val;
const plugin = isResultObject(result) ? result.plugins : result;
const message = isResultObject(result) ? result.message : undefined;
const pluginArray = Array.isArray(plugin) ? plugin : [plugin];
const validPlugins = pluginArray.filter(Boolean);
const pluginCount = validPlugins.length;
if (pluginCount > 0) {
plugins.push(...validPlugins);
const suffix = message ? ` (${message})` : '';
consola.info(`${paddedName}${pluginCount} 个实例${suffix}`);
} else if (message) {
consola.info(`${paddedName}${message}`);
} else {
consola.info(`${paddedName} 返回了空数组或无效值`);
if (pluginCount > 0) {
plugins.push(...validPlugins);
consola.success(`${paddedName}${pluginCount} 个实例 (${loadMethod})`);
} else {
consola.info(`${paddedName} 返回了空数组或无效值`);
}
}
}
consola.success(` ${pluginEntries.length} 个插件文件,已加载 ${plugins.length} 个实例`);
console.timeEnd('加载插件');
consola.success(`✅ 总共加载 ${plugins.length}插件实例`);
return plugins;
}

View File

@@ -1,16 +1,13 @@
import type { LoadPluginFunction } from './_loadPlugins';
import type { ConfigEnv, PluginOption } from 'vite';
import { loadEnv } from 'vite';
export const loadPlugin: LoadPluginFunction = (_pluginLoadOptions) => {
const env = _pluginLoadOptions.env;
export default [
// ...
] satisfies PluginOption;
// 示例:根据环境变量禁用插件并返回消息
if (env.VITE_DEMO_ENABLED !== 'true') {
return {
plugins: [],
message: `已通过环境变量禁用: VITE_DEMO_ENABLED=${env.VITE_DEMO_ENABLED}`,
};
}
// 正常返回插件
return [];
};
export function loadPlugin(_configEnv: ConfigEnv): PluginOption {
const env = loadEnv(_configEnv.mode, process.cwd());
console.debug(`env :>> `, env);
// ...
return undefined;
}

View File

@@ -0,0 +1,17 @@
import type { PluginOption } from 'vite';
export default [
// // 检查是否在VS Code终端中运行
// if (process.env.TERM_PROGRAM === 'vscode' || process.env.VSCODE_PID) {
// // plugins.push(
// // // 构建后自动将dist目录打包成zip文件
// // viteArchiverPlugin({
// // addTimestamp: false, // 是否添加时间戳到输出文件名
// // format: 'zip', // 输出的压缩文件格式
// // outputDir: '', // 输出目录,默认为项目根目录
// // outputFileName: 'dist', // 输出的zip文件名不含扩展名
// // sourceDir: 'dist', // 要打包的源目录
// // }),
// // )
// }
] satisfies PluginOption;

View File

@@ -1,6 +1,6 @@
import type { /* ManualChunkMeta, PreRenderedAsset, */ RollupOptions } from 'rollup';
import type { ManualChunkMeta, PreRenderedAsset, RollupOptions } from 'rollup';
// import path from 'node:path';
import path from 'node:path';
// https://www.npmjs.com/package/utils4u/v/2.19.2?activeTab=code
@@ -12,95 +12,106 @@ export const viteConfigRollupOptions: RollupOptions = {
if (warning.code === 'EVAL' && warning.id?.includes('node_modules/protobufjs')) return;
warn(warning);
}, */
output: {
// 如果一个 chunk 小于 10KBRollup 会尝试将它合并到其他 chunk 中。这样可以避免产生大量碎片文件
experimentalMinChunkSize: 10 * 1024,
// // Keep hashed file names predictable across entry, chunk, and asset outputs.
// entryFileNames: 'entry/[name].[hash].js', // 默认: "[name].js"
// chunkFileNames: 'chunk/[name].[hash].js', // 默认: "[name]-[hash].js"
// // assetFileNames:'', // 默认: "assets/[name]-[hash][extname]"
// // https://cn.rollupjs.org/configuration-options/#output-assetfilenames
// assetFileNames(chunkInfo: PreRenderedAsset) {
// const names = [...new Set(chunkInfo.names)];
// if (names.length !== 1) {
// console.error('Multiple names for asset:', chunkInfo);
// process.exit(1);
// }
// const assetName = names[0];
// const ext = assetName.split('.').pop()?.toLowerCase();
// if (ext && /png|jpe?g|gif|svg|webp|avif/.test(ext)) {
// return 'chunks/images/[name].[hash][extname]';
// }
// if (ext && /woff2?|ttf|otf/.test(ext)) {
// return 'chunks/fonts/[name].[hash][extname]';
// }
// if (ext === 'css') {
// return 'chunks/css/[name].[hash][extname]';
// }
// return '_chunks/[name].[hash][extname]';
// },
// manualChunks: (id: string, _meta: ManualChunkMeta) => {
// // https://github.com/unocss/unocss/issues/4917
// // if (['/src/layouts'].some((prefix) => id.includes(prefix))) {
// // const url = new URL(id, 'file://');
// // if (!url.search /* ?vue&type=script&setup=true&lang.ts */) {
// // return 'layouts';
// // }
// // }
// if (id.includes('meta-layouts')) {
// // console.debug(`id :>> `, id); // id :>> virtual:meta-layouts
// // 这里很奇怪,打印 id 是`virtual:meta-layouts`,但是 `'virtual:meta-layouts' === id` 却是 false
// return 'lib-meta-layouts';
// }
// if (id.includes('index.page.vue')) {
// const url = new URL(id, 'file://');
// if (!url.search /* ?vue&type=script&setup=true&lang.ts */) {
// const parentDir = path.basename(path.dirname(id));
// return `${parentDir}-index.page`;
// }
// }
// if (!id.includes('node_modules')) return;
// // 处理 pnpm 的特殊路径结构
// let packageName;
// if (id.includes('.pnpm')) {
// // pnpm 路径: .pnpm/naive-ui@2.43.1_vue@3.5.22/node_modules/naive-ui/...
// const pnpmMatch = id.match(/\.pnpm\/(.+?)@/);
// if (pnpmMatch) {
// packageName = pnpmMatch[1];
// }
// } else {
// // 普通路径: node_modules/lodash/...
// const normalMatch = id.match(/node_modules\/(@[^/]+\/[^/]+|[^/]+)\//);
// if (normalMatch) {
// packageName = normalMatch[1];
// }
// }
// if (packageName) {
// if (['highlight.js'].includes(packageName)) {
// return 'lib-hljs';
// }
// // 根据包名分组
// if (['consola', 'lodash', '@juggle+resize-observer', 'vueuc'].includes(packageName)) {
// return 'lib-vendor';
// }
// // // 拆了有问题
// // if (['naive-ui'].includes(packageName) && id.includes('_internal')) {
// // return 'lib-naive-ui-internal';
// // }
// if (['naive-ui'].includes(packageName)) {
// return 'lib-naive-ui';
// }
// if (
// ['primelocale', 'primevue', 'primeuix', 'primeicons'].some((name) =>
// packageName!.includes(name),
// )
// ) {
// return 'lib-primevue';
// }
// if (['vue', 'vue-router', 'pinia', 'vue-demi', 'vue-i18n'].includes(packageName)) {
// return 'lib-vue-vendor';
// }
// }
// },
// Keep hashed file names predictable across entry, chunk, and asset outputs.
entryFileNames: 'entry/[name].[hash].js', // 默认: "[name].js"
chunkFileNames: 'chunk/[name].[hash].js', // 默认: "[name]-[hash].js"
// assetFileNames:'', // 默认: "assets/[name]-[hash][extname]"
// https://cn.rollupjs.org/configuration-options/#output-assetfilenames
assetFileNames(chunkInfo: PreRenderedAsset) {
const names = [...new Set(chunkInfo.names)];
if (names.length !== 1) {
console.error('Multiple names for asset:', chunkInfo);
process.exit(1);
}
const assetName = names[0];
const ext = assetName.split('.').pop()?.toLowerCase();
if (ext && /png|jpe?g|gif|svg|webp|avif/.test(ext)) {
return 'chunks/images/[name].[hash][extname]';
}
if (ext && /woff2?|ttf|otf/.test(ext)) {
return 'chunks/fonts/[name].[hash][extname]';
}
if (ext === 'css') {
return 'chunks/css/[name].[hash][extname]';
}
return '_chunks/[name].[hash][extname]';
},
manualChunks: (id: string, _meta: ManualChunkMeta) => {
// https://github.com/unocss/unocss/issues/4917
// if (['/src/layouts'].some((prefix) => id.includes(prefix))) {
// const url = new URL(id, 'file://');
// if (!url.search /* ?vue&type=script&setup=true&lang.ts */) {
// return 'layouts';
// }
// }
if (id.includes('meta-layouts')) {
// console.debug(`id :>> `, id); // id :>> virtual:meta-layouts
// 这里很奇怪,打印 id 是`virtual:meta-layouts`,但是 `'virtual:meta-layouts' === id` 却是 false
return 'lib-meta-layouts';
}
if (id.includes('index.page.vue')) {
const url = new URL(id, 'file://');
if (!url.search /* ?vue&type=script&setup=true&lang.ts */) {
const parentDir = path.basename(path.dirname(id));
return `${parentDir}-index.page`;
}
}
if (!id.includes('node_modules')) return;
// 处理 pnpm 的特殊路径结构
let packageName;
if (id.includes('.pnpm')) {
// pnpm 路径: .pnpm/naive-ui@2.43.1_vue@3.5.22/node_modules/naive-ui/...
const pnpmMatch = id.match(/\.pnpm\/(.+?)@/);
if (pnpmMatch) {
packageName = pnpmMatch[1];
}
} else {
// 普通路径: node_modules/lodash/...
const normalMatch = id.match(/node_modules\/(@[^/]+\/[^/]+|[^/]+)\//);
if (normalMatch) {
packageName = normalMatch[1];
}
}
if (packageName) {
if (['highlight.js'].includes(packageName)) {
return 'lib-hljs';
}
// 根据包名分组
if (['consola', 'lodash', '@juggle+resize-observer', 'vueuc'].includes(packageName)) {
return 'lib-vendor';
}
// // 拆了有问题
// if (['naive-ui'].includes(packageName) && id.includes('_internal')) {
// return 'lib-naive-ui-internal';
// }
if (['naive-ui'].includes(packageName)) {
return 'lib-naive-ui';
}
if (
['primelocale', 'primevue', 'primeuix', 'primeicons'].some((name) =>
packageName!.includes(name),
)
) {
return 'lib-primevue';
}
if (['vue', 'vue-router', 'pinia', 'vue-demi', 'vue-i18n'].includes(packageName)) {
return 'lib-vue-vendor';
}
}
},
},
};

View File

@@ -3,7 +3,7 @@ import { createViteProxy } from 'utils4u/vite';
import { defineConfig, loadEnv } from 'vite';
import { loadPlugins } from './vite-plugins/_loadPlugins';
import { optimizeDeps } from './vite.config.optimizeDeps';
import { viteConfigRollupOptions } from './vite.config.rollup';
// import { viteConfigRollupOptions } from './vite.config.rollup';
import consola from 'consola';
// https://vite.dev/config/
@@ -24,7 +24,7 @@ export default defineConfig(async (configEnv) => {
build: {
minify: env.VITE_BUILD_MINIFY === 'true' ? undefined /* 即默认 */ : false, // 默认: 'terser'
sourcemap: env.VITE_BUILD_SOURCE_MAP === 'true',
rollupOptions: viteConfigRollupOptions,
// rollupOptions: viteConfigRollupOptions,
},
css: {
devSourcemap: true,