Home Web Front-end JS Tutorial Methods to build react project framework based on webpack4

Methods to build react project framework based on webpack4

Jun 30, 2018 pm 03:24 PM
webpack

This article mainly introduces the method of building a react project framework based on webpack4. The content is quite good. I will share it with you now and give it as a reference.

Introduction

Introduction to the framework, a react single-page application built using webpac, integrating antd. Use webpack-dev-server to start local services and add hot updates to facilitate development and debugging. Use bundle-loader for code cutting and lazy loading

Manually built, without using cli, a large number of comments are suitable for beginners to understand and learn webpack, and have an in-depth understanding of react projects

Start

##

 git clone https://gitee.com/wjj0720/react-demo.git
 cd react-demo
 yarn
 yarn start
Copy after login

##Package

yarn build
Copy after login

Directory structure


 +node_modules
 -src
  +asset
  +Layout
  +pages
  +redux
  +utils
  +app.js
  +index.html
  +index.js
 .babelrc 
 package.json 
 postcss.config.js
 webpack.config.js //webpack 配置
Copy after login

bundle-loader lazy loading usage


 // webpack.config.js 配置
 module: {
  rules: [
   {
    test: /\.bundle\.js$/,
    use: {
     loader: 'bundle-loader',
     options: {
      name: '[name]',
      lazy: true
     }
    }
   }
  ]
 }
 // 页面引入组件
 import Home from "bundle-loader?lazy&name=[name]!./Home";

 // 组件使用 因为组件懒加载 是通过异步的形式引入 所以不能再页面直接以标签的形式使用 需要做使用封装 
 import React, {Component} from 'react'
 import { withRouter } from 'react-router-dom'
 class LazyLoad extends Component {
  state = {
   LoadOver: null
  }
  componentWillMount() {
   this.props.Loading(c => {
    this.setState({
     LoadOver: withRouter(c.default)
    })
   })
  }
 
  render() {
   let {LoadOver} = this.state;
   return (
    LoadOver ? <LoadOver/> : <p>加载动画</p>
   )
  }
 }
 export default LazyLoad

 // 通过封装的懒加载组件过度 增加加载动画
 <LazyLoad Loading={Home} />
Copy after login

Routing configuration


