使用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:

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

2.安装和配置ts:

npm install -D typescript

 根目录新建tsconfig.json文件:

{
  "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:

npm install react react-dom

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

 npm install @types/react @types/react-dom

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

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:

npm i -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime @babel/runtime

根目录创建.babelrc.json:

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

6.安装webpack

 npm i -D webpack webpack-cli webpack-dev-server babel-loader html-webpack-plugin

7.配置webpack

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

npm i -D ts-node

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

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中追加启动脚本:

,
  "scripts": {
    "start": "webpack serve --config webpack.dev.config.ts"
  }

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

npm start

运行结果:

 源码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
搭建 React + TypeScript 项目的步骤如下: 1. 创建一个新的项目文件夹 ``` mkdir my-react-ts-app cd my-react-ts-app ``` 2. 初始化项目 ``` npm init -y ``` 3. 安装必要的依赖 ``` npm install --save react react-dom npm install --save-dev typescript @types/react @types/react-dom webpack webpack-cli webpack-dev-server awesome-typescript-loader html-webpack-plugin ``` 4. 创建一个 TypeScript 配置文件 ``` touch tsconfig.json ``` 5. 将以下内容添加到 tsconfig.json 文件中 ``` { "compilerOptions": { "outDir": "./dist/", "module": "es6", "target": "es5", "lib": ["es6", "dom"], "sourceMap": true, "jsx": "react", "moduleResolution": "node", "esModuleInterop": true }, "include": [ "./src/**/*" ] } ``` 6. 添加一个 index.html 文件到项目根目录 7. 添加以下内容到 index.html 文件中 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>My React TypeScript App</title> </head> <body> <div id="root"></div> </body> </html> ``` 8. 创建一个 src 目录 ``` mkdir src ``` 9. 在 src 目录中创建一个 App.tsx 文件 ``` touch src/App.tsx ``` 10. 将以下内容添加到 App.tsx 文件中 ```tsx import React from 'react'; const App = () => { return ( <div> <h1>Hello, World!</h1> </div> ); }; export default App; ``` 11. 在 src 目录中创建一个 index.tsx 文件 ``` touch src/index.tsx ``` 12. 将以下内容添加到 index.tsx 文件中 ```tsx import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root')); ``` 13. 在项目根目录中创建一个 webpack.config.js 文件 ``` touch webpack.config.js ``` 14. 将以下内容添加到 webpack.config.js 文件中 ```js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.tsx', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, module: { rules: [ { test: /\.tsx?$/, loader: 'awesome-typescript-loader', }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'index.html', }), ], devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 3000, }, }; ``` 15. 运行 npm start 启动项目 ``` npm start ``` 以上就是从零搭建一个 React + TypeScript 的完整项目的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值