Commit 51ba6679 by liimin

feat(cli): 添加脚手架功能并完善模板

新增 CLI 脚手架功能,支持创建 React/Vue 项目并注入可选特性(路由、状态管理、UI库等)。包含以下变更:

1. 实现基础模板复制与占位符替换功能
2. 添加 React/Vue 项目模板及可选特性目录
3. 支持 package.json 合并与依赖安装
4. 完善 CLI 参数解析与帮助信息
5. 更新构建配置以支持 CJS/ESM 双格式输出
6. 添加 README 文档说明脚手架用法
0 parents
Showing 70 changed files with 1886 additions and 0 deletions
duyia
Userconfig
addwords
noneles
rangestart
compileroptions
lintstagedrc
\ No newline at end of file \ No newline at end of file
# .gitignore
# Node
node_modules/
dist/
build/
.env
.env.*
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# IDE
.vscode/
.idea/
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
#OS
.DS_Store
Thumbs.db
#TypeScript
.tsbuildinfo
#Misc
coverage/
*.local
*.cache
*.tmp
#Git
.git/
pnpm lint:prettier && pnpm lint:eslint && pnpm lint:spellcheck
pnpm precommit
export default {
"*.{js,ts,tsx,jsx,vue}": ["prettier --write", "eslint --fix"],
"*.{md,json,css,less,scss}": ["prettier --write"]
};
engine-strict=true
\ No newline at end of file \ No newline at end of file
# .prettierignore
dist
public
.local
node_modules
pnpm-lock.yaml
\ No newline at end of file \ No newline at end of file
# Venus Monorepo
## 简介
- 一个使用 `pnpm` 管理的前端/后端与组件库的 Monorepo。
- 包含应用层(`apps/frontend`, `apps/backend`)与多个可复用包(`packages/*`)。
- 统一使用 `TypeScript` 与 `Rollup` 构建,配合 `ESLint`、`Prettier`、`Husky`、`lint-staged`、`Commitlint`、`Commitizen` 保持代码与提交规范。
## 技术栈
- 工作空间与包管理:`pnpm`(`pnpm-workspace.yaml`)
- 语言:`TypeScript`
- 框架:`Vue 3`(组件库)、可扩展到 React 等
- 构建:`Rollup`(统一打包脚本)
- 代码质量:`ESLint`(含 `vue-eslint-parser`)、`Prettier`、`CSpell`
- 提交规范:`Husky`、`lint-staged`、`Commitlint`、`Commitizen`
## 环境要求
- `Node >= 20`
- `pnpm >= 10.8.1`
## 快速开始
- 安装依赖:
- `pnpm install`
- 初始化 Husky(如未自动安装):
- `pnpm prepare`
- 构建所有包:
- `pnpm build`
- 开发模式(监听并增量打包 packages):
- `node scripts/dev.js`
- 单独构建某个包:
- `node scripts/buildSingle.js <packageName>`
- 示例:`node scripts/buildSingle.js components/vue`
## 项目结构
- `apps/frontend`:前端示例或入口(`tsconfig.json` 使用 `lib: [DOM, ESNext]`)
- `apps/backend`:后端示例或入口(`tsconfig.json` 使用 `types: [node]`)
- `packages/components/vue`:Vue 组件库(输出 `esm/cjs/iife`,`vue` 为 peer 依赖)
- `packages/tools` / `packages/charts` / `packages/cli`:工具、图表、CLI 辅助库
- `scripts/`:统一构建脚本(`build.js`/`dev.js`/`buildSingle.js`/`buildBase.js`)
## 可用脚本
- 格式化:`pnpm lint:prettier`
- 代码检查与修复:`pnpm lint:eslint`
- 拼写检查:`pnpm lint:spellcheck`
- 统一构建所有包:`pnpm build`
- 使用 `Commitizen` 提交:`pnpm commit`
- 预提交钩子:`pnpm precommit`(实际由 `husky` 在 `git commit` 时触发)
## 代码规范与 Lint
- `eslint.config.js`:
- 基础:`@eslint/js` + `typescript-eslint` + `eslint-config-prettier`
- 前端与包(`apps/frontend`、`packages/*`):启用 `eslint-plugin-vue` 的推荐规则;`parser: vue-eslint-parser`,并在 `<script lang="ts">` 使用 `typescript-eslint` 的解析器;`globals: browser`。
- 后端(`apps/backend`):`globals: node`。
- 已忽略:`dist`、`node_modules`、`scripts`、`*.d.ts`、`*.md`。
- `prettier.config.js` 与 `.prettierignore`:统一代码风格,忽略 `dist`、`node_modules` 等。
- `lint-staged`(`.lintstagedrc.js`):
- `*.{js,ts,tsx,jsx,vue}` → `prettier --write`、`eslint --fix`
- `*.{md,json,css,less,scss}` → `prettier --write`
- `CSpell`(`cspell.json`):
- 自定义词典:`./.cspell/custom-dictionary.txt`
- 常见目录与文件忽略(`node_modules`, `dist`, `*.d.ts`, `package.json` 等)
## 提交规范
- 使用 `pnpm commit` 进入交互式提交(`cz-git`),遵循 `commitlint` 规则。
- 可用类型包含:`feat`、`fix`、`docs`、`style`、`refactor`、`perf`、`test`、`build`、`ci`、`chore`、`revert`、`wip`、`workflow`、`types`、`release` 等。
- `husky` 预提交钩子会运行 `lint-staged`:自动执行 `prettier` 与 `eslint`,如失败将阻止提交。
## 构建与输出
- 统一构建脚本会扫描 `packages/*`:
- 仅对存在 `src/index.ts` 的包进行构建。
- Vue 组件包会作为外部依赖保留 `vue`,并在 `iife` 格式下使用 `globals: { vue: "Vue" }`。
- 输出目录:`dist/`,默认 `esm` 与 `cjs`,Vue 组件库可额外输出 `iife`。
## 常见问题
- 推送被拒(非快进):
- `git pull --rebase venus master` → 解决冲突 → `git push -u venus master`
- ESLint 报 `process 未定义`:
- 前端文件应使用浏览器环境,移除无用的 `process` 引用或在后端环境下处理。
- 拼写检查拦截:
- 将需保留的技术术语添加到 `./.cspell/custom-dictionary.txt`,并执行 `pnpm lint:spellcheck`。
## 许可
- `ISC`
---
## Venus 脚手架(CLI)使用指南
Venus Monorepo 内置脚手架 `@venus/cli`,提供快速创建前端项目的能力,并可按需注入路由、状态管理、UI 与 ESLint 等特性。
### 命令概览
- 在工作区内使用:
- `pnpm exec venus <command>`
- 常用命令:
- `venus create <name> [--template react|vue] [--dir <path>] [--root <path>] [--no-install] [--router] [--store] [--ui <name>] [--eslint] [--force]`
- `venus build`(在仓库根目录执行 `scripts/build.js`)
- `venus ls-templates`(列出可用模板与 UI 选项)
### 默认目录策略
- 当未显式传入 `--dir` 时,CLI 会根据模板类型将项目放到:
- React:`apps/frontend/react/<name>`
- Vue:`apps/frontend/vue/<name>`
- 如需自定义路径,可使用 `--dir <path>`:最终路径为 `<dir>/<name>`。
### 可选特性
- `--router`:注入路由示例与依赖。
- `--store`:注入状态管理示例与依赖(React 使用 `@reduxjs/toolkit`,Vue 使用 `pinia`)。
- `--ui <name>`:注入 UI 库与示例(React 现有 `antd`;Vue 现有 `element-plus`)。
- `--eslint`:注入 ESLint 配置与依赖。
- `--no-install`:跳过依赖安装(默认会执行 `pnpm install`)。
- `--force`:目标目录存在且非空时,强制覆盖写入(谨慎使用)。
拷贝与合并规则:
- 模板根位于 `packages/cli/templates/<react|vue>`。
- 基础模板会复制到目标项目,并跳过 `optional/` 目录与任何 `_package.merge.json` 文件。
- 当选择可选特性时:复制对应 `optional/<feature>` 的文件至目标项目(仍跳过 `_package.merge.json`),并将该文件内容合并到目标 `package.json`:
- 合并 `dependencies`、`devDependencies`、`scripts` 等;数组去重、对象深度合并。
- 模板中的占位符 `__APP_NAME__` 会替换为项目名。
### 常用示例
- React(默认目录 + 全部可选项):
- `pnpm exec venus create flags-react --template react --router --store --ui antd --eslint --no-install`
- Vue(默认目录 + 全部可选项):
- `pnpm exec venus create flags-vue --template vue --router --store --ui element-plus --eslint --no-install`
- 指定目录:
- `pnpm exec venus create my-app --template react --dir apps/customflags --no-install`
Windows 提示:如 `--ui` 名称含连字符或可能被 Shell 误解析,推荐使用 `--ui=<name>` 写法(例:`--ui=element-plus`)。
另外,可使用 `venus ls-templates` 查看可用模板及其 UI 选项,例如:
```
- react: eslint; router; store; ui: [antd]
- vue: eslint; router; store; ui: [element-plus]
```
### 本地创建全局命令
在不发布到 npm 的前提下,也可以在本机将 `venus` 作为全局命令使用:
方法一(推荐):pnpm 全局 link
1. 构建:在仓库根执行 `node scripts/build.js`
2. 全局链接:`pnpm -C packages/cli link --global`
3. 验证:`venus --help` 或运行 `venus create ...`
4. 取消链接:`pnpm -C packages/cli unlink --global`
方法二:npm link
1. 进入 CLI 包:`cd packages/cli`
2. 构建输出:`node ../../scripts/build.js`
3. 全局链接:`npm link`
4. 取消链接:`npm unlink -g @venus/cli`(以包名为准)
环境检查:
- Windows:`where venus` 查看命令路径;确保 `pnpm bin -g` 输出的全局 bin 目录已在系统 PATH 中。
### 发布到 npm(可选)
如需发布以便团队安装使用:
- 取消或设置 `"private": false`;保证包名唯一(如 `@venus/cli`)。
- 可添加 `publishConfig`:`{"access": "public"}`。
- 构建后到 `packages/cli` 执行 `pnpm publish` 或 `npm publish`。
- 本包 `files` 已包含 `dist` 与 `templates`,发布后可直接使用 `venus` 命令及模板。
### 扩展指南
- 新增 UI 选项:在 `packages/cli/templates/<react|vue>/optional/ui/<name>/` 添加 `_package.merge.json` 与 `src/` 示例;使用 `--ui <name>` 即可注入。
- 新增可选特性(如 testing):在 `optional/testing/` 下放置 `_package.merge.json` 与示例,并在 CLI 入口增加对应标志与 `applyOptionalFeature` 调用。
- 新增模板(如 svelte):在 `templates/svelte/` 下建立基础模板与 `optional/` 特性;并在 CLI 逻辑中扩展默认目录策略或在命令中显式传 `--dir`。
### 排错
- 找不到 `venus` 命令:检查是否已 link,或确认全局 bin 目录已加入 PATH。Windows 用 `where venus` 检查。
- 模板不存在:确认 `packages/cli/templates/<name>` 存在,并与 `--template` 值一致。
- 安装失败:进入项目目录手动执行 `pnpm install`,或移除 `--no-install`。
- CJS/ESM 冲突:确保 CLI 包 `package.json` 的 `type` 为 `commonjs` 并重新构建。
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");
});
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"types": [],
"lib": ["ESNext", "DOM"]
}
}
/**@type {import('cz-git').Userconfig}*/
export default {
extends: ["@commitlint/config-conventional"],
rules: {
// @see: https://commitlint.js.org/#/reference-rules
"body-leading-blank": [2, "always"],
"footer-leading-blank": [1, "always"],
"header-max-length": [2, "always", 108],
"subject-empty": [2, "never"],
"type-empty": [2, "never"],
"subject-case": [0],
"type-enum": [
2,
"always",
[
"feat",
"fix",
"docs",
"style",
"refactor",
"perf",
"test",
"build",
"ci",
"chore",
"revert",
"wip",
"workflow",
"types",
"release"
]
]
},
prompt: {
scopes: ["root", "backend", "frontend", "components", "utils"],
allowCustomScopes: true,
skipQuestions: ["body", "footer", "footerPrefix", "breaking"], //跳过"详细描述" 和 "底部信息"
messages: {
type: "请选择提交类型:",
scope: "请输入修改范围(可选):",
customScope: "请输入自定义修改范围:",
subject: "请输入简短的变更描述:",
body: '请输入详细的变更描述(可选)。使用"|"换行:',
footer: "请输入要关闭的问题(可选):",
confirmCommit: "是否确认提交变更?"
},
types: [
{ value: "feat", name: "feat: 新增功能" },
{ value: "fix", name: "fix: 修复 bug" },
{ value: "docs", name: "docs: 文档变更" },
{ value: "style", name: "style: 代码格式(不影响功能, 例如空格、分号等格式修正)" },
{ value: "refactor", name: "refactor: 代码重构(不包括 bug 修复, 功能新增)" },
{ value: "perf", name: "perf: 性能优化" },
{ value: "test", name: "test: 添加疏漏测试或已有测试改动" },
{ value: "build", name: "build: 构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)" },
{ value: "ci", name: "ci: 修改 CI 配置、脚本" },
{ value: "chore", name: "chore: 对构建过程或辅助工具和库的更改(不影响源文件、测试用例)" },
{ value: "revert", name: "revert: 回滚 commit" },
{ value: "wip", name: "wip: 进行中" },
{ value: "workflow", name: "workflow: 工作流改进" },
{ value: "types", name: "types: 类型定义文件更改" },
{ value: "release", name: "release: 发布版本" }
]
}
};
{
"import": ["@cspell/dict-lorem-ipsum/cspell-ext.json"],
"caseSensitive": false,
"dictionaries": ["custom-dictionary"],
"dictionaryDefinitions": [
{
"name": "custom-dictionary",
"path": "./.cspell/custom-dictionary.txt",
"addwords": true
}
],
"ignorePaths": [
"**/node_modules/**",
"**/dist/**",
"**/build/**",
"**/docs/**",
"**/vendor/**",
"**/public/**",
"**/static/**",
"**/out/**",
"**/tmp/**",
"**/*.d.ts",
"**/package-lock.json",
"**/package.json",
"**/cache/**",
"**/logs/**"
]
}
import { defineConfig } from "eslint/config";
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintPluginPrettier from "eslint-plugin-prettier";
import eslintPluginVue from "eslint-plugin-vue";
import vueParser from "vue-eslint-parser";
import globals from "globals";
import eslintConfigPrettier from "eslint-config-prettier/flat";
import { rules } from "eslint-config-prettier";
const ignores = ["**/dist/**", "**/node_modules/**", ".*", "scripts/**", "**/*.d.ts", "**/*.md"];
export default defineConfig(
{
// 通用配置
ignores, // 忽略项
extends: [eslint.configs.recommended, ...tseslint.configs.recommended, eslintConfigPrettier], // 继承规则
plugins: {
prettier: eslintPluginPrettier
// vue: eslintPluginVue,
},
languageOptions: {
ecmaVersion: "latest", //ecma版本
sourceType: "module", //es模块
parser: tseslint.parser // 使用 TypeScript 解析器
},
rules: {
"no-var": "error", //禁用var,使用let或const代替
...rules
}
},
//前端配置
{
ignores,
files: ["apps/frontend/**/*.{ts,js,tsx,jsx,vue}", "packages/**/*.{ts,js,tsx,jsx,vue}"],
extends: [...eslintPluginVue.configs["flat/recommended"], eslintConfigPrettier],
languageOptions: {
parser: vueParser,
parserOptions: {
parser: tseslint.parser
},
globals: {
...globals.browser
}
}
},
// 后端配置
{
ignores,
files: ["apps/backend/**/*.{ts,js}"],
languageOptions: {
globals: {
...globals.node
}
}
}
);
{
"name": "venus",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint:prettier": "prettier --write \"**/*.{js,ts,mjs,cjs,json,tsx,css,less,scss,vue,html,md}\"",
"lint:eslint": "eslint --fix \"**/*.{js,ts,mjs,cjs,json,tsx,css,less,scss,vue,html,md}\"",
"lint:spellcheck": "cspell lint \"(packages|apps)/**/*\" --config cspell.json \"**/*.{js,ts,mjs,cjs,json,css,less,scss,vue,html,md}\"",
"commit": "cz",
"prepare": "husky",
"precommit": "lint-staged",
"build": "venus build",
"postinstall": "node scripts/build.js",
"venus": "venus"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-git"
}
},
"keywords": [],
"author": "liimin",
"license": "ISC",
"packageManager": "pnpm@10.8.1",
"engines": {
"node": ">=20",
"npm": ">=9",
"pnpm": ">=10.8.1"
},
"devDependencies": {
"@venus/cli": "workspace:*",
"@commitlint/cli": "^20.0.0",
"@commitlint/config-conventional": "^20.0.0",
"@cspell/dict-lorem-ipsum": "^4.0.5",
"@eslint/js": "^9.36.0",
"@rollup/plugin-commonjs": "^28.0.6",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-terser": "^0.4.4",
"@types/node": "^24.5.2",
"@vitejs/plugin-vue": "^6.0.1",
"commitizen": "^4.3.1",
"cspell": "^9.2.1",
"cz-git": "^1.12.0",
"eslint": "^9.36.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"eslint-plugin-vue": "^10.5.0",
"globals": "^16.4.0",
"husky": "^9.1.7",
"lint-staged": "^16.2.6",
"prettier": "^3.6.2",
"rollup": "^4.52.3",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-typescript2": "^0.36.0",
"rollup-plugin-vue": "^6.0.0",
"typescript": "^5.9.2",
"typescript-eslint": "^8.44.1",
"vue-eslint-parser": "^10.2.0"
},
"dependencies": {
"vue": "^3.5.22"
}
}
{
"name": "@venus/charts",
"private": true,
"version": "0.0.1",
"description": "Venus charts utilities",
"type": "module",
"main": "./dist/index.cjs.js",
"module": "./dist/index.esm.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs.js"
}
},
"files": [
"dist"
],
"buildOptions": {
"formats": [
"esm",
"cjs"
],
"name": "VenusCharts"
},
"devDependencies": {
"typescript": "*"
}
}
export const version = "0.0.1";
export type ChartPoint = { x: number; y: number };
export function lineSeries(points: ChartPoint[]) {
return points.map(p => ({ x: p.x, y: p.y }));
}
export function minMax(points: ChartPoint[]) {
let minX = Infinity,
maxX = -Infinity,
minY = Infinity,
maxY = -Infinity;
for (const p of points) {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
}
return { minX, maxX, minY, maxY };
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationDir": "./dist",
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"],
"lib": ["ES2020"],
"moduleResolution": "bundler",
"skipLibCheck": true,
"isolatedModules": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
# Venus CLI
一个用于快速搭建前端项目的脚手架工具,内置 React/Vue 基础模板与可选特性注入(路由、状态管理、UI、ESLint)。
- 命令:`venus create`、`venus build`、`venus ls-templates`、`--help`、`--version`
- 支持模板:`react`、`vue`
- 可选特性:`--router`、`--store`、`--ui <name>`、`--eslint`
## 安装与环境要求
- Node:`>=20`
- 包管理器:`pnpm >= 10`
- 在工作区执行:`pnpm install`
- 安装后会自动构建工作区包(通过根项目的 `postinstall`),确保 CLI 的 `dist` 可用。
- 在工作区内可直接通过 `pnpm` 运行 CLI(例如:`pnpm venus --help` 或在脚本里写 `venus build`)。
- 如果想在系统终端直接输入 `venus`(不加 `pnpm`)运行:
1) `pnpm setup`(配置 `PNPM_HOME` 到 PATH,新开终端生效)
2) `pnpm -C packages/cli link --global`
> 推荐在本仓库内通过 `pnpm` 调用 CLI(`pnpm venus` 或在 `package.json` 的脚本里写 `venus`)。
## 快速开始(Quick Start)
创建一个 React/Vue 项目(默认生成目录:`apps/frontend/<react|vue>/<name>`):
- React 基础项目(不安装依赖):
```bash
pnpm exec venus create my-react-app --template react --no-install
```
- Vue 基础项目(不安装依赖):
```bash
pnpm exec venus create my-vue-app --template vue --no-install
```
进入项目目录后:
```bash
pnpm install
pnpm run dev
```
## 命令说明
- `venus create <name> [options]`
- 生成一个前端项目(React 或 Vue)。
- 选项:
- `--template <name>` 模板名称,`react|vue`,默认 `react`
- `--dir <path>` 自定义生成目录前缀,最终路径为 `<dir>/<name>`
- `--root <path>` 指定生成根目录,默认当前工作目录
- `--no-install` 跳过依赖安装(默认安装)
- `--router` 注入路由
- `--store` 注入状态管理
- `--ui <name>` 注入 UI 库(React:`antd`;Vue:`element-plus`)
- `--eslint` 注入 ESLint 配置
- `--force` 目标目录非空时强制写入(默认保护非空目录)
- `venus build`
- 执行仓库根目录 `scripts/build.js`,构建工作区内所有包。
- `venus ls-templates`
- 列出当前可用模板与其可选特性(例如 `router`、`store`、`ui: [antd|element-plus]`、`eslint`)。
- `venus --help | -h`
- 打印帮助信息。
- `venus --version | -v`
- 打印 CLI 版本。
## 目录策略与占位符
- 默认生成目录:
- React:`apps/frontend/react/<name>`
- Vue:`apps/frontend/vue/<name>`
- 模板内存在占位符 `__APP_NAME__`,在生成时会被替换为 `<name>`。
## 可选特性注入与依赖合并
- 所有可选特性位于模板目录的 `optional` 子目录下,例如:
- React:`packages/cli/templates/react/optional/...`
- Vue:`packages/cli/templates/vue/optional/...`
- 每个可选特性目录可能包含 `_package.merge.json`,在生成时将被合并到目标项目的 `package.json` 里:
- 例如 React Router:会自动将 `react-router-dom` 依赖合并到目标项目。
- 例如 Vue Router:会自动将 `vue-router` 依赖合并到目标项目。
- 文件复制时会排除 `_package.merge.json` 本体,仅合并其内容到目标项目的 `package.json`。
## 模板细节与示例
### React 模板
- 基础文件:`index.html`、`src/main.tsx`、`src/App.tsx`、`vite.config.ts`、`tsconfig.json`、`Readme.md`
- 可选特性:
- `--router`
- 覆盖入口 `src/main.tsx`,自动包裹 `BrowserRouter`。
- `--store`
- 使用 `zustand` 提供简单的计数器示例(`src/store/counter.ts`、`src/components/Counter.tsx`)。
- `--ui antd`
- 引入 `antd` 并提供一个示例组件 `src/ui.tsx`。
- `--eslint`
- 注入 `.eslintrc.json` 基本配置。
示例:
```bash
pnpm exec venus create my-react --template react --router --store --ui antd --eslint --no-install
```
### Vue 模板
- 基础文件:`index.html`、`src/main.ts`、`src/App.vue`、`vite.config.ts`、`tsconfig.json`、`src/env.d.ts`、`Readme.md`
- 可选特性:
- `--router`
- 生成 `src/router.ts`,需在 `src/main.ts` 中手动 `app.use(router)`(生成后可自行接入)。
- `--store`
- 生成 `src/store/index.ts`,需在 `src/main.ts` 中手动 `app.use(pinia)`。
- `--ui element-plus`
- 生成 `src/ui.ts`,可在 `main.ts` 中 `setupUI(app)` 完成接入。
- `--eslint`
- 注入 `.eslintrc.json` 基本配置。
示例:
```bash
pnpm exec venus create my-vue --template vue --router --store --ui element-plus --eslint --no-install
```
接入(main.ts 示例):
```ts
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'
import { pinia } from './store'
import { setupUI } from './ui'
const app = createApp(App)
app.use(router)
app.use(pinia)
setupUI(app)
app.mount('#app')
```
## 目标目录非空保护与覆盖
- 生成前会检查目标目录是否存在且非空:
- 若非空且未指定 `--force`,会终止并提示。
- 指定 `--force` 则会继续写入(请谨慎使用)。
## 高级用法
- 自定义输出路径:
- `--dir <path>`:指定目录前缀(最终路径为 `<dir>/<name>`)。
- `--root <path>`:改变生成根路径(默认是当前工作目录)。
示例:
```bash
pnpm exec venus create demo --template react --dir apps/custom --root D:/work/venus --no-install
# 结果:D:/work/venus/apps/custom/demo
```
- 跳过依赖安装:
```bash
pnpm exec venus create demo --no-install
# 进入生成目录后自行执行 pnpm install
```
## 在脚本与命令行中的调用方式
- 项目脚本内(`package.json`)可以直接写:
```json
{
"scripts": {
"build": "venus build"
}
}
```
- 在工作区终端中:
- `pnpm venus --help` 或 `pnpm exec venus --help`
- 全局命令(可选):
- `pnpm setup` 后运行 `pnpm -C packages/cli link --global`
- 新开一个终端后直接:`venus --help`
## 常见问题(FAQ)
- 执行 `venus` 提示找不到命令?
- 在工作区用 `pnpm` 调用:`pnpm exec venus --help` 或 `pnpm venus --help`
- 或完成一次全局配置(见上文“全局命令”)。
- 可选特性为何没有生效?
- React Router 会覆盖入口以启用路由;Vue Router/Pinia/Element-Plus 需要在 `main.ts` 中自行接入(见示例)。
- 生成后的依赖冲突?
- 可选特性通过 `_package.merge.json` 合并依赖。若手动修改依赖版本导致冲突,请根据自身项目锁定版本后再安装。
- 非空目录如何覆盖?
- 使用 `--force`,但建议先做好备份或在空目录生成。
---
如需补充新的模板或 UI 库(如 React 的 `mantine` 或 Vue 的 `naive-ui`),欢迎在 `packages/cli/templates` 下新增对应目录并调整 `ls-templates` 输出。
\ No newline at end of file \ No newline at end of file
{
"name": "@venus/cli",
"private": true,
"version": "0.0.1",
"description": "Venus CLI helpers",
"type": "commonjs",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"scripts": {
"prepare": "node ../../scripts/buildSingle.js packages/cli"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"bin": {
"venus": "./dist/index.cjs"
},
"files": [
"dist",
"templates"
],
"buildOptions": {
"formats": [
"esm",
"cjs"
],
"name": "VenusCli"
},
"devDependencies": {
"typescript": "*"
}
}
# __APP_NAME__ (React + Vite + TS)
- 开发:`pnpm dev`
- 构建:`pnpm build`
- 预览:`pnpm preview`
可选特性(若在脚手架选择):
- 路由:`react-router-dom`
- 状态管理:`@reduxjs/toolkit` + `react-redux`
- UI:`antd`
- ESLint:基础配置 `.eslintrc.json`
\ No newline at end of file \ No newline at end of file
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__APP_NAME__</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
{
"root": true,
"env": { "browser": true, "es2020": true },
"parserOptions": { "ecmaVersion": 2020, "sourceType": "module" },
"extends": ["eslint:recommended", "plugin:react/recommended", "plugin:react-hooks/recommended"],
"settings": { "react": { "version": "detect" } }
}
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"react-router-dom": "^6.27.0"
}
}
\ No newline at end of file \ No newline at end of file
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "../App";
const container = document.getElementById("root")!;
createRoot(container).render(
<BrowserRouter>
<App />
</BrowserRouter>
);
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"zustand": "^4.4.0"
}
}
\ No newline at end of file \ No newline at end of file
import React from "react";
import { useCounter } from "../store/counter";
export function Counter() {
const { count, inc, dec } = useCounter();
return (
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<button onClick={dec}>-</button>
<span>{count}</span>
<button onClick={inc}>+</button>
</div>
);
}
\ No newline at end of file \ No newline at end of file
import { create } from "zustand";
type CounterState = {
count: number;
inc: () => void;
dec: () => void;
};
export const useCounter = create<CounterState>((set) => ({
count: 0,
inc: () => set((s) => ({ count: s.count + 1 })),
dec: () => set((s) => ({ count: s.count - 1 })),
}));
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"antd": "^5.19.4"
}
}
\ No newline at end of file \ No newline at end of file
import React from "react";
import { Button } from "antd";
export default function Demo() {
return <Button type="primary">Antd Button</Button>;
}
\ No newline at end of file \ No newline at end of file
{
"name": "__APP_NAME__",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -p tsconfig.json && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.34",
"@types/react-dom": "^18.2.14",
"@vitejs/plugin-react": "^4.2.0",
"typescript": "^5.4.0",
"vite": "^5.0.0"
}
}
\ No newline at end of file \ No newline at end of file
import React from "react";
export default function App() {
return (
<div style={{ padding: 24 }}>
<h1>Welcome to __APP_NAME__</h1>
<p>This project was scaffolded by Venus CLI.</p>
</div>
);
}
\ No newline at end of file \ No newline at end of file
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
const container = document.getElementById("root")!;
createRoot(container).render(<App />);
\ No newline at end of file \ No newline at end of file
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true
},
"include": ["src"]
}
\ No newline at end of file \ No newline at end of file
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
});
# __APP_NAME__
该项目由 Venus CLI 脚手架生成,使用 Vite + Vue 3 + TypeScript。
\ No newline at end of file \ No newline at end of file
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__APP_NAME__</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
{
"root": true,
"env": { "browser": true, "es2020": true },
"parserOptions": { "ecmaVersion": 2020, "sourceType": "module" },
"extends": ["eslint:recommended", "plugin:vue/vue3-recommended"],
"rules": {}
}
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"vue-router": "^4.3.0"
}
}
\ No newline at end of file \ No newline at end of file
import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
const routes: RouteRecordRaw[] = [
{ path: "/", component: () => import("./App.vue") }
];
export const router = createRouter({
history: createWebHistory(),
routes
});
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"pinia": "^2.1.7"
}
}
\ No newline at end of file \ No newline at end of file
import { createPinia } from "pinia";
export const pinia = createPinia();
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
"element-plus": "^2.6.3"
}
}
\ No newline at end of file \ No newline at end of file
import type { App } from "vue";
import ElementPlus from "element-plus";
export function setupUI(app: App) {
app.use(ElementPlus);
}
\ No newline at end of file \ No newline at end of file
{
"name": "__APP_NAME__",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.4.27"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.0.4",
"typescript": "^5.4.5",
"vite": "^5.2.10",
"vue-tsc": "^2.0.21"
}
}
\ No newline at end of file \ No newline at end of file
<template>
<div style="padding: 24px">
<h1>Welcome to __APP_NAME__</h1>
<p>This project was scaffolded by Venus CLI.</p>
</div>
</template>
<script setup lang="ts"></script>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial; }
</style>
\ No newline at end of file \ No newline at end of file
/// <reference types="vite/client" />
\ No newline at end of file \ No newline at end of file
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");
\ No newline at end of file \ No newline at end of file
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"allowJs": true,
"strict": true,
"types": ["vite/client"]
}
}
\ No newline at end of file \ No newline at end of file
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()]
});
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationDir": "./dist",
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"],
"lib": ["ES2020"],
"moduleResolution": "bundler",
"skipLibCheck": true,
"isolatedModules": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
{
"name": "@venus/components-vue",
"version": "1.0.0",
"description": "Vue components library for Venus design system",
"main": "./dist/index.cjs.js",
"module": "./dist/index.esm.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs.js"
},
"./dist/*": "./dist/*"
},
"files": [
"dist",
"src"
],
"scripts": {
"clean": "rimraf dist",
"type-check": "vue-tsc --noEmit",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"vue",
"components",
"ui",
"venus",
"design-system"
],
"author": "liimin",
"license": "ISC",
"dependencies": {
"vue": "^3.5.22"
},
"devDependencies": {
"@types/node": "^24.5.2",
"@vue/typescript-plugin": "^3.1.0",
"rimraf": "^6.0.1",
"typescript": "^5.9.2",
"vue-tsc": "^3.1.0"
},
"peerDependencies": {
"vue": "^3.0.0"
},
"buildOptions": {
"name": "VenusComponentsVue",
"formats": [
"esm",
"cjs",
"iife"
]
}
}
<template>
<button
:type="type"
:class="[
'v-button',
`v-button--${variant}`,
`v-button--${size}`,
{
'v-button--disabled': disabled,
'v-button--loading': loading
}
]"
:disabled="disabled || loading"
@click="handleClick"
>
<span v-if="loading" class="v-button__loading">⏳</span>
<span v-if="icon && !loading" class="v-button__icon">{{ icon }}</span>
<span v-if="$slots.default" class="v-button__content">
<slot />
</span>
</button>
</template>
<script lang="ts">
// Props 定义
export interface VButtonProps {
type?: "button" | "submit" | "reset";
size?: "small" | "medium" | "large";
variant?: "primary" | "secondary" | "danger" | "ghost";
disabled?: boolean;
loading?: boolean;
icon?: string;
}
// Emits 定义
export interface VButtonEmits {
click: [event: MouseEvent];
}
</script>
<script setup lang="ts">
const props = withDefaults(defineProps<VButtonProps>(), {
type: "button",
size: "medium",
variant: "primary",
disabled: false,
loading: false,
icon: ""
});
const emit = defineEmits<VButtonEmits>();
// 点击事件处理
const handleClick = (event: Event) => {
if (!props.disabled && !props.loading) {
emit("click", event as MouseEvent);
}
};
</script>
<style scoped>
.venus-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 8px 16px;
border: 1px solid transparent;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
line-height: 1.5;
cursor: pointer;
transition: all 0.2s ease-in-out;
user-select: none;
}
.venus-button:focus {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* 尺寸变体 */
.venus-button--small {
padding: 4px 8px;
font-size: 12px;
}
.venus-button--medium {
padding: 8px 16px;
font-size: 14px;
}
.venus-button--large {
padding: 12px 24px;
font-size: 16px;
}
/* 颜色变体 */
.venus-button--primary {
background-color: #3b82f6;
color: white;
border-color: #3b82f6;
}
.venus-button--primary:hover:not(:disabled) {
background-color: #2563eb;
border-color: #2563eb;
}
.venus-button--secondary {
background-color: #6b7280;
color: white;
border-color: #6b7280;
}
.venus-button--secondary:hover:not(:disabled) {
background-color: #4b5563;
border-color: #4b5563;
}
.venus-button--danger {
background-color: #ef4444;
color: white;
border-color: #ef4444;
}
.venus-button--danger:hover:not(:disabled) {
background-color: #dc2626;
border-color: #dc2626;
}
.venus-button--ghost {
background-color: transparent;
color: #3b82f6;
border-color: #3b82f6;
}
.venus-button--ghost:hover:not(:disabled) {
background-color: #3b82f6;
color: white;
}
/* 状态 */
.venus-button--disabled,
.venus-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.venus-button--loading {
cursor: not-allowed;
}
.venus-button--icon-only {
padding: 8px;
}
.venus-button--icon-only.venus-button--small {
padding: 4px;
}
.venus-button--icon-only.venus-button--large {
padding: 12px;
}
.venus-button__loading {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
import VButton from "./VButton.vue";
export { VButton };
export default VButton;
// @ts-nocheck
export {};
declare module "vue" {
export interface GlobalComponents {}
export interface GlobalDirectives {}
}
declare global {
const __VLS_directiveBindingRestFields: { instance: null; oldValue: null; modifiers: any; dir: any };
const __VLS_unref: typeof import("vue").unref;
const __VLS_placeholder: any;
type __VLS_NativeElements = __VLS_SpreadMerge<SVGElementTagNameMap, HTMLElementTagNameMap>;
type __VLS_IntrinsicElements = globalThis.JSX.IntrinsicElements;
type __VLS_Element = globalThis.JSX.Element;
type __VLS_GlobalComponents = import("vue").GlobalComponents &
Pick<typeof import("vue"), "Transition" | "TransitionGroup" | "KeepAlive" | "Suspense" | "Teleport">;
type __VLS_GlobalDirectives = import("vue").GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_SpreadMerge<A, B> = Omit<A, keyof B> & B;
type __VLS_WithComponent<
N0 extends string,
LocalComponents,
Self,
N1 extends string,
N2 extends string,
N3 extends string
> = N1 extends keyof LocalComponents
? { [K in N0]: LocalComponents[N1] }
: N2 extends keyof LocalComponents
? { [K in N0]: LocalComponents[N2] }
: N3 extends keyof LocalComponents
? { [K in N0]: LocalComponents[N3] }
: Self extends object
? { [K in N0]: Self }
: N1 extends keyof __VLS_GlobalComponents
? { [K in N0]: __VLS_GlobalComponents[N1] }
: N2 extends keyof __VLS_GlobalComponents
? { [K in N0]: __VLS_GlobalComponents[N2] }
: N3 extends keyof __VLS_GlobalComponents
? { [K in N0]: __VLS_GlobalComponents[N3] }
: {};
type __VLS_FunctionalComponentCtx<T, K> = __VLS_PickNotAny<
"__ctx" extends keyof __VLS_PickNotAny<K, {}> ? (K extends { __ctx?: infer Ctx } ? NonNullable<Ctx> : never) : any,
T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>;
type __VLS_FunctionalComponentProps<T, K> = "__ctx" extends keyof __VLS_PickNotAny<K, {}>
? K extends { __ctx?: { props?: infer P } }
? NonNullable<P>
: never
: T extends (props: infer P, ...args: any) => any
? P
: {};
type __VLS_FunctionalComponent<T> = (
props: (T extends { $props: infer Props } ? Props : {}) & Record<string, unknown>,
ctx?: any
) => __VLS_Element & {
__ctx?: {
attrs?: any;
slots?: T extends { $slots: infer Slots } ? Slots : Record<string, any>;
emit?: T extends { $emit: infer Emit } ? Emit : {};
props?: (T extends { $props: infer Props } ? Props : {}) & Record<string, unknown>;
expose?: (exposed: T) => void;
};
};
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
? false
: true
: false
: false;
type __VLS_NormalizeComponentEvent<
Props,
Emits,
onEvent extends keyof Props,
Event extends keyof Emits,
CamelizedEvent extends keyof Emits
> =
__VLS_IsFunction<Props, onEvent> extends true
? Props
: __VLS_IsFunction<Emits, Event> extends true
? { [K in onEvent]?: Emits[Event] }
: __VLS_IsFunction<Emits, CamelizedEvent> extends true
? { [K in onEvent]?: Emits[CamelizedEvent] }
: Props;
// fix https://github.com/vuejs/language-tools/issues/926
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends (
arg: infer P
) => unknown
? P
: never;
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R
? U extends T
? never
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R)
: never;
type __VLS_OverloadUnion<T> = Exclude<
__VLS_OverloadUnionInner<(() => never) & T>,
T extends () => never ? never : () => never
>;
type __VLS_ConstructorOverloads<T> =
__VLS_OverloadUnion<T> extends infer F
? F extends (event: infer E, ...args: infer A) => any
? { [K in E & string]: (...args: A) => void }
: never
: never;
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never;
}
>
>;
type __VLS_EmitsToProps<T> = __VLS_PrettifyGlobal<{
[K in string & keyof T as `on${Capitalize<K>}`]?: (
...args: T[K] extends (...args: infer P) => any ? P : T[K] extends null ? any[] : never
) => any;
}>;
type __VLS_ResolveEmits<
Comp,
Emits,
TypeEmits = {},
NormalizedEmits = __VLS_NormalizeEmits<Emits> extends infer E ? (string extends keyof E ? {} : E) : never
> = __VLS_SpreadMerge<NormalizedEmits, TypeEmits>;
type __VLS_ResolveDirectives<T> = {
[K in keyof T & string as `v${Capitalize<K>}`]: T[K];
};
type __VLS_PrettifyGlobal<T> = { [K in keyof T as K]: T[K] } & {};
type __VLS_WithDefaultsGlobal<P, D> = {
[K in keyof P as K extends keyof D ? K : never]-?: P[K];
} & {
[K in keyof P as K extends keyof D ? never : K]: P[K];
};
type __VLS_UseTemplateRef<T> = Readonly<import("vue").ShallowRef<T | null>>;
type __VLS_ProxyRefs<T> = import("vue").ShallowUnwrapRef<T>;
function __VLS_getVForSourceType<T extends number | string | any[] | Iterable<any>>(
source: T
): [
item: T extends number
? number
: T extends string
? string
: T extends any[]
? T[number]
: T extends Iterable<infer T1>
? T1
: any,
index: number
][];
function __VLS_getVForSourceType<T>(source: T): [item: T[keyof T], key: keyof T, index: number][];
function __VLS_getSlotParameters<S, D extends S>(slot: S, decl?: D): D extends (...args: infer P) => any ? P : any[];
function __VLS_asFunctionalDirective<T>(
dir: T
): T extends import("vue").ObjectDirective
? NonNullable<T["created" | "beforeMount" | "mounted" | "beforeUpdate" | "updated" | "beforeUnmount" | "unmounted"]>
: T extends (...args: any) => any
? T
: (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(
t: T,
instance?: K
): T extends new (...args: any) => any
? __VLS_FunctionalComponent<K>
: T extends () => any
? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any
? T
: __VLS_FunctionalComponent<{}>;
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(
t: T
): 2 extends Parameters<T>["length"] ? [any] : [];
function __VLS_asFunctionalElement<T>(tag: T, endTag?: T): (attrs: T & Record<string, unknown>) => void;
function __VLS_asFunctionalSlot<S>(slot: S): S extends () => infer R ? (props: {}) => R : NonNullable<S>;
function __VLS_tryAsConstant<const T>(t: T): T;
}
// 组件导出
export { default as VButton } from "./VButton";
// 类型导出 - 暂时注释掉,因为 Vue 组件的类型导出在构建时有问题
// export type { VButtonProps, VButtonEmits } from './VButton/VButton.vue'
// 版本信息
export const version = "1.0.0";
// 导入组件用于默认导出
import VButton from "./VButton";
// 默认导出所有组件
export default {
VButton,
version
};
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"],
"lib": ["DOM", "ES2020"],
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"isolatedModules": true
},
"vueCompilerOptions": {
"target": 3,
"globalTypesPath": "./src/global.d.ts"
},
"include": ["src/**/*", "src/global.d.ts"],
"exclude": ["node_modules", "dist"]
}
{
"name": "@venus/tools",
"version": "0.1.0",
"description": "Utilities for Venus",
"main": "./dist/index.cjs.js",
"module": "./dist/index.esm.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs.js"
},
"./dist/*": "./dist/*"
},
"files": [
"dist",
"src"
],
"buildOptions": {
"name": "VenusTools",
"formats": [
"esm",
"cjs"
]
}
}
// Venus tools entry
export const version = "0.1.0";
export function noop(): void {}
export function sum(a: number, b: number): number {
return a + b;
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"],
"lib": ["ES2020"],
"moduleResolution": "bundler",
"skipLibCheck": true,
"isolatedModules": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
This diff could not be displayed because it is too large.
packages:
- "packages/*"
- "apps/frontend/*"
- "apps/backend/*"
// prettier.config.js
/**
* @type {import('prettier').config}
* @see https://www.prettier.cn/docs/options.html
*/
export default {
// 指定最大换行长度
printWidth: 120,
//缩进制表符宽度|空格数
tabWidth: 2,
//使用制表符而不是空格缩进行(true:制表符,false:空格)
useTabs: false,
//结尾不用分号(true:有,false:没有)
semi: true,
//使用单引号(true:单引号,false:双引号)
singleQuote: false,
// 在对象字面量中决定是否将属性名用引号括起来 可选值"<as-needed|con
quoteProps: "as-needed",
//在JSX中使用单引号而不是双引号(true:单引号,false:双引号)
jsxSingleQuote: false,
// 多行时尽可能打印尾随逗号 可选值"<noneles5|all>"
trailingComma: "none",
//在对象字面量中是否需要用空格括起来(true:需要,false:不需要)
bracketSpacing: true,
//将{>}多行元素放在最后一行的末尾,而不是单独放在下一行(true:放末尾,false:单独一行)
bracketSameLine: false,
//(x)={>}<{><}>箭头函数参数只有一个时是否要有小括号(avoid:省略括号,always:不省略括号)
arrowParens: "avoid",
//指定要使用的解析器,不需要写文件开头的 @prettier
requirePragma: false,
//可以在文件顶部插入一个特殊标记,指定该文件已使用 Prettier 格式化
insertPragma: false,
//用于控制文本是否应该被换行以及如何进行换行
proseWrap: "preserve",
//在htm中空格是否是敏感的“css”。遵守 C5S 显示属性的默认值,"strict”。空格被认为是敏感的,“ignore”。 空格被认为是不敏感的
htmlWhitespaceSensitivity: "css",
//控制在 Vue 单文件组件中{<}script{>}和{<}style{>}标签内的代码缩进方式
vueIndentScriptAndStyle: false,
//换行符使用 1f 结尾是 可选值"{<}auto|lf|crlf|cr{>}"
endOfLine: "auto",
///这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码(rangestart:开始,rangeEnd:结束)
rangeStart: 0,
rangeEnd: Infinity
};
// 进行统一打包管理 rollup
import { rollup } from "rollup";
import { getRollupConfigs, clearDist } from "./buildBase.js";
import terser from "@rollup/plugin-terser";
async function build() {
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
clearDist(name);
const config = configs[name];
console.log(`正在打包:${name}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成:${name}`);
}
}
build();
import path from "node:path";
import fs from "node:fs";
import URL from "node:url";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";
import postcss from "rollup-plugin-postcss";
const __filename = URL.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function discoverPackages() {
const base = path.resolve(__dirname, "../packages");
const result = [];
// tools
const toolsPath = path.resolve(base, "tools");
if (fs.existsSync(path.resolve(toolsPath, "package.json"))) {
result.push("tools");
}
// charts
const chartsPath = path.resolve(base, "charts");
if (fs.existsSync(path.resolve(chartsPath, "package.json"))) {
result.push("charts");
}
// cli
const cliPath = path.resolve(base, "cli");
if (fs.existsSync(path.resolve(cliPath, "package.json"))) {
result.push("cli");
}
// components/*
const componentsPath = path.resolve(base, "components");
if (fs.existsSync(componentsPath)) {
const subs = fs.readdirSync(componentsPath, { withFileTypes: true });
for (const dirent of subs) {
if (dirent.isDirectory()) {
const name = dirent.name;
const pkgPath = path.resolve(componentsPath, name, "package.json");
if (fs.existsSync(pkgPath)) {
result.push(`components/${name}`);
}
}
}
}
return result;
}
function getPackageRoots() {
const pkgs = discoverPackages();
return pkgs.map(pkg => path.resolve(__dirname, `../packages`, pkg));
}
async function packageJson(root) {
const pkgPath = path.resolve(root, "package.json");
const content = await fs.promises.readFile(pkgPath, "utf-8");
return JSON.parse(content);
}
export async function getRollupConfig(root) {
const config = await packageJson(root);
const tsconfig = path.resolve(root, "tsconfig.json");
const { name, formats = ["esm", "cjs"] } = config.buildOptions || {};
const dist = path.resolve(root, "./dist");
const entry = path.resolve(root, "./src/index.ts");
if (!fs.existsSync(entry)) {
return null;
}
const isVue = /components[\\/]+vue$/.test(root) || !!(config.peerDependencies && config.peerDependencies.vue);
const basePlugins = [nodeResolve(), commonjs(), postcss()];
const plugins = isVue
? [
vue({ compileTemplate: true }),
typescript({ tsconfig, tsconfigOverride: { compilerOptions: { outDir: dist } }, check: false }),
...basePlugins
]
: [typescript({ tsconfig, tsconfigOverride: { compilerOptions: { outDir: dist } }, check: false }), ...basePlugins];
const rollupOptions = {
input: entry,
external: isVue ? ["vue"] : [],
plugins
};
const output = [];
for (const format of formats) {
const ext = format === "cjs" ? "cjs" : format === "esm" ? "mjs" : "js";
const outputItem = {
format,
file: path.resolve(dist, `index.${ext}`),
sourcemap: true,
exports: "named",
globals: isVue ? { vue: "Vue" } : {}
};
if (format === "iife") {
outputItem.name = name || "VenusLib";
}
output.push(outputItem);
}
rollupOptions.output = output;
rollupOptions.watch = {
include: path.resolve(root, "src/**"),
exclude: path.resolve(root, "node_modules/**"),
clearScreen: false
};
return rollupOptions;
}
export async function getRollupConfigs() {
const pkgs = discoverPackages();
const roots = getPackageRoots();
const configs = await Promise.all(roots.map(getRollupConfig));
const result = {};
for (let i = 0; i < pkgs.length; i++) {
const cfg = configs[i];
if (!cfg) {
console.warn(`跳过包: ${pkgs[i]},缺少入口文件 src/index.ts`);
continue;
}
result[pkgs[i]] = cfg;
}
return result;
}
export function clearDist(name) {
const dist = path.resolve(__dirname, `../packages`, name, `dist`);
if (fs.existsSync(dist)) {
fs.rmSync(dist, { recursive: true, force: true });
}
}
// 单独打包指定的包
import { rollup } from "rollup";
import { getRollupConfigs, clearDist } from "./buildBase.js";
import terser from "@rollup/plugin-terser";
import path from "node:path";
import URL from "node:url";
const __filename = URL.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function buildSingle(packageName) {
if (!packageName) {
console.error("请指定要构建的包名");
process.exit(1);
}
const packagePath = path.resolve(__dirname, `../packages/${packageName}`);
try {
// 检查包是否存在
const fs = await import("node:fs");
if (!fs.existsSync(packagePath)) {
console.error(`包 ${packageName} 不存在`);
process.exit(1);
}
console.log(`正在构建包: ${packageName}`);
// 清理 dist 目录
const distPath = path.resolve(packagePath, "dist");
if (fs.existsSync(distPath)) {
fs.rmSync(distPath, { recursive: true, force: true });
}
// 获取构建配置
const { getRollupConfig } = await import("./buildBase.js");
const config = await getRollupConfig(packagePath);
console.log(`正在打包: ${packageName}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成: ${packageName}`);
} catch (error) {
console.error(`构建失败: ${error.message}`);
process.exit(1);
}
}
// 从命令行参数获取包名
const packageName = process.argv[2];
buildSingle(packageName);
import { getRollupConfigs } from "./buildBase.js";
import { watch } from "rollup";
async function dev() {
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
const config = configs[name];
const watcher = watch(
config.output.map(o => ({
input: config.input,
plugins: [...config.plugins],
external: config.external,
output: o,
watch: config.watch
}))
);
watcher.on("event", event => {
if (event.code === "START") {
console.log(`开始监听: ${name}`);
} else if (event.code === "ERROR") {
console.error(`打包失败: ${name}`, event.error);
} else if (event.code === "BUNDLE_START") {
console.log(`开始打包: ${name}`);
} else if (event.code === "BUNDLE_END") {
console.log(`打包完成: ${name}`);
}
});
}
}
dev();
{
"compileroptions": {
"baseUrl": ".",
"module": "esnext",
"target": "esnext",
"types": [],
"lib": ["esnext"],
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"strict": true,
"verbatimModuleSyntax": false,
"moduleResolution": "bundler",
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true
},
"exclude": ["node_modules", "dist"]
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!