最新版eslint 搭配prettier应该如何配置
时间: 2024-06-18 16:03:56 浏览: 8
最新版的ESLint搭配Prettier需要进行以下配置:
1. 安装依赖:
```
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier --save-dev
```
2. 创建配置文件`.eslintrc.js`:
```javascript
module.exports = {
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
node: true,
es6: true,
},
extends: ['eslint:recommended', 'plugin:react/recommended', 'prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
},
};
```
3. 创建Prettier配置文件`.prettierrc.js`:
```javascript
module.exports = {
trailingComma: 'es5',
tabWidth: 2,
semi: true,
singleQuote: true,
};
```
4. 在VS Code中安装ESLint和Prettier插件,并在Settings中添加以下配置:
```json
"editor.formatOnSave": true,
"eslint.enable": true,
"eslint.autoFixOnSave": true,
"[javascript]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[javascriptreact]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[typescript]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[typescriptreact]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
```
完成以上配置后,ESLint和Prettier就可以愉快地一起工作了。同时,VS Code还会在保存文件时自动格式化代码。如果你想在终端中运行ESLint和Prettier,可以在package.json中添加以下命令:
```json
"scripts": {
"lint": "eslint .",
"format": "prettier --write '**/*.{js,jsx,ts,tsx}'"
}
```
然后在终端中运行`npm run lint`和`npm run format`即可。