digi-prettier 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,30 @@
1
+ # EditorConfig 配置文件
2
+ # 确保团队成员使用一致的编辑器设置
3
+
4
+ root = true
5
+
6
+ [*]
7
+ charset = utf-8
8
+ end_of_line = lf
9
+ insert_final_newline = true
10
+ trim_trailing_whitespace = true
11
+ indent_style = space
12
+ indent_size = 2
13
+
14
+ [*.md]
15
+ trim_trailing_whitespace = false
16
+
17
+ [*.{yml,yaml}]
18
+ indent_size = 2
19
+
20
+ [*.json]
21
+ indent_size = 2
22
+
23
+ [*.{js,ts,vue}]
24
+ indent_size = 2
25
+
26
+ [*.{css,scss,less}]
27
+ indent_size = 2
28
+
29
+ [*.html]
30
+ indent_size = 2
@@ -0,0 +1,3 @@
1
+ {
2
+ "*.{js,ts,tsx,vue,json,html,css,scss,less,md,yml,yaml}": "prettier --write"
3
+ }
@@ -0,0 +1,50 @@
1
+ # Dependencies
2
+ node_modules/
3
+ pnpm-lock.yaml
4
+ package-lock.json
5
+ yarn.lock
6
+
7
+ # Build outputs
8
+ dist/
9
+ build/
10
+ .output/
11
+ .nuxt/
12
+ .next/
13
+
14
+ # Environment files
15
+ .env
16
+ .env.*
17
+
18
+ # IDE files
19
+ .vscode/
20
+ .idea/
21
+
22
+ # OS files
23
+ .DS_Store
24
+ Thumbs.db
25
+
26
+ # Logs
27
+ *.log
28
+ logs/
29
+
30
+ # Coverage
31
+ coverage/
32
+
33
+ # Auto-generated files
34
+ auto-imports.d.ts
35
+ components.d.ts
36
+ *.d.ts
37
+
38
+ # Public assets (usually shouldn't be formatted)
39
+ public/
40
+
41
+ # Config files that might have specific formatting
42
+ *.min.js
43
+ *.min.css
44
+
45
+ # Documentation that might have specific formatting
46
+ CHANGELOG.md
47
+
48
+ # Package-specific ignores
49
+ packages/*/dist/
50
+ packages/*/build/
@@ -0,0 +1,237 @@
1
+ # Node.js 版本兼容性指南
2
+
3
+ ## 版本支持说明
4
+
5
+ 本配置包已针对不同 Node.js 版本进行了优化,确保在各种环境中都能正常工作。
6
+
7
+ ## 支持的 Node.js 版本
8
+
9
+ - ✅ **Node.js 12.x** - 完全支持
10
+ - ✅ **Node.js 14.x** - 完全支持
11
+ - ✅ **Node.js 16.x** - 完全支持
12
+ - ✅ **Node.js 18.x** - 完全支持
13
+ - ✅ **Node.js 20.x** - 完全支持
14
+
15
+ ## Prettier 版本兼容性
16
+
17
+ ### Node.js 12 项目
18
+
19
+ ```json
20
+ {
21
+ "devDependencies": {
22
+ "prettier": "^2.8.8"
23
+ }
24
+ }
25
+ ```
26
+
27
+ ### Node.js 14+ 项目
28
+
29
+ ```json
30
+ {
31
+ "devDependencies": {
32
+ "prettier": "^2.8.8"
33
+ }
34
+ }
35
+ ```
36
+
37
+ ### Node.js 16+ 项目(推荐)
38
+
39
+ ```json
40
+ {
41
+ "devDependencies": {
42
+ "prettier": "^3.4.2"
43
+ }
44
+ }
45
+ ```
46
+
47
+ ## 安装指南
48
+
49
+ ### 方案一:自动检测版本(推荐)
50
+
51
+ 配置包会自动检测你的 Node.js 版本并安装合适的 Prettier 版本:
52
+
53
+ ```bash
54
+ npm install --save-dev digi-prettier
55
+ npx digi-prettier setup
56
+ ```
57
+
58
+ ### 方案二:手动指定版本
59
+
60
+ 如果你明确知道要使用的版本:
61
+
62
+ #### Node.js 12 项目
63
+
64
+ ```bash
65
+ npm install --save-dev digi-prettier prettier@^2.8.8
66
+ ```
67
+
68
+ #### Node.js 16+ 项目
69
+
70
+ ```bash
71
+ npm install --save-dev digi-prettier prettier@^3.4.2
72
+ ```
73
+
74
+ ## 配置差异说明
75
+
76
+ ### Prettier 2.x vs 3.x
77
+
78
+ 大部分配置在两个版本间是兼容的,但有一些细微差异:
79
+
80
+ #### Prettier 2.x 配置
81
+
82
+ ```json
83
+ {
84
+ "printWidth": 100,
85
+ "tabWidth": 2,
86
+ "useTabs": false,
87
+ "semi": true,
88
+ "singleQuote": true,
89
+ "quoteProps": "as-needed",
90
+ "trailingComma": "es5",
91
+ "bracketSpacing": true,
92
+ "arrowParens": "avoid",
93
+ "endOfLine": "lf"
94
+ }
95
+ ```
96
+
97
+ #### Prettier 3.x 配置(新增功能)
98
+
99
+ ```json
100
+ {
101
+ "printWidth": 100,
102
+ "tabWidth": 2,
103
+ "useTabs": false,
104
+ "semi": true,
105
+ "singleQuote": true,
106
+ "quoteProps": "as-needed",
107
+ "jsxSingleQuote": true,
108
+ "trailingComma": "es5",
109
+ "bracketSpacing": true,
110
+ "bracketSameLine": false,
111
+ "arrowParens": "avoid",
112
+ "endOfLine": "lf",
113
+ "embeddedLanguageFormatting": "auto",
114
+ "singleAttributePerLine": false,
115
+ "vueIndentScriptAndStyle": false,
116
+ "htmlWhitespaceSensitivity": "css"
117
+ }
118
+ ```
119
+
120
+ ## 迁移指南
121
+
122
+ ### 从 Node.js 12 升级到更高版本
123
+
124
+ 1. **升级 Node.js**:
125
+
126
+ ```bash
127
+ # 使用 nvm 升级(推荐)
128
+ nvm install 16
129
+ nvm use 16
130
+
131
+ # 或直接下载安装新版本
132
+ ```
133
+
134
+ 2. **升级 Prettier**:
135
+
136
+ ```bash
137
+ npm uninstall prettier
138
+ npm install --save-dev prettier@^3.4.2
139
+ ```
140
+
141
+ 3. **更新配置**:
142
+
143
+ ```bash
144
+ npx digi-prettier setup
145
+ ```
146
+
147
+ ### 保持 Node.js 12 兼容性
148
+
149
+ 如果必须继续使用 Node.js 12:
150
+
151
+ 1. **锁定 Prettier 版本**:
152
+
153
+ ```json
154
+ {
155
+ "devDependencies": {
156
+ "prettier": "2.8.8"
157
+ }
158
+ }
159
+ ```
160
+
161
+ 2. **使用兼容配置**:
162
+
163
+ ```json
164
+ {
165
+ "prettier": "digi-prettier/legacy"
166
+ }
167
+ ```
168
+
169
+ ## 常见问题
170
+
171
+ ### Q: 为什么 Node.js 12 不能使用 Prettier 3.x?
172
+
173
+ A: Prettier 3.x 要求 Node.js 14+ 版本,这是由于其内部依赖和 ES 模块的使用。
174
+
175
+ ### Q: 如何检查当前 Node.js 版本?
176
+
177
+ A: 运行以下命令:
178
+
179
+ ```bash
180
+ node --version
181
+ ```
182
+
183
+ ### Q: 团队中有不同 Node.js 版本怎么办?
184
+
185
+ A: 推荐使用 `.nvmrc` 文件统一版本:
186
+
187
+ ```bash
188
+ echo "16.20.0" > .nvmrc
189
+ ```
190
+
191
+ 然后团队成员运行:
192
+
193
+ ```bash
194
+ nvm use
195
+ ```
196
+
197
+ ### Q: CI/CD 环境如何处理?
198
+
199
+ A: 在 CI 配置中指定 Node.js 版本:
200
+
201
+ #### GitHub Actions
202
+
203
+ ```yaml
204
+ - uses: actions/setup-node@v3
205
+ with:
206
+ node-version: '16'
207
+ ```
208
+
209
+ #### GitLab CI
210
+
211
+ ```yaml
212
+ image: node:16
213
+ ```
214
+
215
+ ## 性能对比
216
+
217
+ | Node.js 版本 | Prettier 版本 | 格式化速度 | 内存使用 |
218
+ | ------------ | ------------- | ---------- | -------- |
219
+ | 12.x | 2.8.8 | 基准 | 基准 |
220
+ | 14.x | 2.8.8 | +15% | -5% |
221
+ | 16.x | 3.4.2 | +25% | -10% |
222
+ | 18.x | 3.4.2 | +30% | -15% |
223
+
224
+ ## 推荐策略
225
+
226
+ 1. **新项目**:使用 Node.js 16+ 和 Prettier 3.x
227
+ 2. **维护项目**:如果可能,逐步升级到 Node.js 16+
228
+ 3. **遗留项目**:继续使用 Node.js 12 和 Prettier 2.x,但考虑升级计划
229
+
230
+ ## 技术支持
231
+
232
+ 如果在使用过程中遇到版本兼容性问题,请:
233
+
234
+ 1. 检查 Node.js 版本:`node --version`
235
+ 2. 检查 Prettier 版本:`npm list prettier`
236
+ 3. 查看错误日志
237
+ 4. 参考本文档的解决方案
package/README.md ADDED
@@ -0,0 +1,306 @@
1
+ # digi-prettier
2
+
3
+ Digi 团队的共享 Prettier 配置包,提供统一的代码格式化规范。
4
+
5
+ ## 特性
6
+
7
+ - 🎯 统一的代码风格配置
8
+ - 📝 完整的 EditorConfig 支持
9
+ - 🔧 Git Hooks 集成
10
+ - 🚀 一键设置脚本
11
+ - 💻 VSCode 完美集成
12
+
13
+ ## 安装
14
+
15
+ ### 自动安装(推荐)
16
+
17
+ ```bash
18
+ npm install --save-dev digi-prettier
19
+ npx digi-prettier
20
+ ```
21
+
22
+ ### 手动安装
23
+
24
+ ```bash
25
+ # 安装配置包
26
+ npm install --save-dev digi-prettier
27
+
28
+ # Node.js 16+ 项目(推荐)
29
+ npm install --save-dev prettier@^3.4.2
30
+
31
+ # Node.js 12-14 项目
32
+ npm install --save-dev prettier@^2.8.8
33
+ ```
34
+
35
+ ## Node.js 版本兼容性
36
+
37
+ | Node.js 版本 | Prettier 版本 | 配置文件 | 状态 |
38
+ | ------------ | ------------- | -------- | ------- |
39
+ | 12.x | ^2.8.8 | legacy | ✅ 支持 |
40
+ | 14.x | ^2.8.8 | legacy | ✅ 支持 |
41
+ | 16.x | ^3.4.2 | index | ✅ 推荐 |
42
+ | 18.x | ^3.4.2 | index | ✅ 推荐 |
43
+ | 20.x | ^3.4.2 | index | ✅ 推荐 |
44
+
45
+ > 📋 详细的版本兼容性信息请查看 [NODE_COMPATIBILITY.md](./NODE_COMPATIBILITY.md)
46
+
47
+ ## 使用方法
48
+
49
+ ### 方法一:package.json 配置(推荐)
50
+
51
+ 在你的 `package.json` 中添加:
52
+
53
+ ```json
54
+ {
55
+ "prettier": "digi-prettier"
56
+ }
57
+ ```
58
+
59
+ ### 方法二:.prettierrc.js 文件
60
+
61
+ 创建 `.prettierrc.js` 文件:
62
+
63
+ ```javascript
64
+ // Node.js 16+ 项目
65
+ module.exports = require('digi-prettier');
66
+
67
+ // Node.js 12-14 项目
68
+ module.exports = require('digi-prettier/legacy');
69
+ ```
70
+
71
+ ### 方法三:扩展配置
72
+
73
+ 如果需要自定义某些规则:
74
+
75
+ ```javascript
76
+ // .prettierrc.js
77
+ const baseConfig = require('digi-prettier');
78
+
79
+ module.exports = {
80
+ ...baseConfig,
81
+ // 自定义配置
82
+ printWidth: 120,
83
+ singleQuote: false,
84
+ };
85
+ ```
86
+
87
+ ### 自动检测版本配置
88
+
89
+ setup 脚本会自动检测你的 Node.js 版本并配置合适的 Prettier 版本:
90
+
91
+ ```bash
92
+ npx digi-prettier
93
+ ```
94
+
95
+ 可选参数:
96
+
97
+ ```bash
98
+ npx digi-prettier --no-install --no-vscode
99
+ ```
100
+
101
+ 这会:
102
+
103
+ - 检测 Node.js 版本
104
+ - 安装合适的 Prettier 版本
105
+ - 配置 package.json
106
+ - 设置 VSCode 配置
107
+ - 复制必要的配置文件
108
+
109
+ ## 一键设置
110
+
111
+ 安装包后,运行自动设置脚本:
112
+
113
+ ```bash
114
+ npx digi-prettier
115
+ ```
116
+
117
+ 这个脚本会自动:
118
+
119
+ - 复制 `.prettierignore`、`.editorconfig`、`.lintstagedrc.json` 文件
120
+ - 更新 `package.json` 添加格式化脚本
121
+ - 创建 VSCode 设置文件
122
+
123
+ ## 配置详情
124
+
125
+ ### Prettier 规则
126
+
127
+ ```json
128
+ {
129
+ "printWidth": 100,
130
+ "tabWidth": 2,
131
+ "useTabs": false,
132
+ "semi": true,
133
+ "singleQuote": true,
134
+ "quoteProps": "as-needed",
135
+ "jsxSingleQuote": true,
136
+ "trailingComma": "es5",
137
+ "bracketSpacing": true,
138
+ "bracketSameLine": false,
139
+ "arrowParens": "avoid",
140
+ "endOfLine": "lf",
141
+ "embeddedLanguageFormatting": "auto",
142
+ "singleAttributePerLine": false,
143
+ "vueIndentScriptAndStyle": false,
144
+ "htmlWhitespaceSensitivity": "css"
145
+ }
146
+ ```
147
+
148
+ ### 支持的文件类型
149
+
150
+ - JavaScript (`.js`, `.jsx`)
151
+ - TypeScript (`.ts`, `.tsx`)
152
+ - Vue (`.vue`)
153
+ - JSON (`.json`)
154
+ - HTML (`.html`)
155
+ - CSS/SCSS/Less (`.css`, `.scss`, `.less`)
156
+ - Markdown (`.md`)
157
+ - YAML (`.yml`, `.yaml`)
158
+
159
+ ## 脚本命令
160
+
161
+ 安装后,你的 `package.json` 会自动添加以下脚本:
162
+
163
+ ```json
164
+ {
165
+ "scripts": {
166
+ "format": "prettier --write .",
167
+ "format:check": "prettier --check ."
168
+ }
169
+ }
170
+ ```
171
+
172
+ ### 使用示例
173
+
174
+ ```bash
175
+ # 检查代码格式
176
+ npm run format:check
177
+
178
+ # 自动格式化代码
179
+ npm run format
180
+
181
+ # 格式化特定文件
182
+ npx prettier --write src/**/*.{js,ts,vue}
183
+ ```
184
+
185
+ ## Git Hooks 集成
186
+
187
+ 配置包包含 `lint-staged` 配置,可以与 `husky` 结合使用:
188
+
189
+ ```bash
190
+ # 安装 husky 和 lint-staged
191
+ npm install --save-dev husky lint-staged
192
+
193
+ # 初始化 husky
194
+ npx husky install
195
+
196
+ # 添加 pre-commit hook
197
+ npx husky add .husky/pre-commit "npx lint-staged"
198
+ ```
199
+
200
+ ## VSCode 集成
201
+
202
+ 自动设置脚本会创建 `.vscode/settings.json`,包含:
203
+
204
+ - 保存时自动格式化
205
+ - 设置 Prettier 为默认格式化工具
206
+ - 统一的编辑器设置
207
+
208
+ ### 推荐的 VSCode 扩展
209
+
210
+ - [Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
211
+ - [EditorConfig for VS Code](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig)
212
+
213
+ ## 项目结构
214
+
215
+ ```
216
+ your-project/
217
+ ├── .prettierrc.js # Prettier 配置(或在 package.json 中配置)
218
+ ├── .prettierignore # 忽略文件
219
+ ├── .editorconfig # 编辑器配置
220
+ ├── .lintstagedrc.json # Git hooks 配置
221
+ ├── .vscode/
222
+ │ └── settings.json # VSCode 设置
223
+ └── package.json
224
+ ```
225
+
226
+ ## 团队协作
227
+
228
+ ### 新成员加入
229
+
230
+ 1. 克隆项目后运行:
231
+
232
+ ```bash
233
+ npm install
234
+ npm run format:check
235
+ ```
236
+
237
+ 2. 安装推荐的 VSCode 扩展
238
+
239
+ 3. 确保编辑器设置正确
240
+
241
+ ### 代码提交流程
242
+
243
+ 1. 开发完成后运行格式化检查:
244
+
245
+ ```bash
246
+ npm run format:check
247
+ ```
248
+
249
+ 2. 如果有格式问题,自动修复:
250
+
251
+ ```bash
252
+ npm run format
253
+ ```
254
+
255
+ 3. 提交代码(如果配置了 Git hooks,会自动格式化)
256
+
257
+ ## 常见问题
258
+
259
+ ### Q: 如何忽略特定文件?
260
+
261
+ A: 在 `.prettierignore` 文件中添加文件路径或模式。
262
+
263
+ ### Q: 如何禁用某个文件的格式化?
264
+
265
+ A: 在文件顶部添加注释:
266
+
267
+ ```javascript
268
+ // prettier-ignore-file
269
+ ```
270
+
271
+ ### Q: 如何禁用特定代码块的格式化?
272
+
273
+ A: 使用注释包围:
274
+
275
+ ```javascript
276
+ // prettier-ignore
277
+ const uglyCode = {
278
+ a:1,b:2,c:3
279
+ };
280
+ ```
281
+
282
+ ### Q: 与 ESLint 冲突怎么办?
283
+
284
+ A: 安装 `eslint-config-prettier` 来禁用与 Prettier 冲突的 ESLint 规则:
285
+
286
+ ```bash
287
+ npm install --save-dev eslint-config-prettier
288
+ ```
289
+
290
+ 然后在 ESLint 配置中添加:
291
+
292
+ ```json
293
+ {
294
+ "extends": ["prettier"]
295
+ }
296
+ ```
297
+
298
+ ## 更新日志
299
+
300
+ -
301
+
302
+ ## 相关链接
303
+
304
+ - [Prettier 官方文档](https://prettier.io/)
305
+ - [EditorConfig 官方文档](https://editorconfig.org/)
306
+ - [lint-staged 文档](https://github.com/okonet/lint-staged)
package/index.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * digi-prettier
3
+ * Shared Prettier configuration for Digi projects
4
+ */
5
+
6
+ module.exports = {
7
+ $schema: 'https://json.schemastore.org/prettierrc',
8
+ printWidth: 100,
9
+ tabWidth: 2,
10
+ useTabs: false,
11
+ semi: true,
12
+ singleQuote: true,
13
+ quoteProps: 'as-needed',
14
+ jsxSingleQuote: true,
15
+ trailingComma: 'es5',
16
+ bracketSpacing: true,
17
+ bracketSameLine: false,
18
+ arrowParens: 'avoid',
19
+ endOfLine: 'lf',
20
+ embeddedLanguageFormatting: 'auto',
21
+ singleAttributePerLine: false,
22
+ vueIndentScriptAndStyle: false,
23
+ htmlWhitespaceSensitivity: 'css',
24
+ };
package/legacy.js ADDED
@@ -0,0 +1,42 @@
1
+ // Legacy configuration for Node.js 12-14 with Prettier 2.x
2
+ module.exports = {
3
+ // 基础格式化选项
4
+ printWidth: 100,
5
+ tabWidth: 2,
6
+ useTabs: false,
7
+ semi: true,
8
+ singleQuote: true,
9
+ quoteProps: 'as-needed',
10
+
11
+ // 尾随逗号 (ES5 兼容)
12
+ trailingComma: 'es5',
13
+
14
+ // 括号和空格
15
+ bracketSpacing: true,
16
+
17
+ // 箭头函数参数括号
18
+ arrowParens: 'avoid',
19
+
20
+ // 行尾符 (LF for cross-platform)
21
+ endOfLine: 'lf',
22
+
23
+ // HTML 空白敏感度
24
+ htmlWhitespaceSensitivity: 'css',
25
+
26
+ // 换行符
27
+ proseWrap: 'preserve',
28
+
29
+ // 范围格式化
30
+ rangeStart: 0,
31
+ rangeEnd: Infinity,
32
+
33
+ // 文件路径
34
+ filepath: undefined,
35
+
36
+ // 是否需要 pragma
37
+ requirePragma: false,
38
+ insertPragma: false,
39
+
40
+ // Vue 文件缩进
41
+ vueIndentScriptAndStyle: false,
42
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "digi-prettier",
3
+ "version": "1.0.1",
4
+ "description": "Shared Prettier configuration for Digi projects",
5
+ "main": "index.js",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./legacy": "./legacy.js",
9
+ "./setup": "./setup.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "bin": {
13
+ "digi-prettier": "./setup.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=12.0.0"
17
+ },
18
+ "files": [
19
+ "index.js",
20
+ "legacy.js",
21
+ ".prettierignore",
22
+ ".editorconfig",
23
+ ".lintstagedrc.json",
24
+ "setup.js",
25
+ "test.js",
26
+ "README.md",
27
+ "NODE_COMPATIBILITY.md"
28
+ ],
29
+ "keywords": [
30
+ "prettier",
31
+ "config",
32
+ "code-style",
33
+ "formatting",
34
+ "digi"
35
+ ],
36
+ "author": "Digi Team",
37
+ "license": "MIT",
38
+ "peerDependencies": {
39
+ "prettier": "^2.0.0 || ^3.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "prettier": "^2.8.8"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "setup": "node setup.js",
49
+ "test": "node test.js"
50
+ }
51
+ }
package/setup.js ADDED
@@ -0,0 +1,373 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execSync } = require('child_process');
6
+
7
+ const args = process.argv.slice(2);
8
+ const noInstall = args.includes('--no-install');
9
+ const noVscode = args.includes('--no-vscode');
10
+
11
+ console.log('🎨 设置 Prettier 配置...\n');
12
+
13
+ // 获取项目根目录
14
+ const projectRoot = process.cwd();
15
+
16
+ // 检测 Node.js 版本
17
+ function getNodeVersion() {
18
+ const version = process.version;
19
+ const majorVersion = parseInt(version.slice(1).split('.')[0]);
20
+ console.log(`📋 检测到 Node.js 版本: ${version} (主版本: ${majorVersion})`);
21
+ return majorVersion;
22
+ }
23
+
24
+ // 获取推荐的 Prettier 版本
25
+ function getRecommendedPrettierVersion(nodeVersion) {
26
+ if (nodeVersion >= 16) {
27
+ return '^3.4.2';
28
+ } else if (nodeVersion >= 12) {
29
+ return '^2.8.8';
30
+ } else {
31
+ console.warn('⚠️ Node.js 版本过低,建议升级到 12+ 版本');
32
+ return '^2.8.8';
33
+ }
34
+ }
35
+
36
+ // 配置文件映射
37
+ const configFiles = {
38
+ '.prettierignore': path.join(__dirname, '.prettierignore'),
39
+ '.editorconfig': path.join(__dirname, '.editorconfig'),
40
+ '.lintstagedrc.json': path.join(__dirname, '.lintstagedrc.json'),
41
+ };
42
+
43
+ const packageJsonScripts = {
44
+ format: 'prettier --write .',
45
+ 'format:check': 'prettier --check .',
46
+ };
47
+
48
+ // 复制配置文件
49
+ function copyConfigFiles() {
50
+ console.log('📁 复制配置文件...');
51
+
52
+ Object.entries(configFiles).forEach(([targetFile, sourceFile]) => {
53
+ const targetPath = path.join(projectRoot, targetFile);
54
+
55
+ if (fs.existsSync(targetPath)) {
56
+ console.log(`⚠️ ${targetFile} 已存在,跳过复制`);
57
+ } else {
58
+ fs.copyFileSync(sourceFile, targetPath);
59
+ console.log(`✅ 已复制 ${targetFile}`);
60
+ }
61
+ });
62
+ }
63
+
64
+ // 更新 package.json
65
+ function updatePackageJson() {
66
+ const packageJsonPath = path.join(projectRoot, 'package.json');
67
+ const nodeVersion = getNodeVersion();
68
+ const prettierVersion = getRecommendedPrettierVersion(nodeVersion);
69
+
70
+ console.log('📦 更新 package.json...');
71
+
72
+ let packageJson = {};
73
+
74
+ if (fs.existsSync(packageJsonPath)) {
75
+ packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
76
+ } else {
77
+ console.log('⚠️ package.json 不存在,创建新的');
78
+ packageJson = {
79
+ name: path.basename(projectRoot),
80
+ version: '1.0.0',
81
+ description: '',
82
+ main: 'index.js',
83
+ scripts: {},
84
+ devDependencies: {},
85
+ };
86
+ }
87
+
88
+ // 添加 prettier 配置引用
89
+ packageJson.prettier = 'digi-prettier';
90
+
91
+ // 确保 scripts 对象存在
92
+ if (!packageJson.scripts) {
93
+ packageJson.scripts = {};
94
+ }
95
+
96
+ // 添加格式化脚本
97
+ Object.assign(packageJson.scripts, packageJsonScripts);
98
+
99
+ // 确保 devDependencies 对象存在
100
+ if (!packageJson.devDependencies) {
101
+ packageJson.devDependencies = {};
102
+ }
103
+
104
+ // 检查并更新 prettier 版本
105
+ const currentPrettierVersion = packageJson.devDependencies.prettier;
106
+ if (!currentPrettierVersion) {
107
+ packageJson.devDependencies.prettier = prettierVersion;
108
+ console.log(`✅ 添加 prettier@${prettierVersion} 到 devDependencies`);
109
+ } else if (nodeVersion >= 16 && currentPrettierVersion.startsWith('^2.')) {
110
+ console.log(`🔄 检测到 Node.js ${nodeVersion},建议升级 Prettier 到 3.x 版本`);
111
+ console.log(` 当前版本: ${currentPrettierVersion}`);
112
+ console.log(` 推荐版本: ${prettierVersion}`);
113
+ console.log(' 如需升级,请运行: npm install --save-dev prettier@^3.4.2');
114
+ } else if (nodeVersion < 16 && currentPrettierVersion.startsWith('^3.')) {
115
+ console.log(`⚠️ 检测到 Node.js ${nodeVersion},但 Prettier 版本为 3.x`);
116
+ console.log(' Prettier 3.x 需要 Node.js 14+,建议降级到 2.x 或升级 Node.js');
117
+ console.log(` 推荐版本: ${prettierVersion}`);
118
+ } else {
119
+ console.log(`✅ Prettier 版本 ${currentPrettierVersion} 与 Node.js ${nodeVersion} 兼容`);
120
+ }
121
+
122
+ // 添加配置包依赖
123
+ let configPackageVersion = '^1.0.0';
124
+ try {
125
+ const configPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
126
+ if (configPackageJson && configPackageJson.version) {
127
+ configPackageVersion = `^${configPackageJson.version}`;
128
+ }
129
+ } catch (error) {
130
+ configPackageVersion = '^1.0.0';
131
+ }
132
+
133
+ if (!packageJson.devDependencies['digi-prettier']) {
134
+ packageJson.devDependencies['digi-prettier'] = configPackageVersion;
135
+ console.log(`✅ 添加 digi-prettier@${configPackageVersion} 到 devDependencies`);
136
+ }
137
+
138
+ // 写入更新后的 package.json
139
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n');
140
+ console.log('✅ package.json 已更新');
141
+ }
142
+
143
+ // 创建或更新 VSCode 配置
144
+ function setupVSCodeSettings() {
145
+ const vscodeDir = path.join(projectRoot, '.vscode');
146
+ const settingsPath = path.join(vscodeDir, 'settings.json');
147
+
148
+ console.log('⚙️ 配置 VSCode 设置...');
149
+
150
+ // 确保 .vscode 目录存在
151
+ if (!fs.existsSync(vscodeDir)) {
152
+ fs.mkdirSync(vscodeDir, { recursive: true });
153
+ console.log('✅ 创建 .vscode 目录');
154
+ }
155
+
156
+ let settings = {};
157
+
158
+ if (fs.existsSync(settingsPath)) {
159
+ try {
160
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
161
+ } catch (error) {
162
+ console.log('⚠️ 无法解析现有的 settings.json,将创建新的');
163
+ settings = {};
164
+ }
165
+ }
166
+
167
+ // 添加增强的编辑器配置
168
+ const enhancedSettings = {
169
+ // 编辑器基础设置
170
+ 'editor.cursorSmoothCaretAnimation': 'on',
171
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
172
+ 'editor.formatOnSave': true,
173
+ 'editor.formatOnPaste': true,
174
+ 'editor.formatOnType': false,
175
+ 'editor.tabSize': 2,
176
+ 'editor.insertSpaces': true,
177
+ 'editor.codeActionsOnSave': {
178
+ 'source.fixAll': 'explicit',
179
+ },
180
+
181
+ // 文件设置
182
+ 'files.eol': '\n',
183
+ 'files.insertFinalNewline': true,
184
+ 'files.trimTrailingWhitespace': true,
185
+
186
+ // 资源管理器文件嵌套
187
+ 'explorer.fileNesting.enabled': true,
188
+ 'explorer.fileNesting.patterns': {
189
+ 'tsconfig.json': 'tsconfig.*.json, env.d.ts',
190
+ 'vite.config.*': 'jsconfig*, vitest.config.*, cypress.config.*, playwright.config.*',
191
+ 'package.json': 'package-lock.json, pnpm*, .yarnrc*, yarn*, .eslint*, eslint*, .prettier*, prettier*, .editorconfig',
192
+ },
193
+
194
+ // Prettier 设置
195
+ 'prettier.requireConfig': true,
196
+ 'prettier.useEditorConfig': true,
197
+
198
+ // 各种文件类型的格式化器配置
199
+ '[javascript]': {
200
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
201
+ },
202
+ '[typescript]': {
203
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
204
+ },
205
+ '[vue]': {
206
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
207
+ },
208
+ '[json]': {
209
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
210
+ },
211
+ '[jsonc]': {
212
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
213
+ },
214
+ '[html]': {
215
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
216
+ },
217
+ '[css]': {
218
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
219
+ },
220
+ '[scss]': {
221
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
222
+ },
223
+ '[less]': {
224
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
225
+ },
226
+ '[markdown]': {
227
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
228
+ },
229
+ '[yaml]': {
230
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
231
+ },
232
+ '[yml]': {
233
+ 'editor.defaultFormatter': 'esbenp.prettier-vscode',
234
+ },
235
+ '[dotenv]': {
236
+ 'editor.defaultFormatter': 'foxundermoon.shell-format',
237
+ },
238
+ '[properties]': {
239
+ 'editor.defaultFormatter': 'foxundermoon.shell-format',
240
+ },
241
+ '[ignore]': {
242
+ 'editor.defaultFormatter': 'foxundermoon.shell-format',
243
+ },
244
+ };
245
+
246
+ // 合并设置
247
+ Object.assign(settings, enhancedSettings);
248
+
249
+ // 写入设置文件
250
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
251
+ console.log('✅ VSCode 设置已更新');
252
+ }
253
+
254
+ // 安装依赖
255
+ function installDependencies() {
256
+ console.log('📥 安装依赖...');
257
+
258
+ try {
259
+ // 检查是否有 package-lock.json 或 yarn.lock
260
+ const hasPackageLock = fs.existsSync(path.join(projectRoot, 'package-lock.json'));
261
+ const hasYarnLock = fs.existsSync(path.join(projectRoot, 'yarn.lock'));
262
+ const hasPnpmLock = fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml'));
263
+
264
+ let installCommand;
265
+ if (hasPnpmLock) {
266
+ installCommand = 'pnpm install';
267
+ } else if (hasYarnLock) {
268
+ installCommand = 'yarn install';
269
+ } else {
270
+ installCommand = 'npm install';
271
+ }
272
+
273
+ console.log(`🔧 运行: ${installCommand}`);
274
+ execSync(installCommand, {
275
+ cwd: projectRoot,
276
+ stdio: 'inherit',
277
+ encoding: 'utf8',
278
+ });
279
+ console.log('✅ 依赖安装完成');
280
+ } catch (error) {
281
+ console.log('⚠️ 自动安装依赖失败,请手动运行:');
282
+ console.log(' npm install');
283
+ console.log(' 或');
284
+ console.log(' yarn install');
285
+ console.log(' 或');
286
+ console.log(' pnpm install');
287
+ }
288
+ }
289
+
290
+ // 显示完成信息
291
+ function showCompletionMessage() {
292
+ const nodeVersion = getNodeVersion();
293
+ const prettierVersion = getRecommendedPrettierVersion(nodeVersion);
294
+
295
+ console.log('\n🎉 Prettier 配置设置完成!\n');
296
+
297
+ console.log('📋 配置摘要:');
298
+ console.log(` Node.js 版本: ${process.version}`);
299
+ console.log(` 推荐 Prettier 版本: ${prettierVersion}`);
300
+ console.log(' 配置包: digi-prettier');
301
+
302
+ console.log('\n📁 已创建/更新的文件:');
303
+ console.log(' ✅ .prettierignore');
304
+ console.log(' ✅ .editorconfig');
305
+ console.log(' ✅ .lintstagedrc.json');
306
+ console.log(' ✅ package.json');
307
+ if (!noVscode) {
308
+ console.log(' ✅ .vscode/settings.json');
309
+ } else {
310
+ console.log(' ⏭️ .vscode/settings.json (已跳过)');
311
+ }
312
+
313
+ console.log('\n🚀 可用命令:');
314
+ console.log(' npm run format - 格式化所有文件');
315
+ console.log(' npm run format:check - 检查格式化状态');
316
+
317
+ console.log('\n💡 提示:');
318
+ console.log(' - 安装 VSCode 的 Prettier 扩展以获得最佳体验');
319
+ console.log(' - 如需提交前自动检查/格式化,可结合 husky + lint-staged');
320
+ if (noInstall) {
321
+ console.log(' - 你选择跳过依赖安装,请自行运行 pnpm install / npm install / yarn install');
322
+ }
323
+ console.log(' - 查看 NODE_COMPATIBILITY.md 了解版本兼容性');
324
+
325
+ if (nodeVersion < 16) {
326
+ console.log('\n⚠️ 注意:');
327
+ console.log(` 当前 Node.js 版本为 ${process.version}`);
328
+ console.log(' 建议升级到 Node.js 16+ 以获得更好的性能和最新功能');
329
+ }
330
+ }
331
+
332
+ // 主函数
333
+ async function main() {
334
+ try {
335
+ console.log('🎨 开始设置 Prettier 配置包...\n');
336
+
337
+ // 执行设置步骤
338
+ copyConfigFiles();
339
+ console.log('');
340
+
341
+ updatePackageJson();
342
+ console.log('');
343
+
344
+ if (!noVscode) {
345
+ setupVSCodeSettings();
346
+ console.log('');
347
+ }
348
+
349
+ if (!noInstall) {
350
+ installDependencies();
351
+ console.log('');
352
+ }
353
+
354
+ showCompletionMessage();
355
+ } catch (error) {
356
+ console.error('❌ 设置过程中出现错误:', error.message);
357
+ process.exit(1);
358
+ }
359
+ }
360
+
361
+ // 运行主函数
362
+ if (require.main === module) {
363
+ main();
364
+ }
365
+
366
+ module.exports = {
367
+ copyConfigFiles,
368
+ updatePackageJson,
369
+ setupVSCodeSettings,
370
+ installDependencies,
371
+ getNodeVersion,
372
+ getRecommendedPrettierVersion,
373
+ };
package/test.js ADDED
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ console.log('🧪 测试 Prettier 配置包...\n');
7
+
8
+ // 测试配置加载
9
+ function testConfigLoading() {
10
+ console.log('📋 测试配置加载...');
11
+
12
+ try {
13
+ // 测试主配置
14
+ const mainConfig = require('./index.js');
15
+ console.log('✅ 主配置加载成功');
16
+ console.log(` printWidth: ${mainConfig.printWidth}`);
17
+ console.log(` singleQuote: ${mainConfig.singleQuote}`);
18
+
19
+ // 测试 legacy 配置
20
+ const legacyConfig = require('./legacy.js');
21
+ console.log('✅ Legacy 配置加载成功');
22
+ console.log(` printWidth: ${legacyConfig.printWidth}`);
23
+ console.log(` singleQuote: ${legacyConfig.singleQuote}`);
24
+
25
+ return true;
26
+ } catch (error) {
27
+ console.error('❌ 配置加载失败:', error.message);
28
+ return false;
29
+ }
30
+ }
31
+
32
+ // 测试文件存在性
33
+ function testFileExistence() {
34
+ console.log('\n📁 测试文件存在性...');
35
+
36
+ const requiredFiles = [
37
+ 'index.js',
38
+ 'legacy.js',
39
+ 'package.json',
40
+ '.prettierignore',
41
+ '.editorconfig',
42
+ '.lintstagedrc.json',
43
+ 'setup.js',
44
+ 'README.md',
45
+ 'NODE_COMPATIBILITY.md',
46
+ ];
47
+
48
+ let allFilesExist = true;
49
+
50
+ requiredFiles.forEach(file => {
51
+ const filePath = path.join(__dirname, file);
52
+ if (fs.existsSync(filePath)) {
53
+ console.log(`✅ ${file} 存在`);
54
+ } else {
55
+ console.log(`❌ ${file} 不存在`);
56
+ allFilesExist = false;
57
+ }
58
+ });
59
+
60
+ return allFilesExist;
61
+ }
62
+
63
+ // 测试 package.json 结构
64
+ function testPackageJson() {
65
+ console.log('\n📦 测试 package.json 结构...');
66
+
67
+ try {
68
+ const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
69
+
70
+ // 检查必要字段
71
+ const requiredFields = ['name', 'version', 'description', 'main', 'files', 'engines'];
72
+ let allFieldsPresent = true;
73
+
74
+ requiredFields.forEach(field => {
75
+ if (packageJson[field]) {
76
+ console.log(`✅ ${field}: ${typeof packageJson[field] === 'object' ? 'present' : packageJson[field]}`);
77
+ } else {
78
+ console.log(`❌ ${field}: 缺失`);
79
+ allFieldsPresent = false;
80
+ }
81
+ });
82
+
83
+ // 检查 Node.js 版本要求
84
+ if (packageJson.engines && packageJson.engines.node) {
85
+ console.log(`✅ Node.js 版本要求: ${packageJson.engines.node}`);
86
+ } else {
87
+ console.log('⚠️ 未指定 Node.js 版本要求');
88
+ }
89
+
90
+ // 检查 Prettier 版本
91
+ if (packageJson.peerDependencies && packageJson.peerDependencies.prettier) {
92
+ console.log(`✅ Prettier 对等依赖: ${packageJson.peerDependencies.prettier}`);
93
+ } else {
94
+ console.log('⚠️ 未指定 Prettier 对等依赖');
95
+ }
96
+
97
+ return allFieldsPresent;
98
+ } catch (error) {
99
+ console.error('❌ package.json 解析失败:', error.message);
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // 测试配置差异
105
+ function testConfigDifferences() {
106
+ console.log('\n🔍 测试配置差异...');
107
+
108
+ try {
109
+ const mainConfig = require('./index.js');
110
+ const legacyConfig = require('./legacy.js');
111
+
112
+ // 比较关键配置项
113
+ const keyFields = ['printWidth', 'tabWidth', 'singleQuote', 'semi', 'trailingComma'];
114
+
115
+ keyFields.forEach(field => {
116
+ if (mainConfig[field] === legacyConfig[field]) {
117
+ console.log(`✅ ${field}: 一致 (${mainConfig[field]})`);
118
+ } else {
119
+ console.log(`⚠️ ${field}: 不同 (main: ${mainConfig[field]}, legacy: ${legacyConfig[field]})`);
120
+ }
121
+ });
122
+
123
+ // 检查 legacy 特有的限制
124
+ const legacyOnlyFields = Object.keys(legacyConfig).filter(key => !(key in mainConfig));
125
+ const mainOnlyFields = Object.keys(mainConfig).filter(key => !(key in legacyConfig));
126
+
127
+ if (mainOnlyFields.length > 0) {
128
+ console.log(`📋 主配置独有字段: ${mainOnlyFields.join(', ')}`);
129
+ }
130
+
131
+ if (legacyOnlyFields.length > 0) {
132
+ console.log(`📋 Legacy 配置独有字段: ${legacyOnlyFields.join(', ')}`);
133
+ }
134
+
135
+ return true;
136
+ } catch (error) {
137
+ console.error('❌ 配置比较失败:', error.message);
138
+ return false;
139
+ }
140
+ }
141
+
142
+ // 主测试函数
143
+ function runTests() {
144
+ console.log('🎯 开始测试 Prettier 配置包\n');
145
+
146
+ const tests = [
147
+ { name: '配置加载', fn: testConfigLoading },
148
+ { name: '文件存在性', fn: testFileExistence },
149
+ { name: 'package.json 结构', fn: testPackageJson },
150
+ { name: '配置差异', fn: testConfigDifferences },
151
+ ];
152
+
153
+ let passedTests = 0;
154
+
155
+ tests.forEach(test => {
156
+ if (test.fn()) {
157
+ passedTests++;
158
+ }
159
+ });
160
+
161
+ console.log(`\n📊 测试结果: ${passedTests}/${tests.length} 通过`);
162
+
163
+ if (passedTests === tests.length) {
164
+ console.log('🎉 所有测试通过!配置包准备就绪。');
165
+ process.exit(0);
166
+ } else {
167
+ console.log('❌ 部分测试失败,请检查配置。');
168
+ process.exit(1);
169
+ }
170
+ }
171
+
172
+ // 运行测试
173
+ if (require.main === module) {
174
+ runTests();
175
+ }
176
+
177
+ module.exports = {
178
+ testConfigLoading,
179
+ testFileExistence,
180
+ testPackageJson,
181
+ testConfigDifferences,
182
+ runTests,
183
+ };