脚手架创建
通过脚手架创建 create-react-app hello-tsx --template typescript
。
自定义创建
目录结构
新建项目和安装包
npm init -y // 生成package.json
tsc --init // 生成tsconfig.json
npm i react react-dom -S
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
{
"scripts": {
"start": "webpack serve --config build/webpack.config.js"
}
}
tsconfig.json
{
"compilerOptions": {
"jsx": "react",
}
}
.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeScript In Action</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
build/webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
devtool: 'cheap-module-source-map',
entry: {
app: './src/index.tsx',
},
output: {
filename: '[name].[chunkhash:8].js',
},
resolve: {
extensions: ['.js', '.ts', '.tsx'],
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
module: {
rules: [
{
test: /\.tsx?$/i,
use: ['babel-loader', 'ts-loader'],
exclude: /node_modules/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
],
}
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './components/hello';
ReactDOM.render(<Hello name="yefei" />, document.getElementById('app'));
src/componetns/hello.tsx
import React from 'react';
interface Greeting {
name: string
}
export default function Hello(props: Greeting) {
return <div>hello {props.name}, welecome to use typescript</div>
}