for personal reasons I want console.(log|error|...) always to be written in one line.
is there a eslint rule for that which is tested and works?
my approach below introduces some arbitrary syntax problems
module.exports = {
meta: {
fixable: 'code',
},
create(context) {
return {
CallExpression(node) {
if (
node.callee.object &&
node.callee.object.name === 'console' &&
node.callee.property
) {
const sourceCode = context.getSourceCode()
const text = sourceCode.getText(node)
// Check if there are comments inside the console statement
const comments = sourceCode.getCommentsInside(node)
if (text.includes('\n')) {
if (comments.length > 0) {
// Raise a warning if there are comments inside
context.report({
node,
message:
'console.' +
node.callee.property.name +
' contains comments and should be checked manually',
})
} else {
// Fix the text if there are no comments
context.report({
node,
message:
'console.' +
node.callee.property.name +
' should be in one line',
fix(fixer) {
const fixedText = text.replace(/\n/g, ' ').replace(/\s+/g, ' ')
return fixer.replaceText(node, fixedText)
},
})
}
}
}
},
}
},
}
turns out that the interference with other rules was leading to the mess - the rule above actually works when called by itself (or in a dedicated .eslintrc-custom
conf-file )
npx eslint --fix --rule 'custom-eslint-rules/console-log-fix: ["error"]' . --ext .js,.jsx,.ts,.tsx
folder structure:
eslint
|- rules
|- console-log-fix.js
\ index.js
index.js
const fs = require('fs')
const path = require('path')
const rulesDir = path.join(__dirname, 'rules')
const ruleFiles = fs
.readdirSync(rulesDir)
.filter(file => file !== 'index.js' && !file.endsWith('test.js'))
const rules = Object.fromEntries(
ruleFiles.map(file => [
path.basename(file, '.js'),
require(path.join(rulesDir, file)),
])
)
module.exports = { rules }