1

I'm using the AST tool to build a custom esLint rule. I want to build a rule that throws a warning whenever I use hardcoded strings in a function call.

Example:

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

I have built the rules like so:

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

It doesn't work, this is the AST playground. You can see the difference between the two Literals which is the property raw. However, my rule doesn't work.

Edit

Included the .eslintrc.js file:

  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
  },
halfer
  • 19,824
  • 17
  • 99
  • 186
Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68

1 Answers1

4

Maybe you should walk through CallExpression instead of 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')
      }
    }
  })
}
Zmen Hu
  • 795
  • 3
  • 12
  • Thanks for your answer! I get this error `Definition for rule 'custom-rule/no-hardcoded-strings' was not found.eslint(custom-rule/no-hardcoded-strings)`. I included my `.eslintrc.js` file. Is there a place where I could test if it works outside my project? Like a code playground? – Manuel Abascal Mar 19 '20 at 03:01
  • @ManuelAbascal where did you put your plugin, Have you install it? – Zmen Hu Mar 19 '20 at 03:20
  • I followed these instructions https://blog.webiny.com/create-custom-eslint-rules-in-2-minutes-e3d41cb6a9a0 – Manuel Abascal Mar 19 '20 at 03:32
  • 2
    @ManuelAbascal I pushed my demo here: https://gitlab.com/ZmenHu/eslint-plugin-hardcode-string – Zmen Hu Mar 19 '20 at 06:30
  • My man! You rock! It works like a charm! I just need to find a way to add it to my project! Thank you brotha! – Manuel Abascal Mar 19 '20 at 15:06
  • @Zmen Hu thanks man! the trick with package.json `file` worked – cleison Apr 30 '20 at 15:10