Learn to write React components in TypeScript

In order to toss around, I simply learned the next TypeScript, and it really feels good. In order to keep learning and avoid falling behind, we have to toss and turn.

Some time ago, I wrote some demo s with ES6, antd+dva, and found that antd is implemented with TypeScript, and Angular 2 also uses TypeScript. Since so many projects use TypeScript ahead of time, and I'm a fan of React, it's better to study the implementation of React components with TypeScript first.

In view of the beginning, it's better to stand on someone else's shoulder and start.

Tool selection

I know a little about the configuration of webpack, but I don't want to go deep into the engineering research for the time being. So I choose open source tools, atool-build and roadhog, which are used by Ali. Roadhog, because it is really simple and easy to configure.

However, use roadhog version 0.6.0-beta2 (because previous versions do not support TypeScript):

npm install roadhog@0.6.0-beta2 --save-dev

Configuration file:

//.roadhogrc
{
  "entry": "src/index.js",
  "publicPath": "/dist/",
  "outputPath": "./dist",
  "env": {
    "development": {
      "extraBabelPlugins": [
        "dva-hmr",
        "transform-runtime"
      ]
    },
    "production": {
      "extraBabelPlugins": [
        "transform-runtime",
        ["import", { "libraryName": "antd", "style": "css" }] // By adding this item, the import antd style will not be md5
      ]
    }
  }
}

Project structure

+------- src
         +----- components
         +----- models
         +----- routes
+------- .roadhog
+------- node_modules
+------- package.json
+------- ...

The project structure is basically consistent with that of antd-admin.

Entry file

// index.js
import './index.html'
import 'babel-polyfill'
import dva, { connect } from 'dva'
import createLoading from 'dva-loading'
import { browserHistory, Router, Route } from 'dva/router'

/**
 * @desc Here's how to deploy subdirectories under domain names
 * There are usually many sub-projects under the domain name project, so the role of sub-directories is crucial when deploying.
 * It's not easy to implement without basename.
 */
import { useRouterHistory } from 'dva/router'
import createBrowserHistory from 'history/lib/createBrowserHistory'

const history = useRouterHistory(createBrowserHistory)({basename: '/mda'})

// 1. Initialize
const app = dva({
  ...createLoading(),
//  history: browserHistory,
  history,
  onError (error) {
    console.error('app onError -- ', error)
  },
})

// 2. Model
app.model(require('./models/app'))


// 3. Router
app.router(require('./router'))

// 4. Start
app.start('#root')

Application Module (src/routes/app.js)

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'


import {
  Icon,
  Row,
  Col,
  Button,
  Modal,
} from '../components'
import 'antd/dist/antd.css'
import styles from './app.less'

function App ({ children, location, dispatch, app, loading }) {
  const {
    isVisible,
  } = app

  const showModal = () => {
    dispatch({
      type: 'app/showModal',
    })
  }

  const handleOk = () => {
  }

  const handleCancel = () => {
    dispatch({
      type: 'app/hideModal',
    })
  }
  return (
    <div className={styles.normal}>
      <Row>This is a row</Row>
      <Row>
        <Col span={12}>This is one Col</Col>
        <Col span={12}>This is one Col</Col>
      </Row>
      <Button type="primary" onClick={showModal}><Icon type="link" />Popup</Button>
      <Modal title="Bullet window title" visible={isVisible} onOk={handleOk} onCancel={handleCancel}>
        <div>Hello</div>
      </Modal>
    </div>
  )
}

App.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.bool,
}

export default connect(({ app, loading }) => ({ app, loading: loading.models.app }))(App)

assembly

Components are located in src/components. When you start learning, you can copy code directly from ant-design source code components. For simple components such as Button, Grid, Icon, you can copy it and run directly, but pay attention to installing the necessary packages.

Basic dependency packages

{
    "@types/react": "^15.0.22",
    "@types/react-dom": "^0.14.23",
    "antd": "^2.9.1",
    "classnames": "^2.2.5",
    "dva": "^1.2.1",
    "dva-loading": "^0.2.1",
    "object-assign": "^4.1.1",
    "omit.js": "^0.1.0",
    "prop-types": "^15.5.8",
    "rc-animate": "^2.3.6",
    "rc-dialog": "^6.5.8",
    "rc-util": "^4.0.2",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
}

summary

With tools and projects built, you can comfortably learn TypeScript to develop React components. Since I am also learning, there is still too much work to do. Hope that aspiring students can study and discuss together.

Here are some pits:

  • roadhog seems to be associated with dva, without careful study, without routing configuration, the program can not run, let's configure a simple routing first, let the application run.

  • You need to install @types/react, @types/react-dom, although you don't know the exact principle yet.

  • You need to configure tsconfig.json in the root directory, otherwise you won't be able to run.

  • Typeings directory is not used for the time being, to be learned

  • When migrating modal modules, errors are always reported, and the final solution is Solving the problem of modal onClose assignment error

Here are the relevant commands

  • Development: npm run server

  • Construction: npm run build

source code

Keywords: Javascript React TypeScript npm JSON

Added by XxDeadmanxX on Mon, 08 Jul 2019 04:53:26 +0300