确保我的TypeScript和相应的JavaScript文件中只有ASCII字符的最佳方法是什么?
答案 0 :(得分:5)
它还没有规则。
来自:https://github.com/palantir/tslint/#writing-custom-rules
以下是一个想法:
import * as ts from "typescript";
import * as Lint from "tslint/lib/lint";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "unicode forbidden";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new SourcefileWalker(sourceFile, this.getOptions()));
}
}
// The walker takes care of all the work.
class SourceFileWalker extends Lint.RuleWalker {
public visitSourceFile(node: ts.SourceFile) {
// ACTUAL TODO:
const text = node.getFullText();
// Match ascii only
if (!isASCII(text)){
// create a failure at the current position
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
// call the base version of this visitor to actually parse this node
super.visitSourceFile(node);
}
}
function isASCII(str, extended) {
return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str);
}
这是一个足够好的示例,我留给您进行测试和调试。享受