Author: a tuque warehouse: Github, Gitee Tuque community main station (first) : Tuque community blog: Digijin, Zhihu, MOC public number: Tuque community contact me: after paying attention to the public number can add Tuque sauce wechat oh original is not easy, ❤️ like + comment + collection ❤️ three, encourage the author to write a better tutorial

Welcome to TypeScript’s Getting Started to Practice series on Type is Justice:

  • Type is Justice: TypeScript from Getting Started to Practice (Prologue)
  • Type is Justice: TypeScript from Inception to Practice (PART 1)
  • Type is Justice: TypeScript from Getting Started to Practice, PART II

Ready to code

Because we need to cover TypeScript syntax in as complete and concise a way as possible, we need a proper hands-on project. This section explains how we prepared the initial TypeScript React project code. In the next section, we’ll really start explaining TypeScript syntax in conjunction with the React project code.

The source code for this article is available on Github or Gitee. If you think it is well written, please give Github or Gitee a thumbs up at ❤️ or ❤️

This tutorial is part of the React front End engineer’s learning path. Welcome to Star and encourage us to continue to create better tutorials

The premise condition

  1. To make sure you have Node.js installed, visit the official website to install: official website address.
  2. Make sure you know the basics of React development. The Tux community has a great tutorial to get you started with React.
  3. Make sure you have some command-line basics, including installing packages using Npm (node.js package management tool).

Initializing the application

The best way to initialize a React App is to use the Create React App scaffolding maintained by the React App. Open a terminal and run the following command to initialize a TypeScript version of the React App:

$ npx create-react-app typescript-tea --template typescript
Copy the code

After running the above command, there should be a series of output in the command line. Wait a few minutes, it will tell you that the initialization is complete, and provide the right command to help you start the project. We will enter the following command as prompted to start the project:

$ cd typescript-tea
$ npm start
Copy the code

After running the above command, the Webpack development server will be automatically opened and a browser window will be opened to show you the initial interface of your application by visiting http://localhost:3000/ :








Note For the rest of this article, we call TypeScript TS to simplify the language.

Introduce the ANTD component library

Actual combat driven technology learning can bring us a sense of achievement, convenient and easy to use package can speed up our development efficiency, good-looking interface can improve our aesthetic ability, relieve learning fatigue. In the course of this tutorial, we will use Ant Design’s React component library antD to assist our project writing, so that we can focus on the core knowledge of TS without being disturbed by complex interface language, and also make corresponding target functions.

Ant Design is an enterprise-level product Design system incubated by Ant Financial. It provides a complete definition of TS type, which makes it easy for us to use in TS projects. Version 4.0 has been released recently, aiming to create efficient and pleasant work experience. In addition, Ant Design’s surrounding ecology is also rich:

  • Including a new generation of data visualization solutions: AntV
  • Preact/React/React Native based UI component library: Ant Design Mobile
  • Out of the box midstage front-end/Design solution: Ant Design Pro
  • Illustration: Sea Hare
  • A Sketch tool set for designers to improve productivity: Kitchen

We plan to write a series of tutorials on Ant Design ecology to help you improve your Design and development efficiency. Stay tuned! ✌ ️

Install dependencies

Now that we’ve outlined the ANTD component library and its surroundings, let’s write code to introduce ANTD, open a command line, and enter the following command:

$ npm install antd
Copy the code

After installing the dependencies, you can use them in your project by running the command above, but for better custom styling and on-demand references to reduce the size of the packaged package, we need to do a little more customization. Open the command line and install the following dependencies in sequence:

$NPM install react-app-rewired customize-cra babel-plugin-import less [email protected]Copy the code

Note that the less-loader is 5.0.0 because the latest version may have problems. Thanks to @abysss

Note that we have a lot of packages installed above, let’s explain the meanings of each package in turn:

  • The react – app – rewired: Create React App (CRA) scaffolding configuration, such as Webpack, Babel, etc. CRA is a closed black box that does not allow developers to customize it directly, but sometimes we need to modify the configuration. For example, here you need to configure an on-demand reference to ANTD.
  • Customize-cra: A library for react-app-rewired crA since the release of 2.0 that facilitates customizing crA Webpack configurations and provides some out-of-the-box apis.
  • Babel-plugin-import: a Babel plug-in configured to allow developers to reference ANTD components on demand
  • Less and less-loader: Are the Webpack loaders we need for our theme to customize ANTD, since ANTD uses less as the styling language.

