手动构建React工程项目(不借助脚手架)

1、初始化项目

 npm init -y

2、安装依赖

npm install react react-dom
npm install --save-dev typescript @types/react @types/react-dom webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env @babel/preset-react ts-loader

3、构建项目结构

在这里插入图片描述

4、内容开发

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ESNext",
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]

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: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: 'ts-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'public', 'index.html'), // 指向你的index.html模板
      filename: 'index.html', // 输出的html文件名
    }),
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'public'), // 这里可以保留,devServer会服务这个文件夹
    },
    compress: true,
    port: 3000,
  },
};

index.tsx:

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById('root')!);
root.render(<App />);

App.tsx:

import React from 'react';

export default function App() {
  return (
    <div>
      <h1>Hello, World!</h1>
    </div>
  );
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <script src="./bundle.js"></script>
</body>
</html>

package.json

package.json添加scripts指令

"scripts": {
    "start": "webpack serve --open",
    "build": "webpack --mode production"
  },

5、运行

运行项目npm run start
在这里插入图片描述
打包项目npm run build

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值