简体   繁体   中英

Custom TSLint Rule in TypeScript with Angular 7 and `ng lint`

I have a new workspace for a library I am maintaining. We have 2 custom TSLint rules that we were using in Angular 5 that did not leverage the Angular CLI. We are now moving to Angular CLI and Angular 7.

One thing we had working was not needing to compile these TSLint rules to JS before TSLint would pick them up. However, this required ts-node to be used in our package.json 's lint script.

How can I tell ng to pickup these TypeScript TSLint rule files?

tsconfig.json (in projects/my-lib/src )

{
  "rulesDirectory": "./lib/tslint-rules"
}

Then, in our main workspace, we extend this tsconfig from the library and add our custom rule.

Could not find implementations for the following rules specified in the configuration:
    my-custom-tslint-rule
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.

Ok, so I figured this out. There are a few things you need to do if you want to include custom TSLint rules in your Angular library.

  1. Ensure they are being exported in your public_api.ts . This will ensure that when you run ng build <library-name> that the TypeScript compiler will pick up those files and compile them and put them in the dist folder.

  2. Configure your tsconfig.lib.json to use non-es6/es2015 modules. This is what was causing many issues for me. It seems that TSLint doesn't support es2015 style modules. I've switched it to use umd instead. (I also noted that commonjs worked fine as well.)

{
  "compilerOptions": {
    ...
    "module": "umd",
  }
}
  1. In any project where this is library is installed, you can pick up your rules by doing the following. Edit your tslint.json and add the installed node_modules tslint-rules to your tslint.json . Then, add your specific rules to the list of rules.
  "rulesDirectory": [
    // ...,
    "node_modules/<my-package>/esm2015/lib/tslint-rules"
  ],

Then, add your configured rule as follows:

  "rules": {
    // ...,
    "my-custom-rule": true,
    // ...
  }
  1. Alternatively, you can also setup a tslint-default.json in your library, and copy that into your dist folder after running ng build . This should have the rule directory added and the default setup for your custom rules.

Then, when you install this package elsewhere, you only need to extend this tslint-default.json from the installed node_modules folder.

Hope this helps anyone who is trying to build an Angular library and include custom TSLint rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM