乐闻世界logo
搜索文章和话题

Prettier 的 ignore 文件如何配置?有哪些常用规则?

2月21日 16:56

Prettier 的 ignore 文件配置详解

Prettier 的 .prettierignore 文件允许指定不需要格式化的文件和目录,这对于优化性能和避免不必要的格式化非常重要。

基本语法

.prettierignore 文件使用类似 .gitignore 的语法:

shell
# 忽略 node_modules 目录 node_modules # 忽略构建产物 dist build out # 忽略特定文件 *.min.js *.min.css # 忽略特定目录 coverage .next .nuxt # 忽略配置文件 package-lock.json yarn.lock pnpm-lock.yaml

忽略模式

1. 目录忽略

shell
# 忽略整个目录 node_modules # 忽略嵌套目录 **/dist # 忽略特定路径的目录 src/dist

2. 文件扩展名忽略

shell
# 忽略所有 .min.js 文件 *.min.js # 忽略多个扩展名 *.min.js *.min.css *.min.html

3. 路径模式

shell
# 忽略特定路径下的文件 src/temp/*.js # 忽略所有子目录中的文件 **/*.test.js # 使用通配符 src/**/*.generated.js

4. 否定模式

shell
# 忽略所有 .js 文件,但保留 src 目录下的 *.js !src/**/*.js # 忽略 dist 目录,但保留 dist/public dist !dist/public

常见忽略规则

1. 依赖和构建产物

shell
node_modules dist build out .next .nuxt .cache

2. 压缩文件

shell
*.min.js *.min.css *.min.html *.bundle.js

3. 测试覆盖率

shell
coverage .nyc_output

4. 锁定文件

shell
package-lock.json yarn.lock pnpm-lock.yaml

5. 生成的文件

shell
*.generated.js *.generated.ts *.d.ts

6. 临时文件

shell
*.tmp *.temp *.swp

高级用法

1. 使用自定义 ignore 文件

bash
# 指定自定义 ignore 文件 prettier --write --ignore-path .prettierignore.custom "**/*.js"

2. 禁用默认忽略

bash
# 忽略 node_modules 也会被格式化 prettier --write --ignore-unknown "**/*.js"

3. 命令行指定忽略

bash
# 在命令行中指定忽略模式 prettier --write "**/*.js" --ignore "node_modules/**"

最佳实践

1. 性能优化

shell
# 忽略大型目录以提高性能 node_modules dist build coverage

2. 避免格式化第三方代码

shell
# 不格式化第三方库 lib/vendor public/assets/vendor

3. 保护特殊文件

shell
# 不格式化需要保持原样的文件 *.min.js *.min.css *.bundle.js

4. 项目特定规则

shell
# 根据项目需求自定义 src/generated/** scripts/temp/**

常见问题

1. ignore 规则不生效

  • 检查 .prettierignore 文件位置(应在项目根目录)
  • 确认语法正确(类似 .gitignore)
  • 使用 --debug-check 查看详细信息

2. 想要格式化被忽略的文件

bash
# 使用绝对路径绕过 ignore 规则 prettier --write /absolute/path/to/file.js # 临时修改 ignore 文件

3. 复杂的忽略模式

shell
# 组合使用多种模式 node_modules dist **/*.min.js !src/vendor/*.js

与其他工具的 ignore 文件

1. 与 .gitignore 协作

shell
# 可以在 .prettierignore 中引用 .gitignore # 但需要手动复制规则

2. 与 ESLint ignore 协作

shell
# .eslintignore 和 .prettierignore 可以有不同的规则 # 根据工具特性分别配置

通过合理配置 .prettierignore,可以优化 Prettier 的性能,避免不必要的格式化,提高开发效率。

标签:Prettier