5

如何给项目添加eslint校验

 3 years ago
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.
neoserver,ios ssh client

如何给项目添加eslint校验

本文共有1955个字,关键词:

给一个纯原生的项目添加eslint,如:remember-scroll

  1. 做到项目运行时自动提示语法错误。
  2. 做到 git commit 时校验语法错误。

1. 安装和配置eslint

  1. 安装eslint
npm install eslint --save-dev
  1. 初始化.eslintrc.js
npx eslint --init
  1. 可能还需配置一些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,
    }
};
  1. 在根目录添加.eslintignore:
node_modules
dist

2.git commit添加校验

使用lint-staged 添加git commit钩子

npx mrm@2 lint-staged

这个命令会根据package.json里面的依赖工具,自动安装和配置好 huskylint-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项目请自行搜索对应的插件或配置方法。

  1. 安装@rollup/plugin-eslint
npm install @rollup/plugin-eslint --save-dev
  1. rollup.config.js配置
import eslint from '@rollup/plugin-eslint'

export default {
  // ...
  plugins: [
    eslint({
      throwOnError: true,
      throwOnWarning: true,
      include: ['src/**'],
      exclude: ['node_modules/**']
    }),
    // ...
  ]
}

至此,已经实现了我们的前面提到的两个目标啦,可以测试一下。

「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」

版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK