当前位置:   article > 正文

9. Eslint_eslint-output

eslint-output

1. 配置文件

配置文件由很多种写法:

  • .eslintrc.*:新建文件,位于项目根目录
    • .eslintrc
    • .eslintrc.js
    • .eslintrc.json
    • 区别在于配置格式不一样
  • package.json 中 eslintConfig:不需要创建文件,在原有文件基础上写。

2. 具体配置

  1. module.exports = {
  2. // 解析选项
  3. parserOptions: {},
  4. // 具体检查规则
  5. rules: {},
  6. // 继承其他规则
  7. extends: [],
  8. // ...
  9. // 其他规则详见:https://eslint.bootcss.com/docs/user-guide/configuring
  10. };
'
运行
  1. parserOptions 解析选项
  1. parserOptions: {
  2. ecmaVersion: 6, // ES 语法版本
  3. sourceType: "module", // ES 模块化
  4. ecmaFeatures: { // ES 其他特性
  5. jsx: true // 如果是 React 项目,就需要开启 jsx 语法
  6. }
  7. }

 ​​​​​​2. rules 具体规则

  • "off" 或 0 - 关闭规则
  • "warn" 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
  • "error" 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)
  1. rules: {
  2. semi: "error", // 禁止使用分号
  3. 'array-callback-return': 'warn', // 强制数组方法的回调函数中有 return 语句,否则警告
  4. 'default-case': [
  5. 'warn', // 要求 switch 语句中有 default 分支,否则警告
  6. { commentPattern: '^no default$' } // 允许在最后注释 no default, 就不会有警告了
  7. ],
  8. eqeqeq: [
  9. 'warn', // 强制使用 === 和 !==,否则警告
  10. 'smart' // https://eslint.bootcss.com/docs/rules/eqeqeq#smart 除了少数情况下不会有警告
  11. ],
  12. }

3. extends 继承

现有以下较为有名的规则:

  1. // 例如在React项目中,我们可以这样写配置
  2. module.exports = {
  3. extends: ["react-app"],
  4. rules: {
  5. // 我们的规则会覆盖掉react-app的规则
  6. // 所以想要修改规则直接改就是了
  7. eqeqeq: ["warn", "smart"],
  8. },
  9. };
'
运行

在 Webpack 中使用

npm i eslint-webpack-plugin eslint -D
  1. 定义 Eslint 配置文件
  • .eslintrc.js
  1. module.exports = {
  2. // 继承 Eslint 规则
  3. extends: ["eslint:recommended"],
  4. env: {
  5. node: true, // 启用node中全局变量
  6. browser: true, // 启用浏览器中全局变量
  7. },
  8. parserOptions: {
  9. ecmaVersion: 6,
  10. sourceType: "module",
  11. },
  12. rules: {
  13. "no-var": 2, // 不能使用 var 定义变量
  14. },
  15. };
'
运行
  • webpack.config.js
  1. const path = require("path");
  2. const ESLintWebpackPlugin = require("eslint-webpack-plugin");
  3. module.exports = {
  4. entry: "./src/index.js",
  5. output: {
  6. path: path.resolve(__dirname, "dist"),
  7. filename: "static/js/main.js",
  8. clean: true,
  9. },
  10. plugins: [
  11. new ESLintWebpackPlugin({
  12. context: path.resolve(__dirname, "src"),
  13. }),
  14. ],
  15. mode: "development",
  16. };

src / index.js

  1. var result1 = count(2, 1);
  2. console.log(result1);
  3. var result2 = sum(1, 2, 3, 4);
  4. console.log(result2);

执行 npx webpack

VSCode Eslint 插件 

        打开 VSCode,下载 Eslint 插件,即可不用编译就能看到错误,可以提前解决。但是此时就会对项目所有文件默认进行 Eslint 检查了,我们 dist 目录下的打包后文件就会报错。但是我们只需要检查 src 下面的文件,不需要检查 dist 下面的文件,所以可以使用 Eslint 忽略文件解决。在项目根目录新建下面文件:

  • .eslintignore
  1. # 忽略dist目录下所有文件
  2. dist
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/991067
推荐阅读
相关标签
  

闽ICP备14008679号