current position:Home>Study together to build the react + webpack + ts framework!!!!!!(a)

Study together to build the react + webpack + ts framework!!!!!!(a)

2022-08-06 18:14:04Mary

React项目框架搭建

相信我,Xiaobai step by step,learn to frame,The focus is on programming ideas!!!4D675E11.jpg

前言

起初,Mainly want to learn more systematicallyreact,Then start to build the project framework intermittently,The process lasts longer,It's learning and practicing,然后!!!After a period of time before learning, nullify the knowledge points,Forget it again,So I had to sort out the documentation..Huge trouble writing documentation!brain hurts brain hurts

前置项

react:react18
打包工具:webpack5
路由:[email protected]
UI:antd4.21.7
语言:typescript
node: node14
axios The libraries currently used are all current最新版本


ready to recreate a new project step by step rebuild again and record!!!
4A067AD0.jpg

  1. 首先,初始化一个新项目(No scaffolding or anything)
1.创建一个文件夹 react-demo
2.进行初始化
npm init / yarn init
一路点击回车,自动生成一个package.json文件
复制代码

step by step,Hurry up,Make up for what's missing~

  1. 修改package.json
// scriptsAdd local run command in
scripts: {
  "dev": "webpack"
}
// 执行npm命令运行项目
npm run dev
复制代码

Then you will find the error,识别不了webpack

image.png

  1. 装webpack相关依赖

接下来,安装下webpack即可 注意:安装依赖时,differentiated bydevDependencies还是dependencie,保持良好的习惯

npm i webpack -D
复制代码

继续运行,It will report an error and prompt to installwebpack-cli(No picture posted here~)

接着运行,Report not found from config filemode等属性,Then you need to create in the root directorywebpack.config.jsLet's start configuring

image.png

webpack.config.js基础配置

const path = require('path')
module.exports = {
    mode: "development", // 默认开发环境
    entry: path.resolve(__dirname, './src/index.tsx'), // 入口文件\
    // 打包出口文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'js/[name].[contenthash:8].bundle.js',
        // webpack5支持clean属性配置 No need to depend on otherplugin配置
        clean: true, // clear the previousbundle 
    }
}
复制代码

Simply configure the entry fileindex.tsxand export directorydist即可,运行npm run dev就可以打包了

image.png

思考一下,How can I display the content in the browser??Do we need to have ahtml文件,Then if you write all the code is mounted to thehtml上,Does this satisfy the need?

All the code is not generated after packagingdist/js/file below,Then we directly pass this file throughscript标签引入到html文件不就行了吗

// index.tsx
console.log('react项目框架搭建')

// public/index.html
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src='../dist/js/main.f8fffaee.bundle.js'></script>
</head>
复制代码

浏览器打开html文件,运行成功

image.png

再接再厉!We don't want to manually import every timebundle.js,I want it to run normally locally and to be able to convert the generated package自动挂载html上!!!Then you need to configure somewebpack-dev-server相关的

  • Change it a littlepackage.json中的scripts
"scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
复制代码
  • 然后就直接运行npm run dev,Follow the error message according to the previous idea,安装webpack-dev-server
npm i webpack-dev-server -D
复制代码
  • npm run devcan run normally 默认的端口号是8080
devServer: {
    port: 9090, // The port number here can be defined by yourself 默认8080
    hot: true // 本地开发热更新 Automatically recompile after code changes
}
复制代码
  • 跑是跑起来了,But can't see anything,Next, we're going to show some content.~
    • 创建一个html文件 这里我在根目录下创建了一个public目录,public下创建index.html;
    <body>
        <!-- for mounting content -->
        <div id="app"></div>
    </body>
    复制代码
    • webpack配置,将bundle.js自动挂载到html文件,这就需要安装HtmlWebpackPlugin
    npm i html-webpack-plugin -D
    // webpack.config.js
    复制代码
    • webpack.config.js
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    module.exports = {
        plugins: [
            // 将bundle.js自动挂载到index.html
            new HtmlWebpackPlugin({
                template: path.resolve(__dirname, './public/index.html'), // template file to mount
                filename: 'index.html',
            })
        ]
    }
    复制代码
    • Then run it directly locally,print statement output normally,说明配置正常,可以自动将bundle.js挂载到html上了(404Ignore mistakes,just not providedico图标而已~)

      image.png

  1. 接下来 要考虑ts的相关配置了 image.png 随便写一个ts的语法,就会发现报错,原因是未安装typescript,and does not provide the correspondingloaderto process this type of file
