项目作者: jaredLunde

项目描述 :
💸 SSR-capable async components & code splitting with Webpack 4+ and Babel 7+
高级语言: JavaScript
项目地址: git://github.com/jaredLunde/react-broker.git
创建时间: 2018-09-01T06:16:49Z
项目社区:https://github.com/jaredLunde/react-broker

开源协议:MIT License

下载




react-broker


Wolf of Wall Street Gif



Bundlephobia



NPM Version


MIT License


  1. npm i react-broker


A lightweight library for lazy components using React 16.8+. It’s perfect for
code splitting and has the simplest SSR story you’ve ever seen out-of-the-box.

Critically, this package is only intended to work with Webpack, specifically
Webpack 4 and future versions. There are no plans to implement a design
accommodating Parcel or other bundlers. There is also a hard requirement
for babel-plugin-macros (which is shipped with CRA) if you opt to use the macro.

Quick Start

  1. import {BrokerProvider} from 'react-broker'
  2. import lazy from 'react-broker/macro'
  3. // Automatically generates dynamic imports for webpack with babel-plugin-macros.
  4. // Just give it the path.
  5. const LazyPage = lazy('../pages/Page', {loading: props => 'Loading...'})
  6. ////////////////////////////////////////////////////////////////////////////////
  7. // ⬇ BECOMES ⬇ //
  8. ///////////////////////////////////////////////////////////////////////////////
  9. const LazyPage =
  10. require('react-broker').lazy(
  11. 'src/pages/Page',
  12. () => import(/* webpackChunkName: "src/pages/Page" */ '../pages/Page'),
  13. {loading: props => 'Loading...'}
  14. )
  15. function App () {
  16. // Look at me! I'm used like a normal component.
  17. return (
  18. <BrokerProvider>
  19. <LazyPage id='1'></LazyPage>
  20. </BrokerProvider/>
  21. )
  22. }

Requirements

  • Webpack 4+ (because chunks)
  • React 16.8+ (because hooks)
  • Babel (because babel-plugin-macros)

Examples

Hello world

Hello world w/ Router


API

react-broker/macro

The function that transforms your imports and delegates your async components.

  1. import lazy from 'react-broker/macro'

lazy(component <String>, options <Object>)

component {String}

A path to a React component you want to lazy load. The component must be in the default
export of the file.

Paths cannot be passed via an identifier, it has to be a plain string. It is used just like a
regular component.

You may also lazy load external library components, but just know that the component in question must be the
default export.

  1. // Used like a regular component
  2. const LazyPage = lazy('./pages/Home', {loading: props => 'Loading ${props.id}...'})
  3. <LazyPage id={1}>
  4. // ...
  5. </LazyPage>

options {Object}

  • loading (props, context{retry, error})
    • props props passed the component
    • context
      • retry is a function which will force a reload of the component
      • error is any error returned by Promise.reject, this is only relevant
        if an error component isn’t also defined in options
  • error (props, context{retry, error})
    • See loading

Broker.Provider

Manages code-splitting and the resolution of your async components by
keeping track of which chunk names have been loaded and also determining
which <scripts> need to be included from the server-side. Broker.Provider
must be defined at the top-level of your lazy loaded components.

Props

chunkCache {Broker.createChunkCache}

You only provide a chunkCache on the server side. In the client it is not
allowed. The chunk cache is used for tracking which chunks were loaded during
the latest render phase of the app.
Broker.createChunkCache

  1. import * as Broker from 'react-broker'
  2. const chunkCache = Broker.createChunkCache()
  3. function App (props) {
  4. return (
  5. <Broker.Provider chunkCache={chunkCache}>
  6. <LazyPage id={props.id}></LazyPage>
  7. </Broker.Provider>
  8. )
  9. }

Broker.createChunkCache

Creates a context for Broker.Provider to track chunks in and provides
helper methods to provide access to those chunks.

createChunkCache.getChunkNames()

Returns an array of all the Webpack chunk names loaded into the current app.

createChunkCache.getChunks(webpackStats)

Returns a Set of all the Webpack chunks loaded into the current app.

  • webpackStats <Object>
    • The stats object created by
      Webpack.
createChunkCache.getChunkScripts(webpackStats, options)

Returns a string representation of all the <script> tags to include in the
output of your app when using with SSR.

  • webpackStats {Object}
    • The stats object created by
      Webpack.
  • options {Object}
    • preload {Bool|Object}
      • If true, this will generate <link rel='preload'> tags with your scripts.
      • If an object, the key/value pairs will be added to the <link rel='preload'>
        tags as attributes. e.g. {preload: {crossorigin: 'anonymous'}} generates
        <link rel='preload' as='script' crossorigin='anonymous' href='...'>
    • async {Bool}
      • If true, an async flag will be added to your <script> tags
      • default true
    • defer {Bool}
      • If true, a defer flag will be added to your <script> tags and async
        will be omitted
      • default false

See the SSR section for an example


Broker.lazy

This is the function created by react-broker/macro.

To skip the macro you could do something like this with the Webpack code-splitting
API:

  1. import {lazy} from 'react-broker'
  2. const Component = lazy(
  3. 'uniqueChunkName',
  4. () => import(/* webpackChunkName: "uniqueChunkName" */'./path/to/component'),
  5. {loading: props => 'Loading...'}
  6. )

Lazy.load()

Preloads the component.

  1. const LazyPage = lazy('./pages/Home')
  2. // ...
  3. <Link onMouseEnter={LazyPage.load}>
  4. Home
  5. </Link>

Broker.load(...components <String>)

Preloads one or several Lazy components.

  1. import * as Broker from 'react-broker'
  2. import lazy from 'react-broker/macro'
  3. const LazyA = lazy('./A')
  4. const LazyB = lazy('./B')
  5. Broker.load(LazyA, LazyB).then(/*...*/)

Broker.loadAll(

App: React.Element,

renderer: ReactDOM.renderToStaticMarkup|renderToString

)

Tracks all of the chunks used in your app during the server side render and
optionally renders your app to a string

  • App {React.Element}
    • Your React application
  • renderer {ReactDOM.renderToStaticMarkup|ReactDOM.renderToString}
    • default ReactDOM.renderToStaticMarkup
    • The renderer used for determining the chunks used in your app. To avoid,
      extra renders, you could change this to `ReactDOM.renderToString.

See the SSR section for an example


Broker.loadInitial(chunkCache: Broker.createChunkCache)

Populates your chunk cache with the async components present in your application.
This requires that Broker.getChunkScripts was used on the server side. The primary
use case for this function is elimination loading components and flashes when
initially rendering your app in the browser.

See the SSR section for an example


Server-side Rendering

client/render.js

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. import * as Broker from 'react-broker'
  4. import App from '../App'
  5. const app = (
  6. <Broker.Provider>
  7. <App></App>
  8. </Broker.Provider>
  9. )
  10. Broker.loadInitial().then(
  11. () => ReactDOM.hydrate(app, document.getElementById('⚛️'))
  12. )

server/render.js

  1. import React from 'react'
  2. import ReactDOMServer from 'react-dom/server'
  3. import express from 'express'
  4. import * as Broker from 'react-broker'
  5. import App from '../App'
  6. export default function createRenderer({
  7. // These are the Webpack compilation stats returned by Webpack post-run.
  8. // https://webpack.js.org/api/stats/
  9. clientStats
  10. }) {
  11. app = express()
  12. app.get('*', /* Note 'async' here */ async (req, res, next) => {
  13. res.set('Content-Type', 'text/html')
  14. // keeps track of lazy chunks used by the current page
  15. const chunkCache = Broker.createChunkCache()
  16. // chunkCache is passed to Broker.Provider as a prop
  17. const app = (
  18. <Broker.Provider chunkCache={chunkCache}>
  19. <App></App>
  20. </Broker.Provider>
  21. )
  22. // Preloads the async components and renders the app to a string
  23. const page = await Broker.loadAll(app, ReactDOMServer.renderToString)
  24. // You could also do this if you have other requirements in addition to preloading with
  25. // react-broker
  26. // await Broker.loadAll(app, ReactDOMServer.renderToStaticMarkup)
  27. // const page = await ReactDOMServer.renderToString(app)
  28. // Generates <script> and <preload> tags for this page
  29. const chunks = chunkCache.getChunkScripts(clientStats, {preload: true})
  30. res.send(`
  31. <html>
  32. <head>
  33. ${chunks.preload}
  34. </head>
  35. <body>
  36. <div id='⚛️'>
  37. ${app}
  38. </div>
  39. ${chunks.scripts}
  40. </body>
  41. </html>
  42. `)
  43. })
  44. return app
  45. }