Starting with React Native 0.57, we can finally develop directly in TypeScript without any additional configuration. This article focuses on how to use TypeScript to gracefully develop React Native applications.
1. Initialize the project
Before initializing the project, please ensure that the environment setup has been completed according to the React Native Chinese Development environment setup document
$ react-native init AwesomeProject
Copy the code
Note: the entry file index.js needs to be preserved, and all other files can use the.ts or.tsx suffix.
The TypeScript compiler
$ yarn global add typescript
$ yarn add -D typescript @types/react @types/react-native
Copy the code
Configure tsconfig.json
$ tsc --init --pretty --target esnext --allowJs --checkJs --jsx react-native --allowSyntheticDefaultImports --experimentalDecorators --emitDecoratorMetadata
Copy the code
Note: Note that redundant comments may be incompatible and need to be removed, as detailed documentation can be found in the compilation options.
The configuration file
tsconfig.json
{
"compilerOptions": {
"target": "esnext"."module": "commonjs"."allowJs": true."checkJs": true."jsx": "react-native"."strict": true."allowSyntheticDefaultImports": true."esModuleInterop": true."experimentalDecorators": true."emitDecoratorMetadata": true
},
"exclude": ["node_modules"."**/*.js"]."compileOnSave": false
}
Copy the code
Explanation:
target
: Specifies the ECMAScript target version “ES3” (default), “ES5”, “ES6″/”ES2015”, “ES2016”, “ES2017”, “ES2018”, “ES2019” or “ESNext”.mode
: Specifies which module System code to generate: “None”, “CommonJS”, “AMD”, “System”, “UMD”, “ES6”, “ES2015”, or “ESNext”.allowJs
: Allows the compilation of javascript files.checkJs
In:.js
Error reported in file. with--allowJs
Use together.jsx
Support JSX in.tsx files: “react”, “react-native” or “preserve” To viewJSX.strict
: Enables all strict type checking options. To enable the--strict
Equivalent to enabling--noImplicitAny
.--noImplicitThis
.--alwaysStrict
.--strictNullChecks
和--strictFunctionTypes
和--strictPropertyInitialization
.allowSyntheticDefaultImports
: Allows default import from modules that do not have default export Settings. This does not affect the output of the code, just for type checking.esModuleInterop
TypeScript takes a different approach to Babel, and until now, there has been no real fixed standard. Simply put, iF you’re using Babel, Webpack, or React Native and expect a different import behavior than what you’re used to, TypeScript provides this compilation option.experimentalDecorators
: Enables the experimental ES decorator.Add design type metadata to decorator declarations in the source code.
Adds design type metadata to decorator declarations in source code.
EsLint code detection
The Lint tool is used to check that code is syntactically correct and stylistically correct. The latest tools, ESLint, not only allow you to customize grammar rules, but also allow users to create plugins that change the default JavaScript syntax, such as those that support ES6 and JSX.
VsCode support
Install ESLint Plugin
Configuration ESLint Plugin
{
"eslint.validate": [
"javascript"."javascriptreact",
{
"language": "typescript"."autoFix": true
},
{
"language": "typescriptreact"."autoFix": true
},
{
"language": "vue"."autoFix": true
},
{
"language": "html"."autoFix": true}]."eslint.autoFixOnSave": true
}
Copy the code
eslint.validate
: The ESLint plugin only validates javascript and javascriptreact by default, so you need to manually enable validation support for other languageseslint.autoFixOnSave
: Automatically fixes errors when saving is enabled
Project configuration
Note: Before configuration, make sure that.eslintrc.js exists in the root directory. To specify files to be ignored, use the.eslintignore file (node_modules, bower_compnents folders are already ignored by default).
$ yarn add -D eslint eslint-config-airbnb eslint-plugin-jsx-a11y eslint-plugin-import eslint-plugin-react eslint-plugin-react-native @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-import-resolver-typescript
Copy the code
- Eslint: assembles JavaScript and JSX checking tools
- eslint-config-airbnb: This package is provided for Airbnb
.eslintrc
As an extensible shared configuration - Eslint-plugin-jsx-a11y: Static AST checker for accessibility rules for JSX elements.
- Eslint-plugin-import: This plugin is designed to support linting for ES2015 + (ES6 +) import/export syntax.
- Eslint-plugin-react: eslint react validation rules plugin
- Eslint-plugin-react-native: React Native specific linting rules for ESLint
- @typescript-eslint/parser: Convert typescript to ESTree so esLint can recognize it
- @typescript-eslint/eslint-plugin: a plugin that contains a bunch of eslint rules specific to typescript
- Eslint-import-resolver -typescript: Adds plugins supported by typescript to eslint-plugin-import
The configuration file
.eslintrc.js:
Because the file is too long, it will not be shown here, please stamp the specific configuration
.eslintignore:
# /node_modules/* and /bower_components/* ignored by default
Copy the code
5. Format the Prettier code
ESLint can detect potential problems in code and improve code quality, but it doesn’t completely unify code styles. Prettier, on the other hand, has the advantage of formatting code. Prettier scans for style problems in files and automatically reformats the code to ensure that indentation, spacing, semicolons, single and double quotes, and so on follow consistent rules.
VsCode support
If you just want to format your JS or TS code, you can ignore this section
Install the Prettier Plugin
Configuration Prettier Plugin
Note: In addition to the configuration below, it is recommended that you uninstall beautify directly and configure prettier as the default formatter for prettier.
prettier.requireConfig
: An prettier file must exist in the project to run prettiereditor.formatOnSave
: Enable automatic formatting when saving
{
"prettier.requireConfig": true."editor.formatOnSave": true
}
Copy the code
Configuration rules:
Prettier is used with ESLint
13, an PrettierConfig file for Prettier You can use an Prettier file for Prettier. But the editor doesn’t tell you when there’s a problem with the style. To make matters worse, ESLint and Prettier have some conflicts over formatting rules. Fortunately, Prettier is designed to be easy to integrate with ESLint, so you can easily use both in projects without worrying about conflicts.
$ yarn add prettier eslint-config-prettier eslint-plugin-prettier -D
Copy the code
- Prettier: master prettier library
- Eslint-config-prettier: Disables all unnecessary ESLint rules or rules that may conflict with prettier rules for prettier.
- Eslint-plugin-prettier: runs prettier as an ESLint plug-in
The configuration file
.eslintrc.js:
module.exports = {
extends: [
+ 'plugin:prettier/recommended',
+ 'prettier/react',
+ 'prettier/@typescript-eslint',
+ 'prettier',],}Copy the code
.eslintignore:
# /node_modules/* and /bower_components/* ignored by default
Copy the code
.prettierrc.js
module.exports = {
semi: false.// Whether to use a semicolon for the line bit. Default is true
trailingComma: 'es5'.Tail / / whether or not to use commas, there are three optional value "< none | es5 | all >"
singleQuote: true.// Whether to use single quotes for the string. The default is false and double quotes are used
printWidth: 120.// The number of characters in a line. If the number exceeds the number of characters in a line, the line will be newed. default is 80
tabWidth: 2.// A TAB represents a number of Spaces
bracketSpacing: true.{foo: bar}
}
Copy the code
.prettierinore
**/node_modules/*
Copy the code
6. EditorConfig is configured uniformly across editors
When many people are working on a project together, it is often the case that they use different editors. As far as front-end developers are concerned, some people like Sublime, some people like Webstorm, some people like Atom, some people like Vim, HBuilder, etc. Developers of different programming languages like different editors. The EditorConfig project is designed to solve the problem of code style uniformity across editor development projects.
VSCode Plugin
After the installation, you do not need to configure the configuration file.
The configuration file
.editorconfig:
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.gradle]
indent_size = 4
[BUCK]
indent_size = 4
Copy the code
Git pre-commit Hook
The pre-commit hook runs before the commit information is typed. It is used to check for snapshots that are about to be committed, for example, to see if anything is missing, to ensure that tests are running, and to verify code. If the hook exits with a non-zero value, Git will abandon the commit, but you can get around this by using Git commit –no-verify. You can use this hook to check whether the code style is consistent (running a program like Lint), whether trailing whitespace characters are present (the built-in hook does that), or whether the new method is properly documented.
Husky: Use Git hooks easily
Husky can prevent bad Git commit, Git push and more 💩
$ yarn add -D husky
Copy the code
The configuration file
.huskyrc.js:
module.exports = {
hooks: {
'pre-commit': 'node node_modules/eslint/bin/eslint.js --fix src/**/*.js',}}Copy the code
Note: The test found that running ESLint –fix directly uses global modules.
Use only Husky questions
- Performance issues: Running a Lint process on an entire project is slow, and linting results may not matter.
- Efficiency issues: Students working on legacy repositories can quickly encounter new problems, and in the early days of starting Lint, you may face thousands of Lint errors that need to be fixed. Some of you may be familiar with the following picture: Only file A is changed, but there are also A lot of errors in files B, C, and D.
Lint-staged: Husky’s good helper
Run linters on your temporary Git files and don’t let 💩 slide into your code base! For those unfamiliar with the concept of staging areas, check out Git – A Concise Guide
$ yarn add -D husky lint-staged
Copy the code
- Husky: Used to add some Git hooks, we need one here
pre-commit
In every timegit commit
Execution at operation timelint-staged
Command. - Lint-staged: You can perform operations on Git staging files (i.e. files you want to commit) to improve both performance and efficiency.
The configuration file
.huskyrc.js:
module.exports = {
hooks: {
'pre-commit': 'lint-staged'.'**/*.{md,json}': ['prettier --write'.'git add',}}Copy the code
lint-staged.config.js:
module.exports = {
'src/**/*.{js,jsx,ts,tsx}': ['eslint --fix'.'git add'],}Copy the code
Import components relative to the root directory
This part is not required and is a bit cumbersome to configure. Here I will only introduce the simple configuration, please refer to the detailed documentation babel-plugin-root-import.
$ yarn add -D babel-plugin-root-import eslint-import-resolver-babel-plugin-root-import
Copy the code
The configuration file
babel.config.js:
module.exports = {
...
plugins: [
[
'babel-plugin-root-import',
{
rootPathSuffix: 'src'.rootPathPrefix: '~'},],]... }Copy the code
.eslintrc.js
{
settings: {
'import/resolver': {
'babel-plugin-root-import': {
rootPathSuffix: 'src'.rootPathPrefix: '~'},},},},}Copy the code
tsconfig.json:
{
"compilerOptions": {
"baseUrl": "."."paths": {
"~ / *": ["src/*"]}}}Copy the code
Support. JSX
React Native already has Built-in support for TypeScript, but does not support the.jsx file suffix. If you want to use.jsx development, you can configure metro.config.js:
module.exports = {
resolver: {
sourceExts: ['ts'.'tsx'.'js'.'jsx'.'json'.'mjs',}}Copy the code
X. Relevant information
- Using ESLint and Prettier in a TypeScript Project: TypeScript, ESLint, Prettier, VSCode
- ESLint + Prettier simplifies code Review: Zeit Now, DevOps
- Use Prettier and ESlint to commit code uniformly: ESlint, Prettier, husky, Lint-Staged
- Write high-quality code with ESLint and Prettier: ESLint, Prettier, husky, Lint-Staged
- Use ESLint+Prettier to unify front-end code styles: ESLint, Prettier
- Use ESLint & Prettier to prettify Vue code: Vue, ESLint, Prettier, husky, Lint-staged, pit
- Building super-slick code checking workflows with Husky and Lint-Staged: Husky, Lint-Staged