npm install --save-dev typescript ts-loader @types/react @types/react-dom
在项目根目录下创建 tsconfig.json文件,先写几个简单的配置选项
{
"compilerOptions": {
"module": "es6",
"target": "es5",
"jsx": "react",
"allowSyntheticDefaultImports": true
}
}
App.js修改为App.tsx,并修改其内容
import React from "react";
+ interface Props {
+ title: string
+ }
+ class App extends React.Component<Props> {
render() {
const { title } = this.props;
return (
<h1>hello { title }</h1>
)
}
}
export default App;
index.js修改为index.tsx,暂不修改内容。
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
+ entry: "./src/index.tsx", // 修改引用文件后缀
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
// 引入模块时不带扩展,尝试按顺序解析这些后缀名
+ resolve: {
+ extensions: [".tsx", ".ts", ".js"]
+ },
module: {
rules: [
{
test: /\.(js|jsx)/,
use: "babel-loader",
exclude: /node_modules/
},
// 将ts编译成js
+ {
+ test: /\.ts(x)?$/,
+ loader: "ts-loader",
+ exclude: /node_modules/
+ }
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html"
})
],
devServer: {
open: true,
}
};
“@types/react”: “^17.0.39”,
“@types/react-dom”: “^17.0.11”,
“ts-loader”: “^9.2.6”,
“typescript”: “^4.5.5”,