创建社区节点规则
- 作者仓库星标 190,957
- 作者仓库 n8n
- 领域
- 通用
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @n8n-io · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- macOS · Linux · Windows
- 运行环境要求
- Node.js
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
第 1 步:了解规则
在编写代码之前,先澄清:该规则检测什么? (缺失属性、错误模式、不良价值)它适用于哪里? (`.node.ts` 文件、凭证类别,两者) 严重性:`error`(必须修复)或 `warn`(应修复)?可以修复吗?它可以安全地自动修复,还是只是建议?
第 2 步:实施规则
创建`src/rules/<rule-name>.ts`:命名:导出为`PascalCaseRule`(例如`MissingPairedItemRule`)。 `name` 字段是 kebab-case。可用的 AST 帮助器 - 请参阅 Reference.md 以获取 `ast-utils` 和 `file-utils` 导出的完整目录。
第 3 步:编写测试
创建`src/rules/<rule-name>.test.ts`:测试指南:始终测试是否跳过非 INodeType 类(有效情况) 测试错误消息和可修复规则的固定输出 对于带有选项的规则,测试每个选项组合
第 5 步:编写文档
创建`docs/rules/<rule-name>.md`:`` will be regenerated by `pnpm build:docs`上方的标题。编写一个合理的第一个版本——它会被覆盖。
第 6 步:验证
从`packages/@n8n/eslint-plugin-community-nodes/`运行:
# Create Community Node Lint Rule
Guide for adding new ESLint rules to `packages/@n8n/eslint-plugin-community-nodes/`.
All paths below are relative to `packages/@n8n/eslint-plugin-community-nodes/`.
## Step 1: Understand the Rule
Before writing code, clarify:
- **What** does the rule detect? (missing property, wrong pattern, bad value)
- **Where** does it apply? (`.node.ts` files, credential classes, both)
- **Severity**: `error` (must fix) or `warn` (should fix)?
- **Fixable?** Can it be auto-fixed safely, or only suggest?
- **Scope**: Both `recommended` configs, or exclude from `recommendedWithoutN8nCloudSupport`?
## Step 2: Implement the Rule
Create `src/rules/<rule-name>.ts`:
```typescript
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import {
isNodeTypeClass, // or isCredentialTypeClass
findClassProperty,
findObjectProperty,
createRule,
} from '../utils/index.js';
export const YourRuleNameRule = createRule({
name: 'rule-name',
meta: {
type: 'problem', // or 'suggestion'
docs: {
description: 'One-line description of what the rule enforces',
},
messages: {
messageId: 'Human-readable message. Use {{placeholder}} for dynamic data.',
},
fixable: 'code', // omit if not auto-fixable
hasSuggestions: true, // omit if no suggestions
schema: [], // add options schema if configurable
},
defaultOptions: [],
create(context) {
return {
ClassDeclaration(node) {
if (!isNodeTypeClass(node)) return;
const descriptionProperty = findClassProperty(node, 'description');
if (!descriptionProperty) return;
const descriptionValue = descriptionProperty.value;
if (descriptionValue?.type !== AST_NODE_TYPES.ObjectExpression) return;
// Rule logic here — use findObjectProperty(), getLiteralValue(), etc.
context.report({
node: targetNode,
messageId: 'messageId',
data: { /* template vars */ },
fix(fixer) {
return fixer.replaceText(targetNode, 'replacement');
},
});
},
};
},
});
```
**Naming**: Export as `PascalCaseRule` (e.g. `MissingPairedItemRule`). The `name` field is kebab-case.
**Available AST helpers** — see [reference.md](reference.md) for the full catalog of `ast-utils` and `file-utils` exports.
## Step 3: Write Tests
Create `src/rules/<rule-name>.test.ts`:
```typescript
import { RuleTester } from '@typescript-eslint/rule-tester';
import { YourRuleNameRule } from './rule-name.js';
const ruleTester = new RuleTester();
// Helper to generate test code — keeps test cases readable
function createNodeCode(/* parameterize the varying parts */): string {
return `
import type { INodeType, INodeTypeDescription } from 'n8n-workflow';
export class TestNode implements INodeType {
description: INodeTypeDescription = {
displayName: 'Test Node',
name: 'testNode',
group: ['input'],
version: 1,
description: 'A test node',
defaults: { name: 'Test Node' },
inputs: [],
outputs: [],
properties: [],
};
}`;
}
ruleTester.run('rule-name', YourRuleNameRule, {
valid: [
{ name: 'class that does not implement INodeType', code: '...' },
{ name: 'node with correct pattern', code: createNodeCode(/* correct */) },
],
invalid: [
{
name: 'descriptive case name',
code: createNodeCode(/* incorrect */),
errors: [{ messageId: 'messageId', data: { /* expected template vars */ } }],
output: createNodeCode(/* expected after fix */), // or `output: null` if no fix
},
],
});
```
**Test guidelines:**
- Always test that non-INodeType classes are skipped (valid case)
- Test both the error message and the fixed output for fixable rules
- For rules with options, test each option combination
- For rules using filesystem, mock with `vi.mock('../utils/file-utils.js')`
- For suggestion-only rules, use `errors: [{ messageId, suggestions: [...] }]`
## Step 4: Register the Rule
### 4a. Add to `src/rules/index.ts`
```typescript
import { YourRuleNameRule } from './rule-name.js';
// Add to the rules object:
export const rules = {
// ... existing rules
'rule-name': YourRuleNameRule,
} satisfies Record<string, AnyRuleModule>;
```
### 4b. Add to `src/plugin.ts` configs
Add to **both** config objects (unless the rule depends on n8n cloud features):
```typescript
'@n8n/community-nodes/rule-name': 'error', // or 'warn'
```
- Use `error` for rules that catch bugs or required patterns
- Use `warn` for style/convention rules (like `options-sorted-alphabetically`)
- If the rule uses `no-restricted-globals` or `no-restricted-imports` patterns,
only add to `recommended` (not `recommendedWithoutN8nCloudSupport`)
## Step 5: Write Documentation
Create `docs/rules/<rule-name>.md`:
```markdown
# Description of what the rule does (`@n8n/community-nodes/rule-name`)
<!-- end auto-generated rule header -->
## Rule Details
Explain why this rule exists and what problem it prevents.
## Examples
### Incorrect
\`\`\`typescript
// code that triggers the rule
\`\`\`
### Correct
\`\`\`typescript
// code that passes the rule
\`\`\`
```
The header above `<!-- end auto-generated rule header -->` will be regenerated by `pnpm build:docs`. Write a reasonable first version — it gets overwritten.
## Step 6: Verify
Run from `packages/@n8n/eslint-plugin-community-nodes/`:
```bash
pushd packages/@n8n/eslint-plugin-community-nodes
pnpm test <rule-name>.test.ts # tests pass
pnpm typecheck # types are clean
pnpm build # compiles
pnpm build:docs # regenerates doc headers and README table
pnpm lint:docs # docs match schema
popd
```
## Checklist
- [ ] Rule file: `src/rules/<rule-name>.ts`
- [ ] Test file: `src/rules/<rule-name>.test.ts`
- [ ] Registered in `src/rules/index.ts`
- [ ] Added to configs in `src/plugin.ts`
- [ ] Doc file: `docs/rules/<rule-name>.md`
- [ ] README table updated via `pnpm build:docs`
- [ ] All verification commands pass
章节与文件索引
按说明文件中的顺序排列。
第 1 步:了解规则
第 2 步:实施规则
第 3 步:编写测试
4b.添加到 src/plugin.ts 配置
第 5 步:编写文档
文件/命令 -> packages/@n8n/eslint-plugin-community-nodes/ · .node.ts · error · warn · recommended · recommendedWithoutN8nCloudSupport · src/rules/<rule-name>.ts · PascalCaseRule
内容校验值 -> 9ec259b1ea12
当前原文的自动摘译,尚未人工审校。
4b.添加到 src/plugin.ts 配置
添加到两个配置对象(除非规则依赖于 n8n 云功能): 将
error用于捕获错误或所需模式的规则 使用warn用于样式/约定规则(如options-sorted-alphabetically) 如果规则使用no-restricted-globals或no-restricted-imports模式,则仅添加到recommended(不recommendedWithoutN8nCloudSupport)