Appearance
Prettier构建工具集成
Prettier可以与各种构建工具集成,以在构建过程中自动格式化代码。本指南详细介绍了如何将Prettier与主流构建工具集成。
与npm脚本集成
基础格式化脚本
json
{
"scripts": {
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
"lint:format": "npm run format && npm run format:check"
}
}
高级格式化脚本
json
{
"scripts": {
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:changed": "pretty-quick --staged", // 只格式化暂存的文件
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"prettier --write",
"git add"
],
"*.{json,css,md}": [
"prettier --write",
"git add"
]
}
}
与Webpack集成
使用prettier-webpack-plugin
bash
npm install --save-dev prettier-webpack-plugin
javascript
// webpack.config.js
const PrettierPlugin = require('prettier-webpack-plugin');
module.exports = {
// ... 其他配置
plugins: [
new PrettierPlugin({
// Prettier选项
semi: true,
trailingComma: 'es5',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
// 仅格式化匹配的文件
pattern: 'src/**/*.js',
// 忽略格式化的文件
exclude: ['node_modules/**', 'dist/**'],
}),
],
};
自定义Webpack格式化插件
javascript
// webpack.prettier.plugin.js
class PrettierWebpackPlugin {
constructor(options = {}) {
this.options = {
pattern: '**/*.{js,jsx,ts,tsx,json,css,md}',
exclude: ['node_modules/**'],
prettierOptions: {},
...options
};
}
apply(compiler) {
compiler.hooks.emit.tapPromise(
'PrettierWebpackPlugin',
async (compilation) => {
const paths = Object.keys(compilation.assets)
.filter(filePath => this.matchesPattern(filePath));
for (const filePath of paths) {
const source = compilation.assets[filePath].source();
try {
const formatted = require('prettier').format(source, {
...this.options.prettierOptions,
filepath: filePath
});
if (formatted !== source) {
compilation.assets[filePath].source = () => formatted;
}
} catch (error) {
console.warn(`Prettier error for ${filePath}:`, error.message);
}
}
}
);
}
matchesPattern(filePath) {
// 检查文件路径是否匹配模式
return this.options.pattern.split(',').some(pattern => {
const minimatch = require('minimatch');
return minimatch(filePath, pattern.trim()) &&
!this.options.exclude.some(excludePattern =>
minimatch(filePath, excludePattern)
);
});
}
}
module.exports = PrettierWebpackPlugin;
与Vite集成
Vite插件
bash
npm install --save-dev vite-plugin-prettier
javascript
// vite.config.js
import { defineConfig } from 'vite';
import prettier from 'vite-plugin-prettier';
export default defineConfig({
plugins: [
prettier({
include: ['**/*.js', '**/*.ts', '**/*.json', '**/*.md'],
exclude: ['node_modules/**'],
formatOptions: {
semi: true,
trailingComma: 'es5',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
}
})
],
});
使用ESLint配合
当与ESLint一起使用时,通常推荐使用eslint-plugin-prettier:
bash
npm install --save-dev eslint-plugin-prettier eslint-config-prettier
json
// package.json
{
"scripts": {
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix",
"format": "prettier --write ."
}
}
javascript
// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'plugin:prettier/recommended', // 启用prettier规则
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
},
};
与Gulp集成
Gulp任务配置
bash
npm install --save-dev gulp-prettier
javascript
// gulpfile.js
const gulp = require('gulp');
const prettier = require('gulp-prettier');
gulp.task('format', () => {
return gulp
.src(['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx', 'src/**/*.json'])
.pipe(
prettier({
semi: true,
trailingComma: 'es5',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
})
)
.pipe(gulp.dest('src/'));
});
gulp.task('check-format', () => {
return gulp
.src(['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx', 'src/**/*.json'])
.pipe(
prettier({
semi: true,
trailingComma: 'es5',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
}, { errorOnUnformatted: true })
);
});
gulp.task('format-watch', () => {
gulp.watch('src/**/*.{js,jsx,ts,tsx,json}', gulp.series('format'));
});
与Grunt集成
Grunt任务配置
bash
npm install --save-dev grunt-prettier
javascript
// Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
prettier: {
options: {
config: '.prettierrc.json',
ignorePath: '.prettierignore',
},
all: {
src: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx', 'src/**/*.json'],
},
},
});
grunt.loadNpmTasks('grunt-prettier');
grunt.registerTask('format', ['prettier']);
grunt.registerTask('default', ['prettier']);
};
与CI/CD集成
GitHub Actions
yaml
# .github/workflows/format-check.yml
name: Format Check
on: [push, pull_request]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run Prettier check
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}"
GitLab CI
yaml
# .gitlab-ci.yml
prettier:
stage: test
image: node:16
script:
- npm ci
- npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}"
only:
- branches
Jenkins Pipeline
groovy
// Jenkinsfile
pipeline {
agent any
stages {
stage('Prettier Check') {
steps {
sh 'npm ci'
sh 'npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}"'
}
}
}
}
与自动化工具集成
Pre-commit Hook
bash
npm install --save-dev husky lint-staged
json
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx,json,css,md}": [
"prettier --write",
"git add"
]
}
}
pretty-quick
bash
npm install --save-dev pretty-quick
json
// package.json
{
"scripts": {
"format-changed": "pretty-quick --staged"
},
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
}
}
与Monorepo工具集成
Lerna集成
json
// package.json
{
"scripts": {
"format": "lerna exec --concurrency 1 -- npx prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "lerna exec --concurrency 1 -- npx prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\""
}
}
Yarn Workspaces集成
json
// package.json
{
"scripts": {
"format": "yarn workspaces run prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "yarn workspaces run prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\""
}
}
性能优化
使用缓存
bash
# Prettier本身没有内置缓存,但可以使用第三方工具
npm install --save-dev cache-loader
javascript
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: 'cache-loader'
},
{
loader: 'prettier-loader',
options: {
// Prettier选项
}
}
]
}
]
}
};
并行处理
bash
# 使用npm-run-all并行运行
npm install --save-dev npm-run-all
json
{
"scripts": {
"format:js": "prettier --write \"src/**/*.js\"",
"format:css": "prettier --write \"src/**/*.css\"",
"format:json": "prettier --write \"src/**/*.json\"",
"format": "npm-run-all format:**"
}
}
最佳实践
1. 分阶段集成
先在开发环境中集成Prettier,然后逐步添加到构建流程中。
2. 选择性格式化
只为特定类型的文件启用格式化:
json
{
"scripts": {
"format:code": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
"format:data": "prettier --write \"src/**/*.{json,yaml,yml}\"",
"format:style": "prettier --write \"src/**/*.{css,scss,less}\"",
"format:docs": "prettier --write \"**/*.{md}\""
}
}
3. 与团队协作
确保团队所有成员都使用相同的格式化配置,使用共享的配置文件。
4. 版本控制
将Prettier配置文件添加到版本控制中,确保所有开发者使用相同配置。
5. 增量格式化
只格式化变更的文件以提高性能:
bash
# 只格式化git暂存的文件
npx pretty-quick --staged
# 或者使用lint-staged
npx lint-staged
通过这些构建工具集成,您可以确保代码在开发、构建和部署过程中保持一致的格式,提高代码质量和团队协作效率。