Home  >  Article  >  Web Front-end  >  Another solution for lazy loading implementation of React routing (code)

Another solution for lazy loading implementation of React routing (code)

不言
不言forward
2018-10-23 15:30:323829browse

The content of this article is about another solution (code) for lazy loading implementation of React routing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article briefly introduces several implementation solutions for lazy loading of routes in React.

Traditional two ways

import()

Conforms to the import() syntax proposed by ECMAScript, which is consistent with the ordinary import statement or require function Similar to , but returns a Promise object. This means that the module is loaded asynchronously for

webpack v2 using

usage

function component() {
  return import( /* webpackChunkName: "lodash" */ 'lodash').then(_ => {
    var element = document.createElement('p');
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    return element;
  }).catch(error => 'An error occurred while loading the component');
}

// 或者使用async

async function getComponent() {
  var element = document.createElement('p');
  const _ = await import(/* webpackChunkName: "lodash" */ 'lodash');
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
  return element;
}

require.ensure

specified by webpack Usage method

webpack v1 v2 Specify usage method

Usage method

require.ensure([], function(require){
    var list = require('./list');
    list.show();
,'list');

<!-- Router -->
const Foo = require.ensure([], () => {
    require("Foo");
}, err => {
    console.error("We failed to load chunk: " + err);
}, "chunk-name");

//react-router2 or 3
<Route path="/foo" getComponent={Foo} />

lazyload-loader

Compared to the first two, This way of writing is more concise.

Usage

// webpack 配置文件中 使用lazyload-loader(必须将lazuyload-loader 放置在use的最右侧)

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,,
        use: [
          'babel-loader',
          'lazyload-loader'
        ]
      },

In business code

 // 使用lazy! 前缀 代表需要懒加载的Router
 
 import Shop from 'lazy!./src/view/Shop';
 
 // Router 正常使用
  <Route path="/shop" component={Shop} />

Principle: https://github.com/rongchangh...

The above is the detailed content of Another solution for lazy loading implementation of React routing (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete