使用typescript开发react应用

初始化

mkdir project-dir
cd project-dir
yarn init -y

安装依赖

yarn add react react-dom
yarn add -D typescript @types/react @types/react-dom

配置tsconfig.json

npx tsc --init

将 compilerOptions 下的 jsx 项配置成 react

{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs",                     
    "jsx": "react",                    
    "strict": true,                           
    "esModuleInterop": true
  }
}

配置webpack文件

yarn add -D webpack webpack-cli html-webpack-plugin webpack-merge webpack-dev-server
yarn add -D awesome-typescript-loader source-map-loader

webpack.common.js

// webpack/webpack.common.js
const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const htmlTemplate = new HtmlWebpackPlugin({
  template: path.resolve(__dirname, '../index.html'),
})

const config = {
  entry: path.resolve(__dirname, '../src/index.tsx'),
  output: {
    path: path.resolve(__dirname, '../src', 'dist')
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"]
  },
  module: {
    rules: [
      { test: /.tsx?$/, loader: "awesome-typescript-loader" },
      { enforce: "pre", test: /.js$/, loader: "source-map-loader" }
    ]
  },
  plugins: [
    htmlTemplate,
  ]
}

module.exports = config;
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>typescript in react</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

webpack.dev.js

// webpack/webpack.dev.js
const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: path.join(__dirname, "../dist"),
    compress: true,
    port: 9000,
    open: true,
  }
})

开始玩吧

// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './hello';

ReactDOM.render(<Hello name={'Typescript'} />, document.getElementById('app'));

// src/hello.tsx
import React, { PureComponent } from 'react';

interface HelloProps {
  name: string;
}

export default class Hello extends PureComponent {
  constructor(public props: HelloProps) {
    super(props);
  }

  render() {
    const { name } = this.props;
    return (
      <h1>Hello {name}</h1>
    );
  }
}

项目地址

https://github.com/zheng-chuang/typescript-in-react

原文地址:https://www.cnblogs.com/zheng-chuang/p/9905854.html