WebEssentials tslint custom rules

有些话、适合烂在心里 提交于 2020-01-25 07:03:24

问题


I have a tslint.json file in my solution directory and I'm trying to create a custom rule following the guidelines on https://www.npmjs.com/package/tslint

I have created a "nonImportsRule.ts", have copied the code from the link and have added "no-imports": true to my tslint.json file however the rule is not being picked up.

The guide says that a rulesDirectory needs to be specified, but I have no idea where this should be configured?

Also - is it possible to setup Web Essentials to break the build if tslint rules are violated?


回答1:


I had a same kind of a problem. I wanted to use the TSLint extensions, tslint-microsoft-contrib and codelyzer, together with Web Analyzer. This did not work. The first step to figure out why was to make an adaptation in server.js which can be found in C:\Users\[User]\AppData\Local\Temp\WebAnalyzer1.7.75. I changed the TSLint function into:

tslint: function (configFile, files) {
    // Try catch tslint errors 
    try {

        var tslint = require("tslint");
        var options = {
            formatter: "json",
            configuration: JSON.parse(fs.readFileSync(configFile, "utf8").trim())
        };

        var results = [];

        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var ll = new tslint(file, fs.readFileSync(file, "utf8"), options);
            results = results.concat(JSON.parse(ll.lint().output));
        }

    } catch(error) {
        // Return tslint error to visual studio so we can get some ideas for counter measures.
        var result = JSON.parse('[{"endPosition": {"character": 0,"line": 0,"position": 0},"failure": "INSTALL ERROR","name": "/","ruleName": "INSTALL ERROR","startPosition": {"character": 0,"line": 0,"position": 0}}]');
        result[0].failure = error.message;
        return result;
    }

    return results;
},

The alternation resulted in error feedback in the visual studio error list when I run the Web Analyzer. Do not forget to force a new instance of node.exe with the task manager after you have applied the alternation. The feedback leaded, for my particular situation, to the following installation of npm packages in the following directories:

Packages:

  • "codelyzer": "0.0.12"
  • "tslint": "^3.7.3"
  • "tslint-microsoft-contrib": "^2.0.2"
  • "typescript": "^1.8.9"

Directories:

  • C:\Users\[User]\AppData\Local\Temp\WebAnalyzer1.7.75
  • C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

After this, Web Analyzer was able to use the same tslint rules as my grunt task. Hopefully a newer version of Web Analyzer will solve my problems more elegantly.




回答2:


Okay, i'm not using Web Essentials extension but Web Analyzer : https://visualstudiogallery.msdn.microsoft.com/6edc26d4-47d8-4987-82ee-7c820d79be1d

So i won't be able to answer on this question 100%, but i want to summarize here my experience with custom tslint rules. First of all, what is not completely clear from documentation is that the whole thing depends on node.js.

  1. So first of all you need to install node js. This will give you npm command to your command line.
  2. After install with npm tslint and typescript. https://github.com/palantir/tslint here are examples. These will create files in : "c:\Users[Username]\AppData\Roaming\npm\node_modules"
  3. Go into "c:\Users[Username]\AppData\Roaming\npm\node_modules\tslint\lib\rules\". Create here noImportRule.ts. Copy the following content:

    import * as ts from "typescript";
    import * as Lint from "../lint";
    
    export class Rule extends Lint.Rules.AbstractRule {
        public static FAILURE_STRING = "import statement forbidden EDE";
    
        public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
         return this.applyWithWalker(new NoImportsWalker(sourceFile,      this.getOptions()));
        }
        }
    
     // The walker takes care of all the work.
     class NoImportsWalker extends Lint.RuleWalker {
     public visitImportDeclaration(node: ts.ImportDeclaration) {
    // 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.visitImportDeclaration(node);
    }
    }
    

Note that in the example import lint is not given with relative path that won't work with this approach. 4. Fire the command : "tsc -m commonjs --noImplicitAny .\noImportsRule.ts". This will compile your custom rule's ts. You will get bunch of compilation errors, such as: ../enableDisableRules.d.ts(1,21): error TS2307: Cannot find module 'typescript'. That's a good question why are these thrown, but forget about them, js file will be generated anyway. 5. Put "no-imports": true to your tslint.json(for now this should be custom one). With this command from command line: tslint -c 'sample.tslint.json' test.ts you will get: test.ts[1, 1]: import statement forbidden. So you made the custom rule working!!! :)

That's all for working from command line. In addition I made custom rules working with WebAnalyzer, at least temporary. I needed to copy my custom rule's files here: c:\Users[Username]\AppData\Local\Temp\WebAnalyzer1.6.65\node_modules\tslint\lib\rules\ and of course configure WebAnalyzer tslint.json to include custom rules. I have no idea how Web Essentials extension makes this whole thing working with tslint, but i guess some way similar :). Somewhere there should be a folder (node_modules\tslint\lib\rules) with rules what tslint uses. There you need to copy your custom ones. Of course the most elegant solution would be to modify Web Essentials extension itself and make the tslint's custom rules directory configurable from visual studio. (so my solution is just a workaround)

Here is my custom rule example in the visual studio warning's list:



来源:https://stackoverflow.com/questions/33518722/webessentials-tslint-custom-rules

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