react-loadable

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 常用JavaScript包
软件类型 开源软件
地区 不详
投 递 者 单展
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

React Loadable

A higher order component for loading components with dynamic imports.

Install

yarn add react-loadable

Example

import Loadable from 'react-loadable';
import Loading from './my-loading-component';

const LoadableComponent = Loadable({
  loader: () => import('./my-component'),
  loading: Loading,
});

export default class App extends React.Component {
  render() {
    return <LoadableComponent/>;
  }
}

Happy Customers:

Users

If your company or project is using React Loadable, please open a PR and addyourself to this list (in alphabetical order please)

Also See:

  • react-loadable-visibility - Building on top of and keeping the same API as react-loadable, this library enables you to load content that is visible on the screen.

  • react-loadable-ssr-addon - Server Side Render add-on for react-loadable. Discover & load automatically dynamically all files dependencies, e.g. splitted chunks, css, etc.



GUIDE

Guide

So you've got your React app, you're bundling it with Webpack, and things aregoing smooth. But then one day you notice your app's bundle is getting so bigthat it's slowing things down.

It's time to start code-splitting your app!

A single giant bundle vs multiple smaller bundles

Code-splitting is the process of taking one large bundle containing your entireapp, and splitting them up into multiple smaller bundles which contain separateparts of your app.

This might seem difficult to do, but tools like Webpack have this built in, andReact Loadable is designed to make it super simple.

Route-based splitting vs. Component-based splitting

A common piece of advice you will see is to break your app into separate routesand load each one asynchronously. This seems to work well enough for many apps–as a user, clicking a link and waiting for a page to load is a familiarexperience on the web.

But we can do better than that.

Using most routing tools for React, a route is simply a component. There'snothing particularly special about them (Sorry Ryan and Michael– you're what'sspecial). So what if we optimized for splitting around components instead ofroutes? What would that get us?

Route vs. component centric code splitting

As it turns out: Quite a lot. There are many more places than just routes whereyou can pretty easily split apart your app. Modals, tabs, and many more UIcomponents hide content until the user has done something to reveal it.

Example: Maybe your app has a map buried inside of a tab component. Whywould you load a massive mapping library for the parent route every time whenthe user may never go to that tab?

Not to mention all the places where you can defer loading content until higherpriority content is finished loading. That component at the bottom of your pagewhich loads a bunch of libraries: Why should that be loaded at the same time asthe content at the top?

And because routes are just components, we can still easily code-split at theroute level.

Introducing new code-splitting points in your app should be so easy that youdon't think twice about it. It should be a matter of changing a few lines ofcode and everything else should be automated.

Introducing React Loadable

React Loadable is a small library that makes component-centric code splittingincredibly easy in React.

Loadable is a higher-order component (a function that creates a component)which lets you dynamically load any module before rendering it into your app.

Let's imagine two components, one that imports and renders another.

import Bar from './components/Bar';

class Foo extends React.Component {
  render() {
    return <Bar/>;
  }
}

Right now we're depending on Bar being imported synchronously via import,but we don't need it until we go to render it. So why don't we just defer that?

Using a dynamic import (a tc39 proposal currently at Stage 3)we can modify our component to load Bar asynchronously.

class MyComponent extends React.Component {
  state = {
    Bar: null
  };

  componentWillMount() {
    import('./components/Bar').then(Bar => {
      this.setState({ Bar: Bar.default });
    });
  }

  render() {
    let {Bar} = this.state;
    if (!Bar) {
      return <div>Loading...</div>;
    } else {
      return <Bar/>;
    };
  }
}

But that's a whole bunch of work, and it doesn't even handle a bunch of cases.What about when import() fails? What about server-side rendering?

Instead you can use Loadable to abstract away the problem.

import Loadable from 'react-loadable';

const LoadableBar = Loadable({
  loader: () => import('./components/Bar'),
  loading() {
    return <div>Loading...</div>
  }
});

class MyComponent extends React.Component {
  render() {
    return <LoadableBar/>;
  }
}

Automatic code-splitting on import()

When you use import() with Webpack 2+, it willautomatically code-split foryou with no additional configuration.

This means that you can easily experiment with new code splitting points justby switching to import() and using React Loadable. Figure out what performsbest for your app.

Creating a great "Loading..." Component

Rendering a static "Loading..." doesn't communicate enough to the user. Youalso need to think about error states, timeouts, and making it a niceexperience.

function Loading() {
  return <div>Loading...</div>;
}

Loadable({
  loader: () => import('./WillFailToLoad'), // oh no!
  loading: Loading,
});

To make this all nice, your loading component receives acouple different props.

Loading error states

When your loader fails, your loading componentwill receive an error prop which will be an Error object (otherwise itwill be null).

function Loading(props) {
  if (props.error) {
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else {
    return <div>Loading...</div>;
  }
}

Avoiding Flash Of Loading Component

Sometimes components load really quickly (<200ms) and the loading screen onlyquickly flashes on the screen.

A number of user studies have proven that this causes users to perceive thingstaking longer than they really have. If you don't show anything, users perceiveit as being faster.

So your loading component will also get a pastDelay propwhich will only be true once the component has taken longer to load than a setdelay.

function Loading(props) {
  if (props.error) {
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.pastDelay) {
    return <div>Loading...</div>;
  } else {
    return null;
  }
}

This delay defaults to 200ms but you can also customize thedelay in Loadable.

Loadable({
  loader: () => import('./components/Bar'),
  loading: Loading,
  delay: 300, // 0.3 seconds
});

Timing out when the loader is taking too long

Sometimes network connections suck and never resolve or fail, they just hangthere forever. This sucks for the user because they won't know if it shouldalways take this long, or if they should try refreshing.

The loading component will receive atimedOut prop which will be set to true when theloader has timed out.

function Loading(props) {
  if (props.error) {
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.timedOut) {
    return <div>Taking a long time... <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.pastDelay) {
    return <div>Loading...</div>;
  } else {
    return null;
  }
}

However, this feature is disabled by default. To turn it on, you can pass atimeout option to Loadable.

Loadable({
  loader: () => import('./components/Bar'),
  loading: Loading,
  timeout: 10000, // 10 seconds
});

Customizing rendering

By default Loadable will render the default export of the returned module.If you want to customize this behavior you can use therender option.

Loadable({
  loader: () => import('./my-component'),
  render(loaded, props) {
    let Component = loaded.namedExport;
    return <Component {...props}/>;
  }
});

Loading multiple resources

Technically you can do whatever you want within loader() as long as itreturns a promise and you're able to render something.But writing it out can be a bit annoying.

To make it easier to load multiple resources in parallel, you can useLoadable.Map.

Loadable.Map({
  loader: {
    Bar: () => import('./Bar'),
    i18n: () => fetch('./i18n/bar.json').then(res => res.json()),
  },
  render(loaded, props) {
    let Bar = loaded.Bar.default;
    let i18n = loaded.i18n;
    return <Bar {...props} i18n={i18n}/>;
  },
});

When using Loadable.Map the render() method is required. Itwill be passed a loaded param which will be an object matching the shape ofyour loader.

Preloading

As an optimization, you can also decide to preload a component before it getsrendered.

For example, if you need to load a new component when a button gets pressed,you could start preloading the component when the user hovers over the button.

The component created by Loadable exposes astatic preload method which does exactly this.

const LoadableBar = Loadable({
  loader: () => import('./Bar'),
  loading: Loading,
});

class MyComponent extends React.Component {
  state = { showBar: false };

  onClick = () => {
    this.setState({ showBar: true });
  };

  onMouseOver = () => {
    LoadableBar.preload();
  };

  render() {
    return (
      <div>
        <button
          onClick={this.onClick}
          onMouseOver={this.onMouseOver}>
          Show Bar
        </button>
        {this.state.showBar && <LoadableBar/>}
      </div>
    )
  }
}



SERVER SIDE RENDERING

Server-Side Rendering

When you go to render all these dynamically loaded components, what you'll getis a whole bunch of loading screens.

This really sucks, but the good news is that React Loadable is designed tomake server-side rendering work as if nothing is being loaded dynamically.

Here's our starting server using Express.

import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './components/App';

const app = express();

app.get('/', (req, res) => {
  res.send(`
    <!doctype html>
    <html lang="en">
      <head>...</head>
      <body>
        <div id="app">${ReactDOMServer.renderToString(<App/>)}</div>
        <script src="/dist/main.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000, () => {
  console.log('Running on http://localhost:3000/');
});

Preloading all your loadable components on the server

The first step to rendering the correct content from the server is to make surethat all of your loadable components are already loaded when you go to renderthem.

To do this, you can use the Loadable.preloadAllmethod. It returns a promise that will resolve when all your loadablecomponents are ready.

Loadable.preloadAll().then(() => {
  app.listen(3000, () => {
    console.log('Running on http://localhost:3000/');
  });
});

Picking up a server-side rendered app on the client

This is where things get a little bit tricky. So let's prepare ourselveslittle bit.

In order for us to pick up what was rendered from the server we need to haveall the same code that was used to render on the server.

To do this, we first need our loadable components telling us which modules theyare rendering.

Declaring which modules are being loaded

There are two options in Loadable andLoadable.Map which are used to tell us which modules ourcomponent is trying to load: opts.modules andopts.webpack.

Loadable({
  loader: () => import('./Bar'),
  modules: ['./Bar'],
  webpack: () => [require.resolveWeak('./Bar')],
});

But don't worry too much about these options. React Loadable includes aBabel plugin to add them for you.

Just add the react-loadable/babel plugin to your Babel config:

{
  "plugins": [
    "react-loadable/babel"
  ]
}

Now these options will automatically be provided.

For typescript you can use react-loadable-ts-transformer which is a ts analog of react-loadable/babel plugin.

Finding out which dynamic modules were rendered

Next we need to find out which modules were actually rendered when a requestcomes in.

For this, there is Loadable.Capture component which canbe used to collect all the modules that were rendered.

import Loadable from 'react-loadable';

app.get('/', (req, res) => {
  let modules = [];

  let html = ReactDOMServer.renderToString(
    <Loadable.Capture report={moduleName => modules.push(moduleName)}>
      <App/>
    </Loadable.Capture>
  );

  console.log(modules);

  res.send(`...${html}...`);
});

Mapping loaded modules to bundles

In order to make sure that the client loads all the modules that were renderedserver-side, we'll need to map them to the bundles that Webpack created.

This comes in two parts.

First we need Webpack to tell us which bundles each module lives inside. Forthis there is the React Loadable Webpack plugin.

Import the ReactLoadablePlugin from react-loadable/webpack and include itin your webpack config. Pass it a filename for where to store the JSON dataabout our bundles.

// webpack.config.js
import { ReactLoadablePlugin } from 'react-loadable/webpack';

export default {
  plugins: [
    new ReactLoadablePlugin({
      filename: './dist/react-loadable.json',
    }),
  ],
};

Then we'll go back to our server and use this data to convert our modules tobundles.

To convert from modules to bundles, import the getBundlesmethod from react-loadable/webpack and the data from Webpack.

import Loadable from 'react-loadable';
import { getBundles } from 'react-loadable/webpack'
import stats from './dist/react-loadable.json';

app.get('/', (req, res) => {
  let modules = [];

  let html = ReactDOMServer.renderToString(
    <Loadable.Capture report={moduleName => modules.push(moduleName)}>
      <App/>
    </Loadable.Capture>
  );

  let bundles = getBundles(stats, modules);

  // ...
});

We can then render these bundles into <script> tags in our HTML.

It is important that the bundles are included before the main bundle, so thatthey can be loaded by the browser prior to the app rendering.

However, as the Webpack manifest (including the logic for parsing bundles) lives inthe main bundle, it will need to be extracted into its own chunk.

This is easy to do with the CommonsChunkPlugin

// webpack.config.js
export default {
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    })
  ]
}

Notice: As of Webpack 4 the CommonsChunkPlugin has been removed and the manifest doesn't need to be extracted anymore.

let bundles = getBundles(stats, modules);

res.send(`
  <!doctype html>
  <html lang="en">
    <head>...</head>
    <body>
      <div id="app">${html}</div>
      <script src="/dist/manifest.js"></script>
      <script src="/dist/main.js"></script>
      ${bundles.map(bundle => {
        return `<script src="/dist/${bundle.file}"></script>`
        // alternatively if you are using publicPath option in webpack config
        // you can use the publicPath value from bundle, e.g:
        // return `<script src="${bundle.publicPath}"></script>`
      }).join('\n')}
      <script>window.main();</script>
    </body>
  </html>
`);

Preloading ready loadable components on the client

We can use the Loadable.preloadReady() method on theclient to preload the loadable components that were included on the page.

Like Loadable.preloadAll(), it returns a promise,which on resolution means that we can hydrate our app.

// src/entry.js
import React from 'react';
import ReactDOM from 'react-dom';
import Loadable from 'react-loadable';
import App from './components/App';

window.main = () => {
  Loadable.preloadReady().then(() => {
    ReactDOM.hydrate(<App/>, document.getElementById('app'));
  });
};

Now server-side rendering should work perfectly!



API DOCS

API Docs

Loadable

A higher-order component for dynamically loading a module beforerendering it, a loading component is renderedwhile the module is unavailable.

const LoadableComponent = Loadable({
  loader: () => import('./Bar'),
  loading: Loading,
  delay: 200,
  timeout: 10000,
});

This returns a LoadableComponent.

Loadable.Map

A higher-order component that allows you to load multiple resources in parallel.

Loadable.Map's opts.loader accepts an object of functions, andneeds a opts.render method.

Loadable.Map({
  loader: {
    Bar: () => import('./Bar'),
    i18n: () => fetch('./i18n/bar.json').then(res => res.json()),
  },
  render(loaded, props) {
    let Bar = loaded.Bar.default;
    let i18n = loaded.i18n;
    return <Bar {...props} i18n={i18n}/>;
  }
});

When using Loadable.Map the render() method's loaded param will be anobject with the same shape as your loader.

Loadable and Loadable.Map Options

opts.loader

A function returning a promise that loads your module.

Loadable({
  loader: () => import('./Bar'),
});

When using with Loadable.Map this accepts an object of thesetypes of functions.

Loadable.Map({
  loader: {
    Bar: () => import('./Bar'),
    i18n: () => fetch('./i18n/bar.json').then(res => res.json()),
  },
});

When using with Loadable.Map you'll also need to pass aopts.render function.

opts.loading

A LoadingComponent that renders while a module isloading or when it errors.

Loadable({
  loading: LoadingComponent,
});

This option is required, if you don't want to render anything, return null.

Loadable({
  loading: () => null,
});

opts.delay

Time to wait (in milliseconds) before passingprops.pastDelay to your loadingcomponent. This defaults to 200.

Loadable({
  delay: 200
});

Read more about delays.

opts.timeout

Time to wait (in milliseconds) before passingprops.timedOut to your loading component.This is turned off by default.

Loadable({
  timeout: 10000
});

Read more about timeouts.

opts.render

A function to customize the rendering of loaded modules.

Receives loaded which is the resolved value of opts.loaderand props which are the props passed to theLoadableComponent.

Loadable({
  render(loaded, props) {
    let Component = loaded.default;
    return <Component {...props}/>;
  }
});

opts.webpack

An optional function which returns an array of Webpack module ids which you canget with require.resolveWeak.

Loadable({
  loader: () => import('./Foo'),
  webpack: () => [require.resolveWeak('./Foo')],
});

This option can be automated with the Babel Plugin.

opts.modules

An optional array with module paths for your imports.

Loadable({
  loader: () => import('./my-component'),
  modules: ['./my-component'],
});

This option can be automated with the Babel Plugin.

LoadableComponent

This is the component returned by Loadable and Loadable.Map.

const LoadableComponent = Loadable({
  // ...
});

Props passed to this component will be passed straight through to thedynamically loaded component via opts.render.

LoadableComponent.preload()

This is a static method on LoadableComponent which canbe used to load the component ahead of time.

const LoadableComponent = Loadable({...});

LoadableComponent.preload();

This returns a promise, but you should avoid waiting for that promise toresolve to update your UI. In most cases it creates a bad user experience.

Read more about preloading.

LoadingComponent

This is the component you pass to opts.loading.

function LoadingComponent(props) {
  if (props.error) {
    // When the loader has errored
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.timedOut) {
    // When the loader has taken longer than the timeout
    return <div>Taking a long time... <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.pastDelay) {
    // When the loader has taken longer than the delay
    return <div>Loading...</div>;
  } else {
    // When the loader has just started
    return null;
  }
}

Loadable({
  loading: LoadingComponent,
});

Read more about loading components

props.error

An Error object passed to LoadingComponent when theloader has failed. When there is no error, null ispassed.

function LoadingComponent(props) {
  if (props.error) {
    return <div>Error!</div>;
  } else {
    return <div>Loading...</div>;
  }
}

Read more about errors.

props.retry

A function prop passed to LoadingComponent when theloader has failed, used to retry loading the component.

function LoadingComponent(props) {
  if (props.error) {
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else {
    return <div>Loading...</div>;
  }
}

Read more about errors.

props.timedOut

A boolean prop passed to LoadingComponent after a settimeout.

function LoadingComponent(props) {
  if (props.timedOut) {
    return <div>Taking a long time...</div>;
  } else {
    return <div>Loading...</div>;
  }
}

Read more about timeouts.

props.pastDelay

A boolean prop passed to LoadingComponent after a setdelay.

function LoadingComponent(props) {
  if (props.pastDelay) {
    return <div>Loading...</div>;
  } else {
    return null;
  }
}

Read more about delays.

Loadable.preloadAll()

This will call all of theLoadableComponent.preload methods recursivelyuntil they are all resolved. Allowing you to preload all of your dynamicmodules in environments like the server.

Loadable.preloadAll().then(() => {
  app.listen(3000, () => {
    console.log('Running on http://localhost:3000/');
  });
});

It's important to note that this requires that you declare all of your loadablecomponents when modules are initialized rather than when your app is beingrendered.

Good:

// During module initialization...
const LoadableComponent = Loadable({...});

class MyComponent extends React.Component {
  componentDidMount() {
    // ...
  }
}

Bad:

// ...

class MyComponent extends React.Component {
  componentDidMount() {
    // During app render...
    const LoadableComponent = Loadable({...});
  }
}

Note: Loadable.preloadAll() will not work if you have more than onecopy of react-loadable in your app.

Read more about preloading on the server.

Loadable.preloadReady()

Check for modules that are already loaded in the browser and call the matchingLoadableComponent.preload methods.

Loadable.preloadReady().then(() => {
  ReactDOM.hydrate(<App/>, document.getElementById('app'));
});

Read more about preloading on the client.

Loadable.Capture

A component for reporting which modules were rendered.

Accepts a report prop which is called for every moduleName that isrendered via React Loadable.

let modules = [];

let html = ReactDOMServer.renderToString(
  <Loadable.Capture report={moduleName => modules.push(moduleName)}>
    <App/>
  </Loadable.Capture>
);

console.log(modules);

Read more about capturing rendered modules.

Babel Plugin

Providing opts.webpack and opts.modules forevery loadable component is a lot of manual work to remember to do.

Instead you can add the Babel plugin to your config and it will automate it foryou:

{
  "plugins": ["react-loadable/babel"]
}

Input

import Loadable from 'react-loadable';

const LoadableMyComponent = Loadable({
  loader: () => import('./MyComponent'),
});

const LoadableComponents = Loadable.Map({
  loader: {
    One: () => import('./One'),
    Two: () => import('./Two'),
  },
});

Output

import Loadable from 'react-loadable';
import path from 'path';

const LoadableMyComponent = Loadable({
  loader: () => import('./MyComponent'),
  webpack: () => [require.resolveWeak('./MyComponent')],
  modules: [path.join(__dirname, './MyComponent')],
});

const LoadableComponents = Loadable.Map({
  loader: {
    One: () => import('./One'),
    Two: () => import('./Two'),
  },
  webpack: () => [require.resolveWeak('./One'), require.resolveWeak('./Two')],
  modules: [path.join(__dirname, './One'), path.join(__dirname, './Two')],
});

Read more about declaring modules.

Webpack Plugin

In order to send the right bundles downwhen rendering server-side, you'll need the React Loadable Webpack plugin to provide you with a mapping of modules to bundles.

// webpack.config.js
import { ReactLoadablePlugin } from 'react-loadable/webpack';

export default {
  plugins: [
    new ReactLoadablePlugin({
      filename: './dist/react-loadable.json',
    }),
  ],
};

This will create a file (opts.filename) which you can import to map modulesto bundles.

Read more about mapping modules to bundles.

getBundles

A method exported by react-loadable/webpack for converting modules tobundles.

import { getBundles } from 'react-loadable/webpack';

let bundles = getBundles(stats, modules);

Read more about mapping modules to bundles.



FAQ

FAQ

How do I avoid repetition?

Specifying the same loading component or delay every time you useLoadable() gets repetitive fast. Instead you can wrap Loadable with yourown Higher-Order Component (HOC) to set default options.

import Loadable from 'react-loadable';
import Loading from './my-loading-component';

export default function MyLoadable(opts) {
  return Loadable(Object.assign({
    loading: Loading,
    delay: 200,
    timeout: 10000,
  }, opts));
};

Then you can just specify a loader when you go to use it.

import MyLoadable from './MyLoadable';

const LoadableMyComponent = MyLoadable({
  loader: () => import('./MyComponent'),
});

export default class App extends React.Component {
  render() {
    return <LoadableMyComponent/>;
  }
}

Unfortunately at the moment using wrapped Loadable breaks react-loadable/babel so in such case you have to add required properties (modules, webpack) manually.

import MyLoadable from './MyLoadable';

const LoadableMyComponent = MyLoadable({
  loader: () => import('./MyComponent'),
  modules: ['./MyComponent'],
  webpack: () => [require.resolveWeak('./MyComponent')],
});

export default class App extends React.Component {
  render() {
    return <LoadableMyComponent/>;
  }
}

How do I handle other styles .css or sourcemaps .map with server-side rendering?

When you call getBundles, it may return file types other thanJavaScript depending on your Webpack configuration.

To handle this, you should manually filter down to the file extensions thatyou care about:

let bundles = getBundles(stats, modules);

let styles = bundles.filter(bundle => bundle.file.endsWith('.css'));
let scripts = bundles.filter(bundle => bundle.file.endsWith('.js'));

res.send(`
  <!doctype html>
  <html lang="en">
    <head>
      ...
      ${styles.map(style => {
        return `<link href="/dist/${style.file}" rel="stylesheet"/>`
      }).join('\n')}
    </head>
    <body>
      <div id="app">${html}</div>
      <script src="/dist/main.js"></script>
      ${scripts.map(script => {
        return `<script src="/dist/${script.file}"></script>`
      }).join('\n')}
    </body>
  </html>
`);
  • 1、react-loadable使用 import { RouteConfig } from 'react-router-config'; import Loadable from 'react-loadable' import React from 'react'; interface CustomRouteConfig extends RouteConfig {} const routes

  • React 项目打包时,如果不进行异步组件的处理,那么所有页面所需要的 js 都在同一文件中(bundle.js),整个js文件很大,从而导致首屏加载时间过长。 所有,可以对组件进行异步加载处理,通常可以使用 React-loadable。 React-loadable 使用 例如,对于项目中的detail组件(/src/pages/detail/),在 detail 目录下新建 loadable

  • 1.新建 LoadableComponnet.js import React from 'react'; import Loadable from 'react-loadable'; import { isDevEvn } from '../utils/env' ; const Loading = (props) => { const { error } = props; const isDev

  • 1、安装react-router-dom,使用路由器BrowserRouter, 路由Route,还有Switch用于处理意外页面 import React, { Component, Fragment } from 'react'; import Header from './component/Header' import store from './store' import { Provi

  • 按需加载路由可以减去不必要运行,比如我们首次打开某个页面,我们只打开了一个路由,如果我们配置了按需加载,当前页面只会加载这个路由,如果没有配置的话,会发现我们进入到某个路由时,其他不相关的路由也已经加载,这样会大大增加项目运行速度,话不多说,直接看代码: 记得下载此模块 cnpm i react-loadable --save 定义路由懒加载工具 // 路由懒加载的工具类(我的项目懒加载类是放在u

  • react-loadable的使用(封装) 当组件还在加载中的时候显示一个页面,一般是一张动图gif表现出加载中的效果 asyncLoader.tsx import Loadable from 'react-loadable'; // import Toast from '_component/toast' import * as React from 'react'; import PageLo

  • 1.常规导入组件 常规的导入组件需要在文件开始就将导入的组件写死,如下 import xxx from 'xxx' 现在我需要通过后端返回的数组动态的生成路由,因此在不知道后端返回的情况下,不知道需要导入哪些组件,就需要根据后端返回的组件路径,动态导入组件, 方法一:require 后端返回的数据如下: [{ path: '/login', component: 'Login'

  • Demo1: import React from 'react' import style from './demo1.less' import _ from 'lodash' class Demo1 extends React.Component{ constructor(props){ super(props) } render(){

  • 引言 当前大部分 React 应用需要使用 code splitting 的时候,都选择使用优秀的 react-loadable 来处理检测代码段是否已加载。然而,随着React v16.6 的发布,我们有一个非常难得的机会 ,可以删除我们的第三方依赖! React.Suspense是一个新添加到核心React库中的功能,他的功能基本和 react-loadable 一致,所以不用多说,让我们来看

  • 1、引入 cnpm install --save react-loadable 2、使用 import React from 'react'; import Loadable from 'react-loadable'; const LoadableComponent = Loadable({ loader: () => import('需要加载的异步组件路径'),

  • import React,{Component} from 'react'; import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom'; import ReactDom from 'react-dom'; import Loadable from 'react-loadable'; const L

  • react大型项目之代码分割 在使用react做大型项目时会遇到项目打包后文件过大,加载慢,等问题。这时候就需要能够分割代码,在react官网中提供了不少的代码分割方案 前言 这里简单介绍一个react-loadable的库,但是这个插件的库已经很久没更新了,建议使用官网推荐的方式 一、react-loadable react-loadable具有丰富的功能,使用起来还是很不错的! 官网链接:re

  • // 先下载react-loadable npm i react-loadable -S // 建立一个loadable.js,放在src/until/loadable.js //引入插件,并导出 import Loadable from 'react-loadable'; export default function withLoadable(comp) { return Loada

 相关资料
  • 问题内容: 我注意到可以这样导入: …或像这样: 第一个导入模块中的所有内容(请参阅:导入整个模块的内容) 第二个仅导入模块导出(请参阅:导入默认值) 似乎这两种方法是不同的,并且根本上是不兼容的。 为什么它们都起作用? 请参考源代码并解释该机制…我有兴趣了解其工作原理。 ES6常规模块信息回答了该问题。 我在问使模块像这样工作的机制。在这里,它似乎与源代码中的 “ hacky”导出机制有关,但尚

  • 这篇快速上手指南会教你如何将TypeScript与React结合起来使用。 在最后,你将学到: 使用TypeScript和React创建工程 使用TSLint进行代码检查 使用Jest和Enzyme进行测试,以及 使用Redux管理状态 我们会使用create-react-app工具快速搭建工程环境。 这里假设你已经在使用Node.js和npm。 并且已经了解了React的基础知识。 我们之所以使

  • 我已经改用react Native制作跨平台应用程序(虽然没有制作)。我只是想要一个答案,我的问题,反应和反应之间的区别。我在网上搜索了一下,但没有找到合适的答案。

  • 问题内容: 与 哪个更好,为什么? 还是除了以后编写更少的代码外没有其他区别? 写作是否意味着只导入Component对象? 问题答案: 让您代替。它减少了React名称空间的键入和重复,这通常是一种理想的现代编码约定。 此外,Webpack 2和Rollup之类的工具会“摇晃”,这意味着任何未使用的导出都不会捆绑到您的最终代码中。使用/,您可以保证所有React的源代码都将被捆绑。使用,某些工具

  • 本文向大家介绍react-native 启动React Native Packager,包括了react-native 启动React Native Packager的使用技巧和注意事项,需要的朋友参考一下 示例 在最新版本的React Native上,无需运行打包程序。它将自动运行。 默认情况下,这将在端口8081上启动服务器。要指定服务器所在的端口            

  • 我正在使用“React admin”创建一个管理界面(前端)。我正在使用spring boot作为我的REST API。我的React应用程序的url是:“http://localhost:3000”。我的spring boot API的url是:“http://localhost:8080”。 下面是CORS配置的spring boot代码,它在一个单独的类中,称为CORSCONFIG: 下面是