Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Created March 12, 2017 11:03
Show Gist options
  • Save jamiebuilds/abecfe8ec2a7ce1e312a904527a31908 to your computer and use it in GitHub Desktop.
Save jamiebuilds/abecfe8ec2a7ce1e312a904527a31908 to your computer and use it in GitHub Desktop.
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './components/App';
import {flushServerSideRequires} from 'react-loadable';
let app = express();
let webpackStats = require('./output-webpack-stats.json');
let modules = {};
let bundles = {};
webpackStats.modules.forEach(module => {
let parts = module.identifier.split('!');
let filePath = parts[parts.length - 1];
modules[filePath] = module.chunks;
});
webpackStats.chunks.forEach(chunk => {
bundles[chunk.id] = chunk.files;
});
app.get('/', (req, res) => {
let app = ReactDOMServer.renderToString(<App/>);
let requires = flushServerSideRequires();
let scripts = ['bundle-main.js'];
requires.forEach(file => {
let matchedBundles = modules[file + '.js'];
matchedBundles.forEach(bundle => {
bundles[bundle].forEach(script => {
scripts.unshift(script);
});
});
});
res.send(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>react-loadable-example</title>
</head>
<body>
<div id="root">${app}</div>
${scripts.map(script => {
return `<script type="text/javascript" src="scripts/${script}"></script>`
}).join('\n')}
</body>
</html>
`)
})
app.use(express.static('public'));
app.listen(3000);
console.log('Listening at http://localhost:3000/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment