How do you ensure there are no non-ASCII characters in TypeScript files?

末鹿安然 提交于 2019-12-11 07:36:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!