webpack+react新建项目—— 使用typescript

公羊英达
2023-12-01

1,安装typescript相关依赖文件

npm install --save-dev typescript ts-loader @types/react @types/react-dom

2,创建tsconfig.json文件

在项目根目录下创建 tsconfig.json文件,先写几个简单的配置选项

{
  "compilerOptions": {
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowSyntheticDefaultImports": true
  }
}

3,重命名App.js和index.js文件并修改内容

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,暂不修改内容。

4,修改webpack.config.js内容

	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,
	  }
	};

package.json依赖

“@types/react”: “^17.0.39”,
“@types/react-dom”: “^17.0.11”,
“ts-loader”: “^9.2.6”,
“typescript”: “^4.5.5”,

 类似资料: