Commit 3c29dd7d by Lin

feat: 格式化校验异常处理

1 parent dd6d98b2
// / <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
......
// / <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
......
......@@ -4,10 +4,11 @@ import { defineConfig } from "@venus/eslint-config";
export default defineConfig([
{
files: [ "**/env.d.ts" ],
files: ["example/src/**/*.ts", "example/src/**/*.vue"],
languageOptions: {
parserOptions: {
project: "./tsconfig.json",
project: ["./example/tsconfig.json"],
tsconfigRootDir: import.meta.dirname,
},
},
},
......
// / <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
......
......@@ -130,9 +130,7 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean {
}
if (normalizedMenuPath.includes(":")) {
const pattern = normalizedMenuPath
.replaceAll(/:[^/]+/g, "[^/]+")
.replaceAll("/", String.raw`\/`);
const pattern = normalizedMenuPath.replaceAll(/:[^/]+/g, "[^/]+").replaceAll("/", String.raw`\/`);
const regex = new RegExp(`^${pattern}$`);
return regex.test(normalizedTargetPath);
}
......
......@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
"baseUrl": ".",
"module": "ESNext",
......
......@@ -34,16 +34,16 @@ const scopeComplete = execSync("git status --porcelain || true")
.trim()
.split("\n")
.find((r) => ~r.indexOf("M src"))
?.replaceAll(/(\/)/g, "%%")
?.match(/src%%((\w|-)*)/)?.[1]
?.replaceAll("/", "%%")
?.match(/src%%((?:\w|-)*)/)?.[1]
?.replace(/s$/, "");
/**
* @type {import('cz-git').UserConfig}
*/
const userConfig = {
extends: ["@commitlint/config-conventional"],
plugins: ["commitlint-plugin-function-rules"],
extends: [ "@commitlint/config-conventional" ],
plugins: [ "commitlint-plugin-function-rules" ],
prompt: {
/** @use `pnpm commit :f` */
alias: {
......@@ -103,7 +103,7 @@ const userConfig = {
* ^^^^^^^^^^^^^^ empty line.
* - Something here
*/
"body-leading-blank": [2, "always"],
"body-leading-blank": [ 2, "always" ],
/**
* type[scope]: [function] description
*
......@@ -111,7 +111,7 @@ const userConfig = {
*
* ^^^^^^^^^^^^^^
*/
"footer-leading-blank": [1, "always"],
"footer-leading-blank": [ 1, "always" ],
/**
* type[scope]: [function] description
* ^^^^^
......@@ -121,22 +121,22 @@ const userConfig = {
"always",
(parsed) => {
if (!parsed.scope || allowedScopes.includes(parsed.scope)) {
return [true];
return [ true ];
}
return [false, `scope must be one of ${allowedScopes.join(", ")}`];
return [ false, `scope must be one of ${allowedScopes.join(", ")}` ];
},
],
/**
* type[scope]: [function] description [No more than 108 characters]
* ^^^^^
*/
"header-max-length": [2, "always", 108],
"header-max-length": [ 2, "always", 108 ],
"scope-enum": [0],
"subject-case": [0],
"subject-empty": [2, "never"],
"type-empty": [2, "never"],
"scope-enum": [ 0 ],
"subject-case": [ 0 ],
"subject-empty": [ 2, "never" ],
"type-empty": [ 2, "never" ],
/**
* type[scope]: [function] description
* ^^^^
......
......@@ -11,138 +11,141 @@ import type { Linter } from "eslint";
import { interopDefault } from "../util";
export async function typescript(): Promise<Linter.Config[]> {
const [ pluginTs, parserTs ] = await Promise.all([
interopDefault(import("@typescript-eslint/eslint-plugin")),
interopDefault(import("@typescript-eslint/parser")),
] as const);
// 公共的 parser 配置
const baseParserOptions = {
createDefaultProgram: false,
ecmaFeatures: { jsx: true },
ecmaVersion: "latest" as const,
sourceType: "module" as const,
};
return [
{
files: [ "**/*.?([cm])[jt]s?(x)" ],
languageOptions: {
parser: parserTs,
parserOptions: {
// 不使用 createDefaultProgram 以避免性能问题,项目使用基于 glob 的 tsconfig
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: "latest",
extraFileExtensions: [ ".vue" ],
jsxPragma: "React",
project: "./tsconfig.*.json",
sourceType: "module",
},
},
plugins: {
"@typescript-eslint": pluginTs as any,
},
rules: {
...pluginTs.configs["eslint-recommended"]?.overrides?.[0]?.rules,
...pluginTs.configs.strict?.rules,
"@typescript-eslint/no-require-imports": "warn",
// 对 @ts-xxx 注释进行限制:允许带说明的忽略以便在确有必要时记录原因
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-check": false,
"ts-expect-error": "allow-with-description",
"ts-ignore": "allow-with-description",
"ts-nocheck": "allow-with-description",
},
],
// '@typescript-eslint/consistent-type-definitions': ['warn', 'interface'],
// 关闭统一类型定义风格限制,团队可自由选择 interface/type
"@typescript-eslint/consistent-type-definitions": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-empty-function": [
"error",
{
allow: [ "arrowFunctions", "functions", "methods" ],
},
],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-this-alias":"warn",
// 禁止非空断言以避免隐藏潜在的 undefined/null 错误
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unused-expressions": "off",
// 忽略以 `_` 开头的未使用变量,用于占位或为接口兼容保留参数
"@typescript-eslint/no-unused-vars": [
"warn",
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
},
],
"@typescript-eslint/no-use-before-define": "off",
// 禁止使用 require,鼓励使用 import,除非在构建/配置脚本中例外
"@typescript-eslint/no-var-requires": "error",
"unused-imports/no-unused-vars": "warn",
// 公共的规则配置
function getBaseRules(pluginTs: any) {
return {
...pluginTs.configs["eslint-recommended"]?.overrides?.[0]?.rules,
...pluginTs.configs.strict?.rules,
"@typescript-eslint/no-require-imports": "warn",
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-check": false,
"ts-expect-error": "allow-with-description",
"ts-ignore": "allow-with-description",
"ts-nocheck": "allow-with-description",
},
},
ignoresMiniprogram(pluginTs, parserTs),
ignoresScript(pluginTs, parserTs),
];
],
"@typescript-eslint/consistent-type-definitions": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-empty-function": [ "error", { allow: [ "arrowFunctions", "functions", "methods" ] } ],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-this-alias": "warn",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unused-expressions": "off",
"@typescript-eslint/no-unused-vars": [ "warn", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" } ],
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-var-requires": "error",
"unused-imports/no-unused-vars": "warn",
};
}
function ignoresMiniprogram(pluginTs: any, parserTs: any): Linter.Config {
// 创建 TypeScript 配置的辅助函数
function createTsConfig(
pluginTs: any,
parserTs: any,
options: {
extraFileExtensions?: string[];
files: string[];
ignores?: string[];
project: string;
ruleOverrides?: Record<string, any>;
},
): Linter.Config {
return {
files: [ "apps/miniprogram/**/*.?([cm])[jt]s?(x)" ],
files: options.files,
...(options.ignores && { ignores: options.ignores }),
languageOptions: {
parser: parserTs,
parserOptions: {
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: "latest",
extraFileExtensions: [ ".vue" ],
jsxPragma: "React",
project: "./tsconfig.*.json",
sourceType: "module",
...baseParserOptions,
...(options.extraFileExtensions && { extraFileExtensions: options.extraFileExtensions, jsxPragma: "React" }),
project: options.project,
},
},
plugins: {
"@typescript-eslint": pluginTs as any,
},
rules: {
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-extraneous-class": "off",
"@typescript-eslint/no-unsafe-function-type": "off",
...getBaseRules(pluginTs),
...options.ruleOverrides,
},
};
}
function ignoresScript(pluginTs: any, parserTs: any): Linter.Config {
return {
files: [ "scripts/**/*.?([cm])[jt]s?(x)" ],
languageOptions: {
parser: parserTs,
parserOptions: {
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: "latest",
extraFileExtensions: [ ".vue" ],
jsxPragma: "React",
project: "./tsconfig.*.json",
sourceType: "module",
export async function typescript(): Promise<Linter.Config[]> {
const [ pluginTs, parserTs ] = await Promise.all([
interopDefault(import("@typescript-eslint/eslint-plugin")),
interopDefault(import("@typescript-eslint/parser")),
] as const);
return [
// 源代码文件使用 tsconfig.json(包含 src 目录的文件)
createTsConfig(pluginTs, parserTs, {
files: [ "**/src/**/*.?([cm])[jt]s?(x)" ],
project: "./tsconfig.json",
extraFileExtensions: [ ".vue" ],
}),
// env.d.ts 文件使用 TypeScript 解析器
createTsConfig(pluginTs, parserTs, {
files: [ "**/env.d.ts" ],
project: "./tsconfig.json",
}),
// .d.ts 类型声明文件使用 TypeScript 解析器
createTsConfig(pluginTs, parserTs, {
files: [ "**/*.d.ts" ],
project: "./tsconfig.json",
}),
// 配置文件不启用 project,避免路径问题
{
files: [ "**/*.config.?([cm])[jt]s", "**/.*.?([cm])[jt]s" ],
languageOptions: {
parser: parserTs,
parserOptions: baseParserOptions,
},
plugins: {
"@typescript-eslint": pluginTs as any,
},
rules: getBaseRules(pluginTs),
},
plugins: {
"@typescript-eslint": pluginTs as any,
},
rules: {
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off",
},
};
// 小程序:放宽规则
createTsConfig(pluginTs, parserTs, {
files: [ "apps/miniprogram/**/*.?([cm])[jt]s?(x)" ],
project: "./tsconfig.json",
extraFileExtensions: [ ".vue" ],
ruleOverrides: {
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-extraneous-class": "off",
"@typescript-eslint/no-unsafe-function-type": "off",
},
}),
// 脚本文件:放宽 require 相关规则
createTsConfig(pluginTs, parserTs, {
files: [ "scripts/**/*.?([cm])[jt]s?(x)" ],
project: "./tsconfig.json",
extraFileExtensions: [ ".vue" ],
ruleOverrides: {
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off",
},
}),
];
}
/* eslint-disable unicorn/prefer-string-replace-all -- 此文件大量使用正则表达式,replaceAll 不支持正则 */
import type { RouteRecordRaw } from "vue-router";
import { existsSync, readdirSync, statSync } from "node:fs";
......@@ -27,6 +28,8 @@ export interface RouteGeneratorOptions {
customRules?: (filePath: string, routeConfig: RouteConfig) => null | RouteConfig;
// 排除的文件或目录
exclude?: (RegExp | string)[];
// 404 组件路径(可选,默认为 "@/views/NotFound.vue")
notFoundComponent?: string;
// 路由前缀(所有路由都会加上这个前缀)
routePrefix?: string;
// views 目录路径
......@@ -44,10 +47,10 @@ function pathToRoutePath(filePath: string, viewsDir: string): string {
// 获取相对于 views 目录的路径
const relativePath = relative(viewsDir, filePath);
// 移除文件扩展名
const pathWithoutExt = relativePath.replace(/\.(vue|tsx|jsx)$/, "");
const pathWithoutExt = relativePath.replace(/\.(?:vue|tsx|jsx)$/, "");
// 处理 index.vue 文件
let routePath = pathWithoutExt.replace(/\/index$/, "").replaceAll("\\", "/");
let routePath = pathWithoutExt.replace(/\/index$|\\/g, (match) => match === "\\" ? "/" : "");
// 转换为 kebab-case
routePath = routePath
......@@ -55,7 +58,7 @@ function pathToRoutePath(filePath: string, viewsDir: string): string {
.map((segment: string) => {
// 将 PascalCase 或 camelCase 转换为 kebab-case
return segment
.replaceAll(/([A-Z])/g, "-$1")
.replace(/([A-Z])/g, "-$1")
.toLowerCase()
.replace(/^-/, "");
})
......@@ -83,10 +86,10 @@ function pathToRoutePath(filePath: string, viewsDir: string): string {
*/
function pathToRouteName(filePath: string, viewsDir: string): string {
const relativePath = relative(viewsDir, filePath);
const pathWithoutExt = relativePath.replace(/\.(vue|tsx|jsx)$/, "");
const pathWithoutExt = relativePath.replace(/\.(?:vue|tsx|jsx)$/, "");
// 移除 index
let name = pathWithoutExt.replace(/\/index$/, "").replaceAll("\\", "/");
let name = pathWithoutExt.replace(/\/index$/, "").replace(/\\/g, "/");
// 转换为 PascalCase
name = name
......@@ -116,7 +119,7 @@ function extractTitle(filePath: string, _viewsDir: string): string {
// 如果是 index.vue,使用目录名
if (fileName === "index") {
return dirName
.replaceAll(/([A-Z])/g, " $1")
.replace(/([A-Z])/g, " $1")
.trim()
.split(" ")
.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
......@@ -125,7 +128,7 @@ function extractTitle(filePath: string, _viewsDir: string): string {
// 否则使用文件名
return fileName
.replaceAll(/([A-Z])/g, " $1")
.replace(/([A-Z])/g, " $1")
.trim()
.split(" ")
.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
......@@ -149,7 +152,7 @@ function generateAuthority(routePath: string): string {
}
// 将路径中的 / 替换为 :
authority = authority.replaceAll("/", ":");
authority = authority.replace(/\//g, ":");
// 转换为小写
return authority.toLowerCase();
......@@ -191,7 +194,7 @@ function generateRouteId(filePath: string, viewsDir: string, isIndex: boolean):
// 将目录名转换为小写 kebab-case
const dirId = dirName
.replaceAll(/([A-Z])/g, "-$1")
.replace(/([A-Z])/g, "-$1")
.toLowerCase()
.replace(/^-/, "");
......@@ -202,7 +205,7 @@ function generateRouteId(filePath: string, viewsDir: string, isIndex: boolean):
// 非 index 文件:目录名-文件名
const fileId = fileName
.replaceAll(/([A-Z])/g, "-$1")
.replace(/([A-Z])/g, "-$1")
.toLowerCase()
.replace(/^-/, "");
......@@ -213,7 +216,7 @@ function generateRouteId(filePath: string, viewsDir: string, isIndex: boolean):
* 检查文件是否应该被排除
*/
function shouldExclude(filePath: string, exclude: (RegExp | string)[] = []): boolean {
const relativePath = filePath.replaceAll("\\", "/");
const relativePath = filePath.replace(/\\/g, "/");
for (const pattern of exclude) {
if (typeof pattern === "string") {
......@@ -236,6 +239,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
viewsDir,
routePrefix = "",
exclude = [ "components", "components/", "NotFound.vue" ],
notFoundComponent = "@/views/NotFound.vue",
customRules,
} = options;
......@@ -332,7 +336,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
const directoryMap = new Map<string, FileInfo[]>();
for (const file of allFiles) {
const dir = file.directory.replaceAll("\\", "/");
const dir = file.directory.replace(/\\/g, "/");
if (!directoryMap.has(dir)) {
directoryMap.set(dir, []);
}
......@@ -348,7 +352,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
// 首先生成所有 index 文件作为父路由
for (const file of allFiles) {
if (file.isIndex && !processedFiles.has(file)) {
const dir = file.directory.replaceAll("\\", "/");
const dir = file.directory.replace(/\\/g, "/");
const dirFiles = directoryMap.get(dir) || [];
// 查找同目录下的非 index 文件作为子路由
......@@ -360,7 +364,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
// 例如:父路由 /assistant,子文件 addUpdate.vue -> 子路由路径为 add-update
const childFileName = basename(childFile.fullPath, extname(childFile.fullPath));
const childRoutePath = childFileName
.replaceAll(/([A-Z])/g, "-$1")
.replace(/([A-Z])/g, "-$1")
.toLowerCase()
.replace(/^-/, "");
......@@ -368,7 +372,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
const childId = generateRouteId(childFile.fullPath, viewsDir, false);
// 计算组件导入路径
const childRelativeToViews = relative(viewsDir, childFile.fullPath).replaceAll("\\", "/");
const childRelativeToViews = relative(viewsDir, childFile.fullPath).replace("\\", "/");
const childComponentPath = `@/views/${childRelativeToViews}`;
const childRoute: RouteRecordRaw = {
......@@ -393,7 +397,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
}
// 计算组件导入路径
const relativeToViews = relative(viewsDir, file.fullPath).replaceAll("\\", "/");
const relativeToViews = relative(viewsDir, file.fullPath).replace("\\", "/");
const componentPath = `@/views/${relativeToViews}`;
const authority = generateAuthority(file.routePath);
const routeId = generateRouteId(file.fullPath, viewsDir, true);
......@@ -429,7 +433,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
// 处理没有 index 父路由的非 index 文件(根目录下的独立文件)
for (const file of allFiles) {
if (!processedFiles.has(file)) {
const relativeToViews = relative(viewsDir, file.fullPath).replaceAll("\\", "/");
const relativeToViews = relative(viewsDir, file.fullPath).replace("\\", "/");
const componentPath = `@/views/${relativeToViews}`;
const authority = generateAuthority(file.routePath);
// 对于根目录下的独立文件,目录名为空,使用文件名作为 id
......@@ -460,12 +464,13 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
// 添加 404 路由
routes.push({
path: "/:pathMatch(.*)*",
component: () => import("@/views/NotFound.vue"),
// @ts-ignore - 动态导入路径,TypeScript 无法在编译时验证路径别名
component: () => import(/* @vite-ignore */ notFoundComponent),
meta: {
title: "404",
hidden: true,
},
});
} as RouteRecordRaw);
return routes;
}
......@@ -488,4 +493,3 @@ export function loadRouteConfig(configPath: string): RouteConfig[] {
return [];
}
}
......@@ -7,7 +7,7 @@ const rootDir = process.cwd();
const CONCURRENCY_LIMIT = 10;
// 需要跳过的目录,避免进入这些目录进行清理
const SKIP_DIRS = new Set([ ".DS_Store", ".git", ".idea", ".vscode" ]);
const SKIP_DIRS = new Set([".DS_Store", ".git", ".idea", ".vscode"]);
/**
* 处理单个文件/目录项
......@@ -104,9 +104,9 @@ async function cleanTargetsRecursively(currentDir, targets, depth = 0) {
(async function startCleanup() {
// 要删除的目录及文件名称
const targets = [ "node_modules", "dist", ".turbo", "dist.zip" ];
const targets = ["node_modules", "dist", ".turbo", "dist.zip"];
const deleteLockFile = process.argv.includes("--del-lock");
const cleanupTargets = [ ...targets ];
const cleanupTargets = [...targets];
if (deleteLockFile) {
cleanupTargets.push("pnpm-lock.yaml");
......
export default {
extends: [ "@venus/stylelint-config" ],
extends: ["@venus/stylelint-config"],
root: true,
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!