简体   繁体   English

如何在TSLint中对js和ts使用相同的规则

[英]How to use the same rules for js and ts in TSLint

I want to use the same style in .js files and .ts files. 我想在.js文件和.ts文件中使用相同的样式。 I know there is jsRules property in tslint.json, but I see 2 problems with it: 我知道tslint.json中有jsRules属性,但我看到它有2个问题:

  • Copying ant pasting exactly the same rules 复制蚂蚁粘贴完全相同的规则
  • When extending some configurations, eg tslint-react, you don't get the rules in jsRules, meaning that you have to go to the source code of the ruleset and copy it manually. 在扩展某些配置时,例如tslint-react,您不会在jsRules中获取规则,这意味着您必须转到规则集的源代码并手动复制它。

Any other way to have the same code style without having to maintain both eslint and tslint? 任何其他方式具有相同的代码样式而不必同时维护eslint和tslint?

Not everyone knows that, but TSLint configuration doesn't have to come in a .json file. 不是每个人都知道,但TSLint配置不必.json在.json文件中。 You can use the .js extension, and keep whatever logic you like inside. 您可以使用.js扩展名,并保留您喜欢的任何逻辑。

In this case, we can split TSLint rules into two categories — universal rules and React-specific ones. 在这种情况下,我们可以将TSLint规则分为两类 - 通用规则和React特定规则。 Both rulesets will be used for TypeScript files, but only the first ones will be applied to JavaScript. 这两个规则集都将用于TypeScript文件,但只有第一个规则集将应用于JavaScript。

tslint.js

const UNIVERSAL_RULES = {
  "max-line-length": [true, 120]
}

const REACT_RULES = {
  "jsx-space-before-trailing-slash": true
}

module.exports = {
  extends: [
    "tslint:recommended"
  ],
  jsRules: UNIVERSAL_RULES,
  rules: {
    ...UNIVERSAL_RULES,
    ...REACT_RULES
  }
}

When running TSLint CLI, it may be required to point to your configuration file explicitly. 运行TSLint CLI时,可能需要显式指向您的配置文件。 You can do that by adding --config tslint.js to your tslint command. 您可以通过将--config tslint.js添加到tslint命令来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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