GithubHelp home page GithubHelp logo

isabella232 / universal-async-component Goto Github PK

View Code? Open in Web Editor NEW

This project forked from lyft/universal-async-component

0.0 0.0 0.0 13 KB

React Universal Async Component that works with server side rendering

License: Apache License 2.0

TypeScript 100.00%

universal-async-component's Introduction

Universal Async Component

Async component that works in server and client. It will allows code splitting that works for universal apps.

What is this?

This is solving the hard problem of mixing code splitting and server side rendering. To avoid "flash of contents" in the initial page load server must include dynamic chunks required to render that screen in the HTML response. Using this library and adding corresponding components to your build system you can achieve that.

Example project

See the example repo

Usage

import { getComponentAsync } from 'universal-async-component';

const AsyncHelloWorld = getComponentAsync({ loader: () => import('./hello') });

const App = () => <AsyncHelloWorld />

Server side rendering

To make server-side rendering work you should update your server code to collect additional required chunks and also update your Webpack config to replace import() calls with something special that makes all of this work.

1. Add CaptureChunks

Wrap you app with CaptureChunks in your server renderer. You need to provide Webpack client side stats to it. Also, pass an empty array

const additionalChunks = [];
var htmlString = ReactDOM.renderToString(
    <CaptureChunks statsChunks={clientStats.chunks} additionalChunks={additionalChunks}>
        <App />
    </CaptureChunks>
);

After above code is run, additionalChunks is populated with all chunkIds that is required to render current App.

Use Webpack StatsPlugin you can write the stats to disk:

new StatsPlugin({
    filename: 'client-stats.json',
    fields: ['chunks', 'publicPath', 'assets'],
})

2. Use additionalChunks

Use additionalChunks retrieved from CaptureChunks to append required chunks

res.send(`
<html>
    <body>
        <div id="root">${htmlString}</div>
        <script src="webpack-bootstrap.js"></script>
        ${additionalChunks.map(chunkId => `<script src="${chunksId}.client.js"></script>`)}
        <script src="client.js"></script>
    </body>
</html>
`)

Note that additional chunks must come before the main bundle and after Webpack bootstrap script. It's easy to extract out Webpack bootstrap by using CommonsChunkPlugin plugin:

new webpack.optimize.CommonsChunkPlugin({
    names: ['bootstrap'],
    filename: 'webpack-bootstrap.js',
    minChunks: Infinity
}),

3. Add "string-replace-loader"

Add "string-replace-loader" before any of other loaders in your client and server Webpack config and require options from "universal-async-component":

const { stringReplaceLoaderOptions } = require('universal-async-component');
const config = {
    rules: [
        test: /\.jsx?/,
        use: {
            loader: "string-replace-loader",
            options: stringReplaceLoaderOptions,
        },
    ],
}

Note: this will go away once React can render async components

universal-async-component's People

Contributors

mohsen1 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.