【问题标题】:I can't make my custom eslint rule to work我无法让我的自定义 eslint 规则起作用
【发布时间】:2020-06-30 03:58:25
【问题描述】:

我正在使用AST 工具来构建自定义 esLint 规则。我想建立一个规则,每当我在 function 调用中使用硬编码的 strings 时都会引发警告。

示例:

var greet = 'Hello';
console.log('Hello') // throws an warning
console.log(greet) // doesn't throw a warning

我已经建立了这样的规则:

module.exports = {
  rules: {
    'no-hardcoded-strings': {
      create(context) {
        return {
          Literal(node) {
            if (node.raw) {
              context.report(node, 'Do not use hardcoded strings');
            }
          },
        };
      },
    },
  },
};

不行,这是AST playground。您可以看到两个字面量之间的区别,即属性raw。但是,我的规则不起作用。

编辑

包含.eslintrc.js 文件:

  plugins: ['custom-rule'],
  extends: [
    'airbnb-base',
    'plugin:cypress/recommended',
    'plugin:prettier/recommended',
    'plugin:json/recommended',
  ],
  settings: {
    'import/resolver': 'webpack',
  },
  rules: {
    'import/prefer-default-export': 'off',
    'import/no-default-export': 'warn',
    'eqeqeq': 'warn',
    'import/no-extraneous-dependencies': 'off',
    'camelcase': 'error',
    'no-unused-expressions': 'error',
    'custom-rule/no-hardcoded-strings': 1
  },

【问题讨论】:

    标签: javascript eslint abstract-syntax-tree linter


    【解决方案1】:

    也许你应该通过CallExpression 而不是Literal

    module.exports.rules = {
      'no-hardcoded-strings': context => ({
        CallExpression: node => {
          if (node.arguments.some(arg => arg.type === 'Literal' && arg.value)) {
            context.report(node, 'Do not use hardcoded strings')
          }
        }
      })
    }
    

    【讨论】:

    • 感谢您的回答!我收到此错误Definition for rule 'custom-rule/no-hardcoded-strings' was not found.eslint(custom-rule/no-hardcoded-strings)。我包括了我的.eslintrc.js 文件。有没有可以测试它是否在我的项目之外工作的地方?像代码游乐场?
    • @ManuelAbascal 你把你的插件放在哪里了,你安装了吗?
    • 我遵循了这些说明blog.webiny.com/…
    • @ManuelAbascal 我在这里推送了我的演示:gitlab.com/ZmenHu/eslint-plugin-hardcode-string
    • 我的男人!你摇滚!它就像一个魅力!我只需要找到一种方法将其添加到我的项目中!谢谢兄弟!
    猜你喜欢
    • 2016-02-03
    • 2020-01-29
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多