出于个人原因,我希望控制台。(日志|错误|...)始终写在一行中。
是否有经过测试且有效的 eslint 规则?
我的方法下面引入了一些任意语法问题
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)
},
})
}
}
}
},
}
},
}
事实证明,对其他规则的干扰导致了混乱 - 上面的规则在被自身调用时实际上有效(或在专用的
.eslintrc-custom
conf文件中)
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 }