- 优化Prettier配置:
- 使用
.prettierrc
文件:
- 在项目根目录创建
.prettierrc
文件(可以是JSON、YAML或JavaScript格式)。
- 配置
printWidth
选项,根据项目风格和屏幕宽度合理设置,例如120
,这样较长的类型定义不会被过度换行导致混乱。例如:
{
"printWidth": 120
}
- 调整
tabWidth
和useTabs
:
- 如果使用空格缩进,
tabWidth
设为合适的空格数,如4
;如果使用制表符,设置useTabs
为true
。
{
"tabWidth": 4,
"useTabs": false
}
singleQuote
和trailingComma
:
- 统一使用单引号
singleQuote: true
,并且合理设置trailingComma
为es5
或all
,这样在多行类型定义中,逗号的位置更一致,易于阅读。
{
"singleQuote": true,
"trailingComma": "es5"
}
- 编写自定义格式化逻辑(以ESLint插件为例):
- 创建ESLint插件:
- 初始化一个npm项目
npm init -y
。
- 安装必要依赖
npm install eslint - - save - dev
。
- 创建插件文件,例如
eslint - plugin - custom - types.js
。
- 编写规则:
- 在插件文件中定义规则,例如检查嵌套接口的缩进是否正确。
module.exports = {
rules: {
'nested - interface - indent': function (context) {
return {
InterfaceDeclaration(node) {
if (node.body && node.body.body) {
const firstChild = node.body.body[0];
if (firstChild) {
const indent = firstChild.range[0] - node.range[0];
for (const child of node.body.body) {
const childIndent = child.range[0] - node.range[0];
if (childIndent!== indent) {
context.report({
node: child,
message: 'Nested interface members should have consistent indent'
});
}
}
}
}
}
};
}
},
configs: {
recommended: {
rules: {
'custom - types/nested - interface - indent': 'error'
}
}
}
};
{
"plugins": ["custom - types"],
"extends": ["plugin:custom - types/recommended"]
}
- 结合IDE设置:
- 在VS Code中,确保Prettier插件和ESLint插件都正确安装和配置。
- 在VS Code的
settings.json
中,可以进一步微调格式化选项,例如设置editor.formatOnSave
为true
,确保保存文件时自动格式化。
{
"editor.formatOnSave": true
}
- 对于复杂类型嵌套的代码块,可以使用VS Code的代码折叠功能,将不相关的部分折叠起来,专注于当前查看的类型结构。