Giter Club home page Giter Club logo

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

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

universal-async-component's Issues

React 16.x TypeError: Object(...) is not a function

I just wanted to try out this fancy library, but it doesn't seem to work with react 16.x.

The error is thrown in line 5.

import * as React from 'react';
import './App.css';
import { getComponentAsync } from 'universal-async-component';

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

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <AsyncHelloWorld />
      </div>
    );
  }
}

export default App;
"dependencies": {
    "lodash": "^4.17.5",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts-ts": "2.13.0",
    "universal-async-component": "^1.0.1"
  },

Comparison with similar libraries

Hi @mohsen1, thank you for open sourcing this library! Given that there are a few libraries that are trying to address this problem, I was wondering if you could provide a comparison (or pros/cons) of this library's approach and functionality with some of the other popular ones:

  1. React-Async-Component
  2. React-Loadable
  3. React-Universal-Component
  4. Loadable-Components

Alternatively, or in addition, understanding the approach of how this library works behind the scenes would be super useful to anyone trying to choose a solution!

Thank you again!

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.