深入浅出TypeScript(5)- 在React项目中使用TypeScript
前言
在第二小节中,我们讨论了利用TypeScript创建Web项目的实现,在本下节,我们讨论一下如何结合React创建一个具备TypeScript类型的应用项目。
准备
Webpack配置在第二小节项目的基础上做了一些修改,
添加React相关依赖:react、react-dom、@types/react 和@types/react-dom
修改Webpack配置文件
修改webpack.base.config.js,其余文件和第二小节保持一致,修改如下:
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
'app': './src/index.tsx'
},
output: {
filename: '[name].[chunkhash:8].js'
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
},
module: {
rules: [
{
test: /\.tsx?$/i,
use: [{
loader: 'ts-loader'
}],
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
optimization: { // 拆包
splitChunks: {
chunks: 'all'
}
}
}
我们把入口设置为index.tsx这是我们的React入口组件。
更改index组件
我们将第二小节中的index.ts修改如下:
// const hello: string = 'Hello TypeScripy'
// document.querySelectorAll('.app')[0].innerHTML = hello
import React from 'react'
import ReactDom from 'react-dom'
import Hello from './Hello'
ReactDom.render(
<Hello name='Type'/>,
document.querySelectorAll('.app')[0]
)
Hello组件
import React from 'react'
interface Greeting {
name: string
} // 使用接口来限定props的类型
const Hello = (props: Greeting) => <div>Hello {props.name}</div>
export default Hello
修改tsconfig.js文件
支持编译选项修改为 jsx: “react”
运行项目
npm start可以看到自己的项目已经运行起来。
项目的github地址: https://github.com/qixingduanyan/ts-react
大家可以自己配置Redux、Router以及异步请求中间件,比如redux-saga、redux-thunk
我自己也配置了一个简易的异步请求脚手架: https://github.com/qixingduanyan/typescript-react-app
总结
这篇文章主要是探讨React项目中使用TypeScript的方式,首先学以致用,才能去探究其中的原理。
如果你想要用TypeScript来做项目,那么这5小节应该可以使你写出比较标准的tsx代码,也应该明白了TypeScript的用法是什么。
Very well voiced genuinely. . cialis without a doctor prescription
Nicely put, Cheers! tretinoin cream 025
You actually expressed it really well! Valsartan Hydrochlorothiazide Composition
Thanks a lot! Awesome information! Does Provigil Lose Its Effectiveness
Regards, Loads of tips.
trazodone 50 mg tablet
You definitely made your point! Lexapro Makes Me Hot
Nicely put, With thanks. cannaxl hemp oil softgel
Cheers, I like this! Hydrochlorothiazide Drug
Fine info. Many thanks! viagra cheap
Kudos. Valuable information! celexa for anxiety