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.
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
},
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')
}
}
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.