使用webpack建立React+TS项目

之前写过类似的文章,这次看到一本新书里也介绍了这个知识点,故尝试之。

Refer: 《Learn React With TypeScript - A Beginner's Guide To Reactive Web Development With React 18 and TypeScript》chapter3 Creating a project with webpack

1.先建立一个空的文件夹,my-app,并用vscode打开然后到根目录底下创建package.json和src目录,并在其中添加index.html:

javascript 复制代码
{
  "name": "my-app",
  "version": "1.0.0",
  "description": "My React and TypeScript app"
}
html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>My app</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>

2.安装和配置ts:

bash 复制代码
npm install -D typescript

根目录新建tsconfig.json文件:

javascript 复制代码
{
  "compilerOptions": {
    "noEmit": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "jsx": "react",
    "forceConsistentCasingInFileNames": true,
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

3.安装React:

bash 复制代码
npm install react react-dom

安装类型(react包本身不含类型):

bash 复制代码
 npm install @types/react @types/react-dom

4.在src目录地下创建index.tsx:

TypeScript 复制代码
import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root") as HTMLElement);

function App() {
  return <h1>My React and TypeScript App!</h1>;
}

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

5.安装Babel:

bash 复制代码
npm i -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime @babel/runtime

根目录创建.babelrc.json:

javascript 复制代码
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

6.安装webpack

bash 复制代码
 npm i -D webpack webpack-cli webpack-dev-server babel-loader html-webpack-plugin

7.配置webpack

a.安装node-ts库允许在ts文件中配置:

bash 复制代码
npm i -D ts-node

b.根目录上创建一个文件webpack.dev.config.ts:

TypeScript 复制代码
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import {
  Configuration as WebpackConfig,
  HotModuleReplacementPlugin,
} from "webpack";
import { Configuration as WebpackDevServerConfig } from "webpack-dev-server";

type Configuration = WebpackConfig & {
  devServer?: WebpackDevServerConfig;
};

const config: Configuration = {
  mode: "development",
  output: {
    publicPath: "/",
  },
  entry: "./src/index.tsx",
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/i,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              "@babel/preset-env",
              "@babel/preset-react",
              "@babel/preset-typescript",
            ],
          },
        },
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html",
    }),
    new HotModuleReplacementPlugin(),
  ],
  devtool: "inline-source-map",
  devServer: {
    static: path.join(__dirname, "dist"),
    historyApiFallback: true,
    port: 4000,
    open: true,
    hot: true,
  },
};

export default config;

c.在package.json中追加启动脚本:

javascript 复制代码
,
  "scripts": {
    "start": "webpack serve --config webpack.dev.config.ts"
  }

8.允许app,命令行使用:

bash 复制代码
npm start

运行结果:

源码

相关推荐
黄尚圈圈24 分钟前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水1 小时前
简洁之道 - React Hook Form
前端
正小安3 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光5 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   5 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   5 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web5 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常5 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇6 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器