问题
What is the best way to ensure that there are only ASCII characters in my TypeScript and corresponding JavaScript files?
回答1:
There isn't a rule for it yet.
Custom rule
From : https://github.com/palantir/tslint/#writing-custom-rules
The following is one idea:
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);
}
That is a good enough sample I leave to you to test and debug. Enjoy 🌹
来源:https://stackoverflow.com/questions/40393263/how-do-you-ensure-there-are-no-non-ascii-characters-in-typescript-files