VUE开发--TSLint配置规则(五十四)

一、TSLint简介

TSLint为TypeScript提供了代码检查能力,对使用TypeScript的React Native工程,在规范性、安全性、可靠性、可维护性等方面起到重要作用。
https://github.com/AlloyTeam/tslint-config-alloy/blob/master/index.js

二、配置文件tslint.json

{
  "defaultSeverity": "warning",
  "extends": [
    "tslint:recommended"
  ],
  "linterOptions": {
    "exclude": [
      "node_modules/**"
    ]
  },
  "rules": {
    "quotemark": [true, "single"],  // 字符串字面量需要使用 单引号 包裹
    "indent": [true, "spaces", 2],   // 检查代码缩紧,采用空格作为缩进单位
    "interface-name": false,
    "ordered-imports": false,
    "object-literal-sort-keys": false,
    "no-consecutive-blank-lines": false
  }
}

三、tslint.json规则说明

xtends?: 内设配置项名称
rules:  规则
    {
        //ts专用
        adjacent-overload-signatures : true,  // 强制函数重载为连续的。
        ban-comma-operator:true, //禁止逗号运算符。
        ban-type: [true, ["object","User {} instead."],["string"]] //禁止类型
        member-access: [true , "no-public"||"check-accessor"|| "check-constructor" || "check-parameter-property"  ] ,  //类成员必须声明 private public ....
        member-order: [true, {order:....}],  //类声明排序
        no-any: true,//不需使用any类型
        no-empty-interface:true //禁止空接口 {}
        no-import-side-effect: [true, {"ignore-module": "(\\.html|\\.css)$"}], //禁止导入带有副作用的语句
        no-inferrable-types:[true, "ignore-params", "ignore-properties"], //不允许将变量或参数初始化为数字,字符串或布尔值的显式类型声明。
        no-internal-module:true, //不允许内部模块
        no-magic-numbers: [true,1,2,3], //不允许在变量赋值之外使用常量数值。当没有指定允许值列表时,默认允许-1,0和1
        no-namespace: [ true,"allpw-declarations"], //不允许使用内部modules和命名空间
        no-non-null-assertion: true , //不允许使用!后缀操作符的非空断言。
        no-parameter-reassignment: true, //不允许重新分配参数
        no-reference: true, // 禁止使用/// <reference path=> 导入 ,使用import代替
        no-unnecessary-type-assertion: true, //如果类型断言没有改变表达式的类型就发出警告
        no-var-requires: true, //不允许使用var module = require("module"),用 import foo = require('foo')导入
        only-arrow-functions:[true,"allow-declarations","allow-named-functions"], //允许箭头表达式,不需要传统表达式 ; 允许独立的函数声明  ;允许表达,function foo() {}但不是function() {}
        prefer-for-of:true,  //建议使用for(..of)
        promise-function-async: true, 要求异步函数返回promise
        typedef: [true, "call-signature", "parameter", "member-variable-declaration"], //需要定义的类型存在
        typedef-whitespace: true, //类型声明的冒号之前是否需要空格
        unified-signatures: true, //重载可以被统一联合成一个
//function 专用
        await-promise: true,  //警告不是一个promise的await
        ban: [
                  true,
                  "eval",
                  {"name": "$", "message": "please don't"},
                  ["describe", "only"],
                  {"name": ["it", "only"], "message": "don't focus tests"},
                  {
                    "name": ["chai", "assert", "equal"],
                    "message": "Use 'strictEqual' instead."
                  },
                  {"name": ["*", "forEach"], "message": "Use a regular for loop instead."}
            ],
            curly: true, //for if do while 要有括号
            forin:true, //用for in 必须用if进行过滤
            import-blacklist:true, //允许使用import require导入具体的模块
            label-postion: true, //允许在do/for/while/swith中使用label
            no-arg:true, //不允许使用 argument.callee
            no-bitwise:true, //不允许使用按位运算符
            no-conditional-assignmen: true, //不允许在do-while/for/if/while判断语句中使用赋值语句
            no-console:true, //不能使用console
            no-construct: true, //不允许使用 String/Number/Boolean的构造函数
            no-debugger: true, //不允许使用debugger
            no-duplicate-super: true, //构造函数两次用super会发出警告
            no-empty:true, //不允许空的块
            no-eval: true, //不允许使用eval
            no-floating-promises: true, //必须正确处理promise的返回函数
            no-for-in-array: true, //不允许使用for in 遍历数组
            no-implicit-dependencies: true, //不允许在项目的package.json中导入未列为依赖项的模块
            no-inferred-empty-object-type: true, //不允许在函数和构造函数中使用{}的类型推断
            no-invalid-template-strings: true, //警告在非模板字符中使用${
            no-invalid-this:true, //不允许在非class中使用 this关键字
            no-misused-new: true, //禁止定义构造函数或new class
            no-null-keyword: true, //不允许使用null关键字
            no-object-literal-type-assertion:true, //禁止objext出现在类型断言表达式中
            no-return-await:true, //不允许return await
            arrow-parens: true, //箭头函数定义的参数需要括号
    }

四、常用规则

// 强制单行注释格式:'//' 后必跟空格
"comment-format": [true, "check-space"],
// 任何情况下,if / for / do / while 后必须通过 {} 包裹代码块
"curly": true,
// 文件必须用新的行结束
"eofline": true,
// 当使用 for in 语句遍历 object 时,强制使用 if 判断 key 是否由原型链继承 hasOwnProperty
"forin": true,
// 禁止数组中的模块全量引入,如:rxjs,需要导入其具体子模块
"import-blacklist": [true, "rxjs/Rx"],
// import { ModuleName } 确保 ModuleName 两端留有空格
"import-spacing": true,
// 检查代码缩紧,采用空格作为缩进单位
"indent": [true, "spaces"],
// 声明 interface 接口,代替 type 关键字声明类型
"interface-over-type-literal": true,
// ?label 是个什么东西?只允许 labels 在 do / for / while / switch 的声明中
"label-position": true,
// 一个文件最多定义一个 class,保证单一职责
"max-classes-per-file": [true, 1],
// 一行代码长度最长不超过 140 字符
"max-line-length": [true, 140],
// 不强制要求 class 的成员声明,例如:private || public
"member-access": false,
// 要求 class 内成员的声明顺序,不能乱放,静态属性,实例属性,静态方法,实例方法
"member-ordering": [
true,
{
"order": ["static-field", "instance-field", "static-method", "instance-method"]
}],
// 不允许使用 arguments.callee
"no-arg": true,
// 禁止使用位操作符,
// Specifically, the following bitwise operators are banned: &, &=, |, |=, ^, ^=, <<, <<=, >>, >>=, >>>, >>>=, and ~.
// This rule does not ban the use of & and | for intersection and union types.
"no-bitwise": true,
// 不许用 new Number() String Boolean 等基础类型的构造函数,允许使用函数式调用 Number(<string>)
// More details: https://stackoverflow.com/questions/4719320/new-number-vs-number
"no-construct": true,
// 不许用 debugger
"no-debugger": true,
// 不允许两次调用 super 函数
"no-duplicate-super": true,
// 不许有空代码块 {}
"no-empty": false,
// 不许有空接口
"no-empty-interface": true,
// 不许用 eval 函数
"no-eval": true,
// 声明立即被赋值的基础类型不需要声明变量类型,let state: boolean = false 删除类型声明
"no-inferrable-types": [true, "ignore-params"],
// 不要为 interface 定义 constructor 函数
"no-misused-new": true,
// Disallows non-null assertions using the ! postfix operator.
// 不许使用 params1!.func() 的语法校验参数值是否存在
"no-non-null-assertion": true,
// 不允许子作用域与外层作用域声明同名变量,
// (instance, instances) => {return instances.filter((instance)=>instance.neighbors.includes(instance))}
// Disallows shadowing variable declarations.
"no-shadowed-variable": true,
// 推荐使用 obj.property 代替 obj["property"],但是 obj["prop-erty"] 是被允许的
"no-string-literal": false,
// 不允许直接 throw 一个字符串字面量
// if (!productToAdd) {
// throw new Error("How can I add new product when no value provided?");
// }
"no-string-throw": true,
// 不允许使用 fall through,两个 switch case 之间没有 break 做分割
"no-switch-case-fall-through": true,
// 代码行尾不允许有空格
"no-trailing-whitespace": true,
// 不允许做 var|let unn = undefined 这种无意义赋值
"no-unnecessary-initializer": true,
// 禁止 unused expression
// 参考:https://eslint.org/docs/rules/no-unused-expressions
"no-unused-expression": true,
// 禁止声明前使用变量,针对 var 变量提升问题
"no-use-before-declare": true,
// 不许使用 var 声明变量
"no-var-keyword": true,
// Checks ordering of keys in object literals.
// 检查对象 key 的声明顺序
"object-literal-sort-keys": false,
// 检查流程控制代码的衔接部分和空格
"one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"],
// 优先使用 const 声明变量
"prefer-const": true,
// 字符串字面量需要使用 单引号 包裹
"quotemark": [true, "double"],
// 使用 parseInt 时需要定义 radix 参数
"radix": true,
// 每个声明后强制 ;
"semicolon": [true, "always"],
// 强制用 === 替换 ==
"triple-equals": [true, "allow-null-check"],
// 冒号左侧的空格数量,下面的列表中全部不要空格,
// "call-signature" checks return type of functions.
// "index-signature" checks index type specifier of indexers.
// "parameter" checks function parameters.
// "property-declaration" checks object property declarations.
// "variable-declaration" checks variable declaration.
"typedef-whitespace": [
true,{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"}],
// 校验两个重载函数是否可以通过 ;;rest 参数合并 (...params) => arguments
"unified-signatures": true,
// 校验变量名起的有没有问题,大小驼峰命名,过滤保留关键字
"variable-name": false,
//? "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"],
// 强制空格用法,
// if else for while 后面接一个空格
// 变量赋值的 = 两侧加空格
// 运算符两侧加空格
// 分隔符后加空格,<,|/|;>
// 变量类型声明前加空格
"whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"],
// FROM Codelyzer: Angular 表达式内的空格检查
// ? checks for whitespace before and after the interpolation characters
"angular-whitespace": [true, "check-interpolation"],
// Disallows using of ViewEncapsulation.None
// ?不允许视图封装.None?
"use-view-encapsulation": true,
// 确保正确的生命周期函数声明
"contextual-life-cycle": true,
// ? () 需要包裹在 [] 内
"banana-in-box": true,
// 事件绑定不使用 'on-' 前缀
"no-output-on-prefix": true,
// 使用 class 中的 @Input 声明输入属性,而不是在元数据结构中
"use-input-property-decorator": true,
// 同上,使用 @output 声明对外输出的数据变量
"use-output-property-decorator": true,
// 使用 @HostProperty 而不是声明元数据
"use-host-property-decorator": true,
// 禁止输入属性重命名
"no-input-rename": true,
// 同上,output
"no-output-rename": true,
// 显式声明组件实例化使用的 生命周期钩子函数
"use-life-cycle-interface": true,
// 管道指令需要声明实现 PipeTransform 接口
"use-pipe-transform-interface": true,
// 组件和指令命名,需要包含关键字 'Component' || 'Direction'
"component-class-suffix": true,
"directive-class-suffix": true

五、VSCode插件安装

TSLint插修的

设置

常见问题:

  1. Vuejs报错error: Unexpected console statement (no-console) at src... 解决办法
    在项目的根目录下的 package.json文件中的eslintConfig:{}中的 “rules”: {加入"no-console":“off”},
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {
      "no-console":"off"
    },
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,049评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,478评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,109评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,097评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,115评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,280评论 1 279
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,748评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,398评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,553评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,440评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,487评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,176评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,750评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,821评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,049评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,559评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,150评论 2 341

推荐阅读更多精彩内容