npm i typescript -D
npm i ts-loader -D // It will be replaced with a more powerfulbabelto do analysis
复制代码

然后配置下.tsx的解析规则,让它使用ts-loader去处理

// webpack.config.js
module: {
  rules: [
      {
          test: /\.(tsx?|js)$/,
          use: 'ts-loader',
          include: /src/, 
      }
  ]
},
复制代码

继续运行,Prompt to createtsconfig.json文件

image.png According to the prompt created under the root directorytsconfig.json

{
    "compilerOptions": {
        "jsx": "react", // 在.tsx文件中支持jsx
        "target": "es6",
        "rootDir": "./src",
        "outDir": "./dist",
        "module": "ESNext",
        "sourceMap": true,
        "strictNullChecks": true,
        "declaration": true, // 生成相应的.d.ts文件
        "allowJs": true,
        "checkJs": true,
        "moduleResolution": "Node", // 将模块解析模式设置为node.js解析模式
        "allowSyntheticDefaultImports": true // Allows you to do not contain the default export module USES the default export
    },
    "include": ["./src/**/*"],
    // 不进行类型检查的文件
    "exclude": ["node_modules", "dist"]
}
复制代码

这样,就能正常解析ts文件啦~

  1. 接下来就进行react相关配置

    • 安装react相关
    npm i -D react react-dom @types/react @types/react-dom
    复制代码

    安装完之后,Modify the entry fileindex.tsx测试下~

    import { createRoot } from 'react-dom/client'
    import * as React from 'react'
    
    const container = document.getElementById('app')
    const root = createRoot(container as Element)
    
    root.render(
        <div>欢迎来到react!</div>
    )
    复制代码

    效果如下:

    image.png

  2. 配置css样式相关

    // webpack.config.js
    rules: [
        {
            test: /\.css$/,
            include: [/node_modules/],
            // css-loader对cssFile merging processing, etc 
            // style-loaderfor processingcss文件以styleembedded in the form of tagshtml页面中
            use: ['style-loader', 'css-loader'],
        },
    ]
    复制代码

    如果我们采用style-loaderEmbed styles directly intohtml中,如果存在大量的css文件,This way will lead tohtmlThe page is particularly bloated and cluttered,It is not easy to debug in production environment, etc.

    可以采用MiniCssExtractPlugin插件,拆分cssand outreach willcss文件引入到html中(For local environmentstyle-loader也可),Itself, this is just a optimization~

    // 安装MiniCssExtractPlugin插件
    // webpack.config.js改一下loader即可
    {
        test: /\.css$/,
        include: [/node_modules/],
        // css-loader对cssFile merging processing, etc 
        // style-loaderfor processingcss文件以styleembedded in the form of tagshtml页面中
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
    }
    // 同时在plugin中添加MiniCssExtractPlugin配置
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'css/[name].css', // filenamePackaged is synchronous code
            chunkFilename: '[id].css', // 异步代码
        }),
    ],
    // 不使用style-loader的话,可以顺手uninstall一下
    复制代码

    创建一个global.css 测试下~

    image.png

待续~

  • 完成以上步骤,一个小的react项目框架就搭建完成了
  • 后续会进行css模块化、react-router、antd、axios二次封装、以及eslint、prettierCode specification configuration, etc.

github链接: https://github.com/yll916/react-demo

copyright notice
author[Mary],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/218/202208061755239495.html

Random recommended