tslint集成到webpack中,如何自定义实现linterOptions.exclude

tslint的 CLI 命令中已经支持了  linterOptions.exclude,在使用tslint CLI命令的时候在tslint.json中配置linterOptions即可应用上,但是集成到webpack的ts-loader调用tslint在检查代码的时候,并没有支持该功能。

咱们先看下webpack中include和exclude的说明文档

        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        exclude: [
          path.resolve(__dirname, "app/demo-files")
        ],
        // these are matching conditions, each accepting a regular expression or string
        // test and include have the same behavior, both must be matched
        // exclude must not be matched (takes preferrence over test and include)
        // Best practices:
        // - Use RegExp only in test and for filename matching
        // - Use arrays of absolute paths in include and exclude
        // - Try to avoid exclude and prefer include
        issuer: { test, include, exclude },

咱们的思路就变成通过webpack的exclude配置linterOption配置了,首先webpack不支持在exclude中添加Regex正则表达式,需要配置绝对路径,我们以linterOption中配置过滤css文件为例,通常css不需要tslint去检查。我们可以通过globby组件获取linterOption中定义的css正则,例如linterOption定义如下

"linterOptions":{
        "exclude": [
            "src/**/*.css"
        ]
},

然后再webpack中添加配置如下:

module: {
        rules: [{
        ...
        {
            test: /[\.ts|\.tsx]$/,
            loader: 'tslint-loader',
            enforce: "pre",
            options: {
                emitErrors: false
            },
            exclude: getTslintExclusions()
        }
        }]
}

下面看下getTslintExclusions方法的实现

const path = require('path');
const fs = require('fs');
const basePath = process.cwd();
const tslintPath = path.join(basePath, 'tslint.json');
const tslint = fs.existsSync(tslintPath)? require(tslintPath) : false;
const globby = require('globby');

function getTslintExclusions() {
    if(tslint && tslint.linterOptions && tslint.linterOptions.exclude) {
        let excludecss = globby.sync(tslint.linterOptions.exclude).map((file) => path.resolve(file));
        return excludecss;
    }
    return [];
}

配置完成之后,运行webpack build命令就可以在tslint中成功过滤css文件的检查了

写在最后,

虽然tslint已经逐渐被eslint组件代替,后续前端项目还是推荐使用tslint,在SharePoint Framework中还是使用了自定义的tslint,为了跟sharepoint framework保持一致的话,tslint还需要使用的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值