Commit 32af8294 authored by Arunoda Susiripala's avatar Arunoda Susiripala Committed by GitHub

Load the main JS bundle in production with async (#1485)

* Use a webpack plugin to combine assets.

* Add comments and make this releseable.

* Fix some typos.

* Fix some typos.
parent 377a614f
...@@ -67,6 +67,7 @@ ...@@ -67,6 +67,7 @@
"is-windows-bash": "1.0.3", "is-windows-bash": "1.0.3",
"json-loader": "0.5.4", "json-loader": "0.5.4",
"loader-utils": "1.1.0", "loader-utils": "1.1.0",
"md5-file": "3.1.1",
"minimist": "1.2.0", "minimist": "1.2.0",
"mitt": "1.1.0", "mitt": "1.1.0",
"mkdirp-then": "1.2.0", "mkdirp-then": "1.2.0",
......
...@@ -5,14 +5,15 @@ import uuid from 'uuid' ...@@ -5,14 +5,15 @@ import uuid from 'uuid'
import del from 'del' import del from 'del'
import webpack from './webpack' import webpack from './webpack'
import replaceCurrentBuild from './replace' import replaceCurrentBuild from './replace'
import md5File from 'md5-file/promise'
export default async function build (dir) { export default async function build (dir) {
const buildDir = join(tmpdir(), uuid.v4()) const buildDir = join(tmpdir(), uuid.v4())
const compiler = await webpack(dir, { buildDir }) const compiler = await webpack(dir, { buildDir })
try { try {
const webpackStats = await runCompiler(compiler) await runCompiler(compiler)
await writeBuildStats(buildDir, webpackStats) await writeBuildStats(buildDir)
await writeBuildId(buildDir) await writeBuildId(buildDir)
} catch (err) { } catch (err) {
console.error(`> Failed to build on ${buildDir}`) console.error(`> Failed to build on ${buildDir}`)
...@@ -44,17 +45,18 @@ function runCompiler (compiler) { ...@@ -44,17 +45,18 @@ function runCompiler (compiler) {
}) })
} }
async function writeBuildStats (dir, webpackStats) { async function writeBuildStats (dir) {
const chunkHashMap = {} // Here we can't use hashes in webpack chunks.
webpackStats.chunks // That's because the "app.js" is not tied to a chunk.
// We are not interested about pages // It's created by merging a few assets. (commons.js and main.js)
.filter(({ files }) => !/^bundles/.test(files[0])) // So, we need to generate the hash ourself.
.forEach(({ hash, files }) => { const assetHashMap = {
chunkHashMap[files[0]] = { hash } 'app.js': {
}) hash: await md5File(join(dir, '.next', 'app.js'))
}
}
const buildStatsPath = join(dir, '.next', 'build-stats.json') const buildStatsPath = join(dir, '.next', 'build-stats.json')
await fs.writeFile(buildStatsPath, JSON.stringify(chunkHashMap), 'utf8') await fs.writeFile(buildStatsPath, JSON.stringify(assetHashMap), 'utf8')
} }
async function writeBuildId (dir) { async function writeBuildId (dir) {
......
// This plugin combines a set of assets into a single asset
// This should be only used with text assets,
// otherwise the result is unpredictable.
export default class CombineAssetsPlugin {
constructor ({ input, output }) {
this.input = input
this.output = output
}
apply (compiler) {
compiler.plugin('after-compile', (compilation, callback) => {
let newSource = ''
this.input.forEach((name) => {
newSource += `${compilation.assets[name].source()}\n`
delete compilation.assets[name]
})
compilation.assets[this.output] = {
source: () => newSource,
size: () => newSource.length
}
callback()
})
}
}
...@@ -7,6 +7,7 @@ import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin' ...@@ -7,6 +7,7 @@ import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin' import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin' import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import JsonPagesPlugin from './plugins/json-pages-plugin' import JsonPagesPlugin from './plugins/json-pages-plugin'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import getConfig from '../config' import getConfig from '../config'
import * as babelCore from 'babel-core' import * as babelCore from 'babel-core'
import findBabelConfig from './babel/find-config' import findBabelConfig from './babel/find-config'
...@@ -119,6 +120,10 @@ export default async function createCompiler (dir, { dev = false, quiet = false, ...@@ -119,6 +120,10 @@ export default async function createCompiler (dir, { dev = false, quiet = false,
} }
} else { } else {
plugins.push( plugins.push(
new CombineAssetsPlugin({
input: ['commons.js', 'main.js'],
output: 'app.js'
}),
new webpack.optimize.UglifyJsPlugin({ new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }, compress: { warnings: false },
sourceMap: false sourceMap: false
......
...@@ -59,16 +59,36 @@ export class NextScript extends Component { ...@@ -59,16 +59,36 @@ export class NextScript extends Component {
_documentProps: PropTypes.any _documentProps: PropTypes.any
} }
getChunkScript (filename) { getChunkScript (filename, additionalProps = {}) {
const { __NEXT_DATA__ } = this.context._documentProps const { __NEXT_DATA__ } = this.context._documentProps
let { buildStats } = __NEXT_DATA__ let { buildStats } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : '-' const hash = buildStats ? buildStats[filename].hash : '-'
return ( return (
<script type='text/javascript' src={`/_next/${hash}/${filename}`} defer /> <script
type='text/javascript'
src={`/_next/${hash}/${filename}`}
{...additionalProps}
/>
) )
} }
getScripts () {
const { dev } = this.context._documentProps
if (dev) {
return (
<div>
{ this.getChunkScript('commons.js') }
{ this.getChunkScript('main.js') }
</div>
)
}
// In the production mode, we have a single asset with all the JS content.
// So, we can load the script with async
return this.getChunkScript('app.js', { async: true })
}
render () { render () {
const { staticMarkup, __NEXT_DATA__ } = this.context._documentProps const { staticMarkup, __NEXT_DATA__ } = this.context._documentProps
...@@ -76,8 +96,7 @@ export class NextScript extends Component { ...@@ -76,8 +96,7 @@ export class NextScript extends Component {
{staticMarkup ? null : <script dangerouslySetInnerHTML={{ {staticMarkup ? null : <script dangerouslySetInnerHTML={{
__html: `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}; module={};` __html: `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}; module={};`
}} />} }} />}
{ staticMarkup ? null : this.getChunkScript('commons.js') } {staticMarkup ? null : this.getScripts()}
{ staticMarkup ? null : this.getChunkScript('main.js') }
</div> </div>
} }
} }
...@@ -102,6 +102,12 @@ export default class Server { ...@@ -102,6 +102,12 @@ export default class Server {
await this.serveStatic(req, res, p) await this.serveStatic(req, res, p)
}, },
'/_next/:hash/app.js': async (req, res, params) => {
this.handleBuildHash('app.js', params.hash, res)
const p = join(this.dir, '.next/app.js')
await this.serveStatic(req, res, p)
},
'/_next/:buildId/pages/:path*': async (req, res, params) => { '/_next/:buildId/pages/:path*': async (req, res, params) => {
if (!this.handleBuildId(params.buildId, res)) { if (!this.handleBuildId(params.buildId, res)) {
res.setHeader('Content-Type', 'application/json') res.setHeader('Content-Type', 'application/json')
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment