在create-react-app中搭配tslint

创建React和TypeScript项目

现在创建React和TypeScript应用程序非常简单。在CRA 2.1 TypeScript之前,我们必须使用单独的脚本将TypeScript包含在我们的React应用程序中。从CRA 2.1开始,TypeScript支持就在框中。我们只需要安装npm 5.2或更高版本。

创建我们的项目

让我们在我们选择的文件夹中运行以下命令,我们要在其中创建项目:

1
npx create-react-app app --typescript
  • npx工具临时安装create-react-appnpm包并使用它来创建我们的项目。整齐!
  • 我们选择调用我们的项目应用程序
  • 我们还指定--typescript了一个位,告诉工具使用TypeScript设置项目。

该工具将花费一分钟左右来创建我们的项目。

添加TSLint

TSLint添加到React和TypeScript有助于我们使代码更具可读性和可维护性。遗憾的是,CRA在其设置中不包含此内容,因此,我们将通过在终端中运行以下命令来自行完成此操作:

1
2
3

cd app
npm install tslint tslint-react --save-dev

我们刚刚安装了TSLint作为开发依赖项以及React项目的一些标准linting规则。

让我们通过添加一个与以下内容tslint.json 相同级别调用的文件来配置TSLint package.json

1
2
3
4
5

{
"extends": ["tslint:latest", "tslint-react"],
"linterOptions": {"exclude": ["config/**/*.js", "node_modules/**/*.ts", "coverage/lcov-report/*.js"]}
}

如果我们希望随着TSLint的发展,linting规则更加稳定,我们可以使用tslint:recommended而不是tslint:latest。

我们可以通过添加字段来覆盖我们想要的特定规则rules

添加TSLint Visual Studio代码扩展

打字稿TSLint插件 VS代码扩展似乎是最流行的扩展,这些天。

img

安装此插件后,我们需要启用它tsconfig.json

1
2
3
4
5
6
7
8

{
"compilerOptions": {
...,
"plugins": [{"name": "typescript-tslint-plugin"}]
},
...
}

修复App.tsx中的linting错误

现在我们的应用程序正在使用TSLint,我们在App需要修复的组件中遇到了一个小问题。

CRA掉毛错误

我们需要在render方法中添加访问修饰符:

1
2
3
4
5
6

class App extends Component {
public render() {
return ( ... );
}
}

添加自动格式

一些与我们的代码格式有关的linting规则(例如语句末尾的半冒号)可以通过像Prettier这样的工具自动处理。

我们可以通过在终端中执行以下命令来安装Prettier:

1
npm install prettier --save-dev

为了让Prettier更好地使用TSLint,我们首先安装 tslint-config-prettier规则预设:

1
npm install tslint-config-prettier --save-dev

然后我们将其添加到tslint.json:

1
{  "extends": ["tslint:latest", "tslint-react", "tslint-config-prettier"],  "linterOptions": {"exclude": ["config//*.js", "node_modules//.ts", "coverage/lcov-report/.js"]}}

我们在.prettierrc文件中指定我们想要的格式规则,该文件位于以下相同的级别package.json:

1
{ "printWidth": 80, "singleQuote": true, "semi": true, "tabWidth": 2, "trailingComma": "all"}

添加更漂亮的Visual Studio代码扩展

更漂亮-代码格式化 VS代码扩展名是流行的扩展,这些天。

img

通过勾选“ 用户设置”中的“ 保存时格式”选项,我们可以让Prettier在Visual Studio代码中保存文件时应用格式:

img

运行应用程序

像往常一样,我们可以通过在终端中输入以下命令来运行应用程序:

npm start

CRA正在运行

就是这样 - 我们现在有一个带有TSLint和Prettier的React和TypeScript项目!

参考文档

-------------本文结束感谢您的阅读-------------

本文标题:在create-react-app中搭配tslint

文章作者:yangpu

发布时间:2019年04月24日 - 18:08

最后更新:2019年04月24日 - 18:08

原始链接:https://mongofeng.github.io/2019/04/24/create-react-app-tslint/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。