脚手架创建

通过脚手架创建 create-react-app hello-tsx --template typescript

自定义创建

目录结构

image.png

新建项目和安装包

  1. npm init -y // 生成package.json
  2. tsc --init // 生成tsconfig.json
  3. npm i react react-dom -S
  4. npm i @babel/core @babel/preset-env @babel/preset-react @types/react @types/react-dom babel-loader clean-webpack-plugin html-webpack-plugin ts-loader typescript webpack webpack-cli webpack-dev-server webpack-merge -D
Webpack相关 React相关 TypeScript相关 babel
webpack webpack-cli
webpack-dev-server
webpack-merge
clean-webpack-plugin
html-webpack-plugin
react
react-dom
@types/react
@types/react-dom
typescript
ts-loader
@babel/core @babel/preset-env
@babel/preset-react
babel-loader

准备基础的配置

package.json

  1. {
  2. "scripts": {
  3. "start": "webpack serve --config build/webpack.config.js"
  4. }
  5. }

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "jsx": "react",
  4. }
  5. }

.babelrc

  1. {
  2. "presets": [
  3. "@babel/preset-env",
  4. "@babel/preset-react"
  5. ]
  6. }

public/index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>TypeScript In Action</title>
  8. </head>
  9. <body>
  10. <div id="app"></div>
  11. </body>
  12. </html>

build/webpack.config.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. module.exports = {
  3. mode: 'development',
  4. devtool: 'cheap-module-source-map',
  5. entry: {
  6. app: './src/index.tsx',
  7. },
  8. output: {
  9. filename: '[name].[chunkhash:8].js',
  10. },
  11. resolve: {
  12. extensions: ['.js', '.ts', '.tsx'],
  13. },
  14. optimization: {
  15. splitChunks: {
  16. chunks: 'all',
  17. },
  18. },
  19. module: {
  20. rules: [
  21. {
  22. test: /\.tsx?$/i,
  23. use: ['babel-loader', 'ts-loader'],
  24. exclude: /node_modules/,
  25. },
  26. ],
  27. },
  28. plugins: [
  29. new HtmlWebpackPlugin({
  30. template: 'public/index.html',
  31. }),
  32. ],
  33. }

src/index.tsx

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import Hello from './components/hello';
  4. ReactDOM.render(<Hello name="yefei" />, document.getElementById('app'));

src/componetns/hello.tsx

  1. import React from 'react';
  2. interface Greeting {
  3. name: string
  4. }
  5. export default function Hello(props: Greeting) {
  6. return <div>hello {props.name}, welecome to use typescript</div>
  7. }