介绍
Javascript 是一门弱类型语言,所以语法检查变得尤为重要。虽然有很多前端IDE开发工具,可以很好地帮助我们提示在编写时的错误,但是大多数开发者还是使用的像 Sublime Text、Visual Studio Code 之类的轻量级编辑器,这导致在开发中很容易出现各种错误,比如单词拼写错误,漏掉了括号等。而且每个人的代码编写习惯也不一样,因此有的项目的代码格式千差万别,比如 缩进空格数,有的习惯4个,有的习惯2个,这也导致项目维护起来越来越麻烦,遇到错误也很难定位。因此对 Javascript 进行语法检查的工具应运而生,目前 ESLint 使用最为广泛。这篇将讲解如何将 ESLint 集成到我们的项目中。
使用方式
配置后格式化代码(alt + shift + f)的同时也可以自动修复小问题。VSCode可以直接设置保存自动格式化。
VSCode 全局设置
VSCode settings.json 文件添加下面设置:
可能与你原来的设置有重复的项目,按照你自己需要选择即可
{ "workbench.colorTheme": "One Dark Pro", "workbench.iconTheme": "vscode-icons", "vetur.validation.script": false, "vetur.validation.template": false, "vetur.validation.style": false, "diffEditor.ignoreTrimWhitespace": false, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ], "eslint.workingDirectories": [{ "mode": "auto" }], "editor.defaultFormatter": "esbenp.prettier-vscode"}
项目中 ESLint 设置
.eslintrc.js:
const allExtensions = ['.js', '.jsx', '.vue'];module.exports = { root: true, env: { node: true, }, extends: ["plugin:vue/vue3-essential", 'eslint:recommended', '@vue/prettier'], parserOptions: { parser: 'babel-eslint', }, plugins: ['import'], rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-unused-vars': 'warn', 'import/order': [ 'warn', { 'newlines-between': 'always', alphabetize: { order: 'asc', }, }, ], 'import/first': 'warn', 'import/newline-after-import': [ 'warn', { count: 1, }, ], 'import/no-cycle': 'warn', }, settings: { 'import/extensions': allExtensions, 'import/external-module-folders': ['node_modules'], 'import/resolver': { node: { extensions: allExtensions, }, webpack: { config: './node_modules/@vue/cli-service/webpack.config.js', }, }, },};
项目中 Prettier 设置
prettier.config.js:
module.exports = {
semi: true,
singleQuote: true,
trailingComma: 'es5',
arrowParens: 'always',
printWidth: 120,
};
项目依赖相关
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"@vue/eslint-config-prettier": "^6.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-import-resolver-webpack": "^0.13.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-vue": "^6.2.2",
"prettier": "^1.19.1",
"node-sass": "^4.14.1",
"sass-loader": "^7.0.1"
},