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还需要使用的。