如何给项目添加eslint校验
source link: https://www.fengxianqi.com/index.php/archives/163/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
如何给项目添加eslint校验
给一个纯原生的项目添加eslint,如:remember-scroll。
- 做到项目运行时自动提示语法错误。
- 做到
git commit
时校验语法错误。
1. 安装和配置eslint
- 安装eslint
npm install eslint --save-dev
- 初始化
.eslintrc.js
npx eslint --init
- 可能还需配置一些
global
变量和exclude node_modules,博主这里最终的.eslint.js
如下:
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
},
globals: {
"process": true,
"__dirname": true,
"module": true,
}
};
- 在根目录添加
.eslintignore
:
node_modules
dist
2.git commit添加校验
使用lint-staged 添加git commit
钩子
npx mrm@2 lint-staged
这个命令会根据package.json里面的依赖工具,自动安装和配置好 husky
和 lint-staged
,跑完后就能在git commit。该命令还会更改我们的package.json
文件,注意其中有一行是:
"lint-staged": {
"*.js": "eslint --cache --fix"
}
这就是在git commit时执行的命令: eslint --cache --fix
。
--cache
表示每次只校验有修改的文件,该参数会在根目录生成一个.eslintcache
文件,我们需要在.gitignore
中忽略这个文件。如果想每次都全量校验所有文件,可以把该参数去掉,去掉后就不会生成.eslintcache
文件了。--fix
表示自动修复。
3.项目运行时自动提示语法错误
由于我项目使用的是rollup
来打包,因此需要在rollup.config.js
里面去新增一个eslint相关的插件来做到,如果是webpack项目请自行搜索对应的插件或配置方法。
npm install @rollup/plugin-eslint --save-dev
rollup.config.js
配置
import eslint from '@rollup/plugin-eslint'
export default {
// ...
plugins: [
eslint({
throwOnError: true,
throwOnWarning: true,
include: ['src/**'],
exclude: ['node_modules/**']
}),
// ...
]
}
至此,已经实现了我们的前面提到的两个目标啦,可以测试一下。
「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK