我无法使我的自定义 eslint 规则起作用

I can't make my custom eslint rule to work

我正在使用 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
  },

也许你应该走过 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')
      }
    }
  })
}