我只能为您提供打字稿的解决方案。
我认为仅使用 TSLint/ESLint 无法实现这一点。
有一个所谓的规则class-name 可以部分解决您的问题,但似乎您需要为这种情况编写自定义规则。
所以让我们试着写这样的custom tslint rule。为此,我们需要在 tslint 配置中使用 rulesDirectory 选项来指定自定义规则的路径
"rulesDirectory": [
"./tools/tslint-rules/"
],
由于我要在 typescript 中编写自定义规则,我将使用 tslint@5.7.0 中添加的一项功能
[增强] 自定义 lint 规则将使用节点路径解析
允许像 ts-node (#3108) 这样的加载器的分辨率
我们需要安装ts-node包
npm i -D ts-node
然后在 tslint.json 中添加假规则
"ts-loader": true,
并在我们的 rulesDirectory 中创建文件 tsLoaderRule.js:
const path = require('path');
const Lint = require('tslint');
// Custom rule that registers all of the custom rules, written in TypeScript, with ts-node.
// This is necessary, because `tslint` and IDEs won't execute any rules that aren't in a .js file.
require('ts-node').register({
project: path.join(__dirname, '../tsconfig.json')
});
// Add a noop rule so tslint doesn't complain.
exports.Rule = class Rule extends Lint.Rules.AbstractRule {
apply() {}
};
这基本上是一种广泛用于有角材料、通用等角包的方法
现在我们可以创建将用打字稿编写的自定义规则(class-name 规则的扩展版本)。
myReactComponentRule.ts
import * as ts from 'typescript';
import * as Lint from 'tslint';
export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
static metadata: Lint.IRuleMetadata = {
ruleName: 'my-react-component',
description: 'Enforces PascalCased React component class.',
rationale: 'Makes it easy to differentiate classes from regular variables at a glance.',
optionsDescription: 'Not configurable.',
options: null,
optionExamples: [true],
type: 'style',
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
static FAILURE_STRING = (className: string) => `React component ${className} must be PascalCased and prefixed by Component`;
static validate(name: string): boolean {
return isUpperCase(name[0]) && !name.includes('_') && name.endsWith('Component');
}
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}
function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isClassLikeDeclaration(node) && node.name !== undefined && isReactComponent(node)) {
if (!Rule.validate(node.name!.text)) {
ctx.addFailureAtNode(node.name!, Rule.FAILURE_STRING(node.name!.text));
}
}
return ts.forEachChild(node, cb);
});
}
function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration {
return node.kind === ts.SyntaxKind.ClassDeclaration ||
node.kind === ts.SyntaxKind.ClassExpression;
}
function isReactComponent(node: ts.Node): boolean {
let result = false;
const classDeclaration = <ts.ClassDeclaration> node;
if (classDeclaration.heritageClauses) {
classDeclaration.heritageClauses.forEach((hc) => {
if (hc.token === ts.SyntaxKind.ExtendsKeyword && hc.types) {
hc.types.forEach(type => {
if (type.getText() === 'React.Component') {
result = true;
}
});
}
});
}
return result;
}
function isUpperCase(str: string): boolean {
return str === str.toUpperCase();
}
最后我们应该把我们的新规则放到tsling.json:
// Custom rules
"ts-loader": true,
"my-react-component": true
所以这样的代码
App extends React.Component
将导致:
我还创建了 ejected react-ts 应用程序,您可以在其中试用。
更新
我想跟踪祖父母的班级名称不会是一件小事
我们确实可以处理继承。为此,我们需要创建从 Lint.Rules.TypedRule 类扩展的规则以访问 TypeChecker:
myReactComponentRule.ts
import * as ts from 'typescript';
import * as Lint from 'tslint';
export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
static metadata: Lint.IRuleMetadata = {
ruleName: 'my-react-component',
description: 'Enforces PascalCased React component class.',
rationale: 'Makes it easy to differentiate classes from regular variables at a glance.',
optionsDescription: 'Not configurable.',
options: null,
optionExamples: [true],
type: 'style',
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
static FAILURE_STRING = (className: string) =>
`React component ${className} must be PascalCased and prefixed by Component`;
static validate(name: string): boolean {
return isUpperCase(name[0]) && !name.includes('_') && name.endsWith('Component');
}
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, undefined, program.getTypeChecker());
}
}
function walk(ctx: Lint.WalkContext<void>, tc: ts.TypeChecker) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (
isClassLikeDeclaration(node) && node.name !== undefined &&
containsType(tc.getTypeAtLocation(node), isReactComponentType) &&
!Rule.validate(node.name!.text)) {
ctx.addFailureAtNode(node.name!, Rule.FAILURE_STRING(node.name!.text));
}
return ts.forEachChild(node, cb);
});
}
/* tslint:disable:no-any */
function containsType(type: ts.Type, predicate: (symbol: any) => boolean): boolean {
if (type.symbol !== undefined && predicate(type.symbol)) {
return true;
}
const bases = type.getBaseTypes();
return bases && bases.some((t) => containsType(t, predicate));
}
function isReactComponentType(symbol: any) {
return symbol.name === 'Component' && symbol.parent && symbol.parent.name === 'React';
}
/* tslint:enable:no-any */
function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration {
return node.kind === ts.SyntaxKind.ClassDeclaration ||
node.kind === ts.SyntaxKind.ClassExpression;
}
function isUpperCase(str: string): boolean {
return str === str.toUpperCase();
}
参见提交: