Skip to content

A higher order component for loading components with dynamic imports.

Notifications You must be signed in to change notification settings

jaywcjlove/react-dynamic-loadable

Repository files navigation

react-dynamic-loadable

Build and Lint

A higher order component for loading components with dynamic imports.

Install

npm install react-dynamic-loadable --save

Simple Example

Simple Example code

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

// Add Loading component.
loadable.setDefaultLoadingComponent(<div>Loading</div>);

const LoadableComponent = loadable({
  component: () => import('./my-component'),
  // LoadingComponent: () => Loading,
});

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

Example

Use Redux (@rematch), React Router Example.

Example code

import React from 'react';
import { model } from '@rematch/core';
import loadable from 'react-dynamic-loadable';

const dynamicWrapper = (models, component) => loadable({
  models: () => models.map((m) => {
    return import(`./models/${m}.js`).then((md) => {
      model({ name: m, ...md[m] || md.default });
    });
  }),
  component,
  LoadingComponent: () => <span>loading....</span>,
});

export const getRouterData = () => {
  const conf = {
    '/': {
      component: dynamicWrapper(['user'], () => import('./layouts/BasicLayout')),
    },
    '/home': {
      component: dynamicWrapper([], () => import('./routes/Home')),
    },
    '/login': {
      component: dynamicWrapper(['user'], () => import('./routes/Login')),
    },
  };
  return conf;
};

Server-Side Rendering

// webpack.config.js
import { DynamicLoadablePlugin } from 'react-dynamic-loadable/DynamicLoadablePlugin';
 
export default {
  plugins: [
    new DynamicLoadablePlugin({
      filename: './dist/loadable-assets.json',
      exclude: /.(js|css)$/
    }),
  ],
};
import { getBundles } from 'react-dynamic-loadable/DynamicLoadablePlugin';
let bundles = getBundles(stats, modules);