Finally, we installed an ICONS package split out in Ant Design 4.0, which can be used to refer to ICONS as needed to further reduce the final packaging volume, continuing with the following command line:

$ npm install @ant-design/icons
Copy the code

And you’re done! Now all our dependencies as well as the installation are complete. Then we need to rewrite CRA’s react-scripts build process and replace it with the react-app-rewired script we installed. When all dependencies are installed, And after replacing react-scripts with react-app-rewired, our package.json file should look like this:

// ...
  "version": "0.1.0 from"."private": true."dependencies": {
    "@ant-design/icons": "^ 4.0.2." "."@testing-library/jest-dom": "^ 4.2.4"."@testing-library/react": "^ 9.3.2." "."@testing-library/user-event": "^ 7.1.2." "."@types/jest": "^ 24.0.0"."@types/node": "^ 12.0.0"."@types/react": "^ 16.9.0"."@types/react-dom": "^ 16.9.0"."antd": "^ 4.0.0"."babel-plugin-import": "^ 1.13.0"."customize-cra": "^ 0.9.1"."less": "^ 3.11.1." "."less-loader": "^ 5.0.0"."react": "^ 16.13.0"."react-app-rewired": "^ 2.1.5"."react-dom": "^ 16.13.0"."react-scripts": "3.4.0"."typescript": "~ 3.7.2." "
  },
  "scripts": {
    "start": "react-app-rewired start"."build": "react-app-rewired build"."test": "react-app-rewired test"."eject": "react-scripts eject"
  },
  // ...
Copy the code

Modify the configuration

After installing the dependencies, we need to make sure that the configuration for rewriting the CRA process takes effect. We need to create config-overrides. Js file in the root directory according to the documentation of react-app-rewired and write the following contents in it:

const { override, fixBabelImports, addLessLoader } = require("customize-cra");
const darkThemeVars = require("antd/dist/dark-theme");

module.exports = override(
  fixBabelImports("import", {
    libraryName: "antd".libraryDirectory: "es".style: true
  }),
  addLessLoader({
    javascriptEnabled: true.modifyVars: {
      hack: `true; @import "The ${require.resolve(
        "antd/lib/style/color/colorPalette.less"
      )}"; `. darkThemeVars,"@primary-color": "#02b875"}}));Copy the code

As you can see, the above code mainly exports an object to modify the Webpack configuration, uses the Override API, receives two function calls to modify the configuration, fixBabelImports is used to configure the antD on demand reference, AddLessLoader is used to configure the antD theme. Here we use Dark Mode, which is new to Ant Design 4.0, and then set the theme color to the Community theme color: # 02B875, which represents the desired green color. 😆 Since then, we have introduced the ANTD component library, configured it on demand, configured the theme colors and used Ant Design’s latest Dark theme, Dark Mode.

Write initial code

Prepare the logic

Next, we will use ANTD to help us quickly write the to-do interface we are implementing. Open SRC/app.tsx and make the corresponding changes to the code as follows:

import React, { useState, useRef } from "react";
import {
  List,
  Avatar,
  Button,
  Typography,
  Form,
  Input,
  Select,
  DatePicker,
  Menu,
  Dropdown,
  Tabs
} from "antd";
import { DownOutlined } from "@ant-design/icons";

import "./App.css";
import logo from "./logo.svg";

const { Title } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const todoListData = [
  {
    content: "Tuq Community: A Great Free Tutorial.".user: "mRcfps".time: "19:34 on 2 March 2020".isCompleted: false
  },
  {
    content: "Tuq Community: A Great Free Tutorial.".user: "pftom".time: "19:34 on 2 March 2020".isCompleted: false
  },
  {
    content: "Tuq Community: A Great Free Tutorial.".user: "Holy".time: "19:34 on 2 March 2020".isCompleted: false
  },
  {
    content: "Tuq Community: A Great Free Tutorial.".user: "crxk".time: "19:34 on 2 March 2020".isCompleted: false
  },
  {
    content: "Tuq Community: A Great Free Tutorial.".user: "Pony".time: "19:34 on 2 March 2020".isCompleted: false}];const userList = [
  {
    id: "666666666".name: "The Tooquine Community".avatar: "https://avatars0.githubusercontent.com/u/39240800?s=60&v=4"
  },
  {
    id: "23410977".name: "mRcfps".avatar: "https://avatars0.githubusercontent.com/u/23410977?s=96&v=4"
  },
  {
    id: "25455350".name: "crxk".avatar: "https://avatars1.githubusercontent.com/u/25455350?s=96&v=4"
  },
  {
    id: "23410977".name: "pftom".avatar: "https://avatars0.githubusercontent.com/u/23410977?s=96&v=4"
  },
  {
    id: "58352313".name: "holy".avatar: "https://avatars0.githubusercontent.com/u/58352313?s=96&v=4"}];constMenu = (< menu > < menu. Item> Complete </ menu. Item> < menu. Item> Delete </ menu. Item> </ menu >); Const TodoInput = ({value = {}}) => {return (<div className=" TodoInput "> <Input type="text" placeholder=" /> <Select style={{ width: 80 }} size="small" defaultValue="666666666"> {userList.map(user => ( <Option value={user.id}>{user.name}</Option> ))} </Select> <DatePicker size="small" style={{ marginLeft: "16px", marginRight: "16px" }} /> </div> ); }; function TodoList() { return ( <List className="demo-loadmore-list" itemLayout="horizontal" dataSource={todoListData} RenderItem ={item => (< list. item actions={[<Dropdown overlay={menu}> <a key="list-loadmore-more"> action <DownOutlined /> </a> </Dropdown> ]} > <List.Item.Meta avatar={ <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /> } title={<a href="https://ant.design">{item.user}</a>} description={item.time} /> <div>{item.content}</div> </List.Item> )} /> ); } function App() { const callback = () => {}; const onFinish = () => {}; const ref = useRef(null); return ( <div className="App" ref={ref}> <div className="container header"> <img src={logo} alt="" /> <Title Level ={3}> </Title> </div> <div className="container"> <Form onFinish={onFinish}> < form. Item name="todo"> <TodoInput /> </ form. Item> </Form> </div> <div className="container"> <Tabs onChange={callback} type="card"> <TabPane TAB =" All" Key ="1"> <TodoList /> </TabPane> <TabPane TAB =" In progress "Key ="2"> <TodoList /> </TabPane> <TabPane TAB =" completed" key="3"> <TodoList /> </TabPane> </Tabs> </div> </div> ); } / /...Copy the code

The above code is mainly the preparation of a series of initial data, the use of ANTD components, and the general outline of how to write. There is no TS syntax involved yet, but this is the basis for us to start the project. Readers simply need to make a copy and put it into the SRC/app.tsx corresponding to their existing typescript-tea project.

Prepare style section

Now that we have the logic code in place, to make our final to-do list look nice and easy to work with, we need to add some styling to the project. Open SRC/app.css and modify the code as follows:

.App {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 60px;
}

.container {
  width: 600px;
}

.header {
  text-align: center;
  margin-bottom: 56px;
}

.header img {
  width: 160px;
  height: 160px;
  margin-bottom: 24px;
}

.todoInput {
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 40px;
  border: 1px solid # 434343;
}

.todoInput input {
  border: none;
}
Copy the code

If your server is still running at this point, you should see something like this:








  • A TS version of the React project is initialized using TypeScript scripts from CRA
  • The ANTD component library is installed and usedreact-app-rewiredReplace the defaultreact-scriptsTo complete the modification of CRA’s Webpack configuration so that we can get on-demand references and theme customization of ANTD components
  • The logical and style sections of the initial to-do code are prepared

We’ve covered a lot of TypeScript’s benefits and put a lot of ink into the initial code, so the readers who have to get to this point can’t wait to see what TS really looks like. Coming soon!

Want to learn more exciting practical skills tutorial? Come and visit the Tooquine community.

The source code for this article is available on Github or Gitee. If you think it is well written, please give Github or Gitee a thumbs up at ❤️ or ❤️