The framework is divided according to modules, and there is route.js under the pages folder That is a module

 // 通过require.context读取模块下路由文件
 const files = require.context(&#39;./pages&#39;, true, /route\.js$/)
 let routers = files.keys().reduce((routers, route) => {
  let router = files(route).default
  return routers.concat(router)
 }, [])

 // 模块路由文件格式
 import User from "bundle-loader?lazy&name=[name]!./User";
 export default [
  {
   path: &#39;/user&#39;,
   component: User
  },
  {
   path: &#39;/user/:id&#39;,
   component: User
  }
 ]
Copy after login

redux usage introduction


##

 // ---------创建 --------
 // 为了不免action、reducer 在不同文件 来回切换 对象的形式创建

 // createReducer 将书写格式创建成rudex认识的reducer
 export function createReducer({state: initState, reducer}) {
  return (state = initState, action) => {
   return reducer.hasOwnProperty(action.type) ? reducer[action.type](state, action) : state
  }
 }

 // 创建页面级别的store
 const User_Info_fetch_Memo = &#39;User_Info_fetch_Memo&#39;
 const store = {
  // 初始化数据
  state: {
   memo: 9,
   test: 0
  },
  action: {
   async fetchMemo (params) {
    return {
     type: User_Info_fetch_Memo,
     callAPI: {url: &#39;http://stage-mapi.yimifudao.com/statistics/cc/kpi&#39;, params, config: {}},
     payload: params
    }
   },
   ...
  },
  reducer: {
   [User_Info_fetch_Memo] (prevState = {}, {payload}) {
    console.log(&#39;reducer--->&#39;,payload)
    return {
     ...prevState,
     memo: payload.memo
    }
   },
   ...
  }
 }

 export default createReducer(store)
 export const action = store.action

 // 最终在模块界别组合 [当然模块也有公共的数据(见Home模块下的demo写法)]
 import {combineReducers} from &#39;redux&#39;
 import info from &#39;./Info/store&#39;
 export default combineReducers({
  info,
  。。。
 })

 // 最终rudex文件夹下的store.js 会去取所有模块下的store.js 组成一个大的store也就是我们最终仓库

 // --------使用------
 // 首先在app.js中将store和app关联
 import { createStore } from &#39;redux&#39;
 import { Provider } from &#39;react-redux&#39;
 // reducer即我们最终
 import reducer from &#39;./redux/store.js&#39;
 // 用户异步action的中间件
 import middleware from &#39;./utils/middleware.js&#39;
 let store = createStore(reducer, middleware)
 <Provider store={store}>
  。。。
 </Provider>


 // 然后组件调用 只需要在组件导出时候 使用connent链接即可
 import React, {Component} from &#39;react&#39;
 import {connect} from &#39;react-redux&#39;
 // 从页面级别的store中导出action
 import {action} from &#39;./store&#39;

 class Demo extends Component {
  const handle = () => {
   // 触发action
   this.props.dispatch(action.fetchMemo({}))
  }
  render () {
   console.log(this.props.test)
   return <p onClick={this.handle}>ss</p>
  }
 }
 export default connect(state => ({
  test: state.user.memo.test
 }) )(demo)
Copy after login

About redux middleware


 // 与其说redux中间件不如说action中间件
 // 中间件执行时机 即每个action触发之前执行

 // 
 import { applyMiddleware } from &#39;redux&#39;
 import fetchProxy from &#39;./fetchProxy&#39;;

 // 中间件 是三个嵌套的函数 第一个入参为整个store 第二个为store.dispatch 第三个为本次触发的action 
 // 简单封装的中间件 没有对请求失败做过多处理 目的在与项错误处理机制给到页面处理
 const middleware = ({getState}) => next => async action => {
  // 此时的aciton还没有被执行 
  const {type, callAPI, payload} = await action
  // 没有异步请求直接返回action
  if (!callAPI) return next({type, payload})
  // 请求数据
  const res = await fetchProxy(callAPI)
  // 请求数据失败 提示
  if (res.status !== 200) return console.log(&#39;网络错误!&#39;)
  // 请求成功 返回data
  return next({type, payload: res.data})
 }
 export default applyMiddleware(middleware)
Copy after login

The above is the entire content of this article, I hope it will be useful for everyone’s learning Help, please pay attention to the PHP Chinese website for more related content!

Related recommendations:

About the three ways to create components in React and their differences


Webpack optimization configuration narrowed file search Introduction to the scope


The above is the detailed content of Methods to build react project framework based on webpack4. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VUE3 Getting Started Tutorial: Packaging and Building with Webpack VUE3 Getting Started Tutorial: Packaging and Building with Webpack Jun 15, 2023 pm 06:17 PM

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

What is the difference between vite and webpack What is the difference between vite and webpack Jan 11, 2023 pm 02:55 PM

Differences: 1. The startup speed of the webpack server is slower than that of Vite; because Vite does not require packaging when starting, there is no need to analyze module dependencies and compile, so the startup speed is very fast. 2. Vite hot update is faster than webpack; in terms of HRM of Vite, when the content of a certain module changes, just let the browser re-request the module. 3. Vite uses esbuild to pre-build dependencies, while webpack is based on node. 4. The ecology of Vite is not as good as webpack, and the loaders and plug-ins are not rich enough.

How to use PHP and webpack for modular development How to use PHP and webpack for modular development May 11, 2023 pm 03:52 PM

With the continuous development of web development technology, front-end and back-end separation and modular development have become a widespread trend. PHP is a commonly used back-end language. When doing modular development, we need to use some tools to manage and package modules. Webpack is a very easy-to-use modular packaging tool. This article will introduce how to use PHP and webpack for modular development. 1. What is modular development? Modular development refers to decomposing a program into different independent modules. Each module has its own function.

How does webpack convert es6 to es5 module? How does webpack convert es6 to es5 module? Oct 18, 2022 pm 03:48 PM

Configuration method: 1. Use the import method to put the ES6 code into the packaged js code file; 2. Use the npm tool to install the babel-loader tool, the syntax is "npm install -D babel-loader @babel/core @babel/preset- env"; 3. Create the configuration file ".babelrc" of the babel tool and set the transcoding rules; 4. Configure the packaging rules in the webpack.config.js file.

Use Spring Boot and Webpack to build front-end projects and plug-in systems Use Spring Boot and Webpack to build front-end projects and plug-in systems Jun 22, 2023 am 09:13 AM

As the complexity of modern web applications continues to increase, building excellent front-end engineering and plug-in systems has become increasingly important. With the popularity of Spring Boot and Webpack, they have become a perfect combination for building front-end projects and plug-in systems. SpringBoot is a Java framework that creates Java applications with minimal configuration requirements. It provides many useful features, such as automatic configuration, so that developers can build and deploy web applications faster and easier. W

What files can vue webpack package? What files can vue webpack package? Dec 20, 2022 pm 07:44 PM

In vue, webpack can package js, css, pictures, json and other files into appropriate formats for browser use; in webpack, js, css, pictures, json and other file types can be used as modules. Various module resources in webpack can be packaged and merged into one or more packages, and during the packaging process, the resources can be processed, such as compressing images, converting scss to css, converting ES6 syntax to ES5, etc., which can be recognized by HTML. file type.

What is Webpack? Detailed explanation of how it works? What is Webpack? Detailed explanation of how it works? Oct 13, 2022 pm 07:36 PM

Webpack is a module packaging tool. It creates modules for different dependencies and packages them all into manageable output files. This is especially useful for single-page applications (the de facto standard for web applications today).

An in-depth analysis of the packaging process and principles of webpack An in-depth analysis of the packaging process and principles of webpack Aug 09, 2022 pm 05:11 PM

How does Webpack implement packaging? The following article will give you an in-depth understanding of Webpack packaging principles. I hope it will be helpful to you!

See all articles