Commit 8f874f05 authored by Arunoda Susiripala's avatar Arunoda Susiripala Committed by GitHub

[WIP] Use buildId in chunk urls as well (#2873)

Use buildId in chunk urls as well
parent fd198d28
module.exports = {
exportPathMap: function () {
return {
'/': { page: '/' },
'/about': { page: '/about' }
}
}
}
...@@ -6,11 +6,11 @@ ...@@ -6,11 +6,11 @@
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"export": "next export",
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"async-reactor": "^1.1.1", "next": "^3.0.6",
"next": "^3.0.1-beta.5",
"react": "^15.4.2", "react": "^15.4.2",
"react-dom": "^15.4.2" "react-dom": "^15.4.2"
}, },
......
...@@ -3,7 +3,6 @@ import Router from 'next/router' ...@@ -3,7 +3,6 @@ import Router from 'next/router'
import Header from '../components/Header' import Header from '../components/Header'
import Counter from '../components/Counter' import Counter from '../components/Counter'
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
import { asyncReactor } from 'async-reactor'
const DynamicComponent = dynamic(import('../components/hello1')) const DynamicComponent = dynamic(import('../components/hello1'))
const DynamicComponentWithCustomLoading = dynamic( const DynamicComponentWithCustomLoading = dynamic(
...@@ -16,11 +15,6 @@ const DynamicComponentWithNoSSR = dynamic( ...@@ -16,11 +15,6 @@ const DynamicComponentWithNoSSR = dynamic(
import('../components/hello3'), import('../components/hello3'),
{ ssr: false } { ssr: false }
) )
const DynamicComponentWithAsyncReactor = asyncReactor(async () => {
const Hello4 = await import('../components/hello4')
return (<Hello4 />)
})
const DynamicComponent5 = dynamic(import('../components/hello5')) const DynamicComponent5 = dynamic(import('../components/hello5'))
const DynamicBundle = dynamic({ const DynamicBundle = dynamic({
...@@ -67,7 +61,6 @@ export default class Index extends React.Component { ...@@ -67,7 +61,6 @@ export default class Index extends React.Component {
<DynamicComponent /> <DynamicComponent />
<DynamicComponentWithCustomLoading /> <DynamicComponentWithCustomLoading />
<DynamicComponentWithNoSSR /> <DynamicComponentWithNoSSR />
<DynamicComponentWithAsyncReactor />
<DynamicBundle showMore={showMore} /> <DynamicBundle showMore={showMore} />
<button onClick={() => this.toggleShowMore()}>Toggle Show More</button> <button onClick={() => this.toggleShowMore()}>Toggle Show More</button>
{ {
......
...@@ -8,13 +8,14 @@ import replaceCurrentBuild from './replace' ...@@ -8,13 +8,14 @@ import replaceCurrentBuild from './replace'
import md5File from 'md5-file/promise' import md5File from 'md5-file/promise'
export default async function build (dir, conf = null) { export default async function build (dir, conf = null) {
const buildId = uuid.v4()
const buildDir = join(tmpdir(), uuid.v4()) const buildDir = join(tmpdir(), uuid.v4())
const compiler = await webpack(dir, { buildDir, conf }) const compiler = await webpack(dir, { buildId, buildDir, conf })
try { try {
await runCompiler(compiler) await runCompiler(compiler)
await writeBuildStats(buildDir) await writeBuildStats(buildDir)
await writeBuildId(buildDir) await writeBuildId(buildDir, buildId)
} catch (err) { } catch (err) {
console.error(`> Failed to build on ${buildDir}`) console.error(`> Failed to build on ${buildDir}`)
throw err throw err
...@@ -59,8 +60,7 @@ async function writeBuildStats (dir) { ...@@ -59,8 +60,7 @@ async function writeBuildStats (dir) {
await fs.writeFile(buildStatsPath, JSON.stringify(assetHashMap), 'utf8') await fs.writeFile(buildStatsPath, JSON.stringify(assetHashMap), 'utf8')
} }
async function writeBuildId (dir) { async function writeBuildId (dir, buildId) {
const buildIdPath = join(dir, '.next', 'BUILD_ID') const buildIdPath = join(dir, '.next', 'BUILD_ID')
const buildId = uuid.v4()
await fs.writeFile(buildIdPath, buildId, 'utf8') await fs.writeFile(buildIdPath, buildId, 'utf8')
} }
...@@ -27,7 +27,7 @@ const interpolateNames = new Map(defaultPages.map((p) => { ...@@ -27,7 +27,7 @@ const interpolateNames = new Map(defaultPages.map((p) => {
const relativeResolve = rootModuleRelativePath(require) const relativeResolve = rootModuleRelativePath(require)
export default async function createCompiler (dir, { dev = false, quiet = false, buildDir, conf = null } = {}) { export default async function createCompiler (dir, { buildId, dev = false, quiet = false, buildDir, conf = null } = {}) {
dir = resolve(dir) dir = resolve(dir)
const config = getConfig(dir, conf) const config = getConfig(dir, conf)
const defaultEntries = dev ? [ const defaultEntries = dev ? [
...@@ -296,7 +296,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false, ...@@ -296,7 +296,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false,
path: buildDir ? join(buildDir, '.next') : join(dir, config.distDir), path: buildDir ? join(buildDir, '.next') : join(dir, config.distDir),
filename: '[name]', filename: '[name]',
libraryTarget: 'commonjs2', libraryTarget: 'commonjs2',
publicPath: '/_next/webpack/', publicPath: `/_next/${buildId}/webpack/`,
strictModuleExceptionHandling: true, strictModuleExceptionHandling: true,
devtoolModuleFilenameTemplate ({ resourcePath }) { devtoolModuleFilenameTemplate ({ resourcePath }) {
const hash = createHash('sha1') const hash = createHash('sha1')
......
...@@ -67,12 +67,12 @@ export class Head extends Component { ...@@ -67,12 +67,12 @@ export class Head extends Component {
getPreloadDynamicChunks () { getPreloadDynamicChunks () {
const { chunks, __NEXT_DATA__ } = this.context._documentProps const { chunks, __NEXT_DATA__ } = this.context._documentProps
let { assetPrefix } = __NEXT_DATA__ let { assetPrefix, buildId } = __NEXT_DATA__
return chunks.map((chunk) => ( return chunks.map((chunk) => (
<link <link
key={chunk} key={chunk}
rel='preload' rel='preload'
href={`${assetPrefix}/_next/webpack/chunks/${chunk}`} href={`${assetPrefix}/_next/${buildId}/webpack/chunks/${chunk}`}
as='script' as='script'
/> />
)) ))
...@@ -153,7 +153,7 @@ export class NextScript extends Component { ...@@ -153,7 +153,7 @@ export class NextScript extends Component {
getDynamicChunks () { getDynamicChunks () {
const { chunks, __NEXT_DATA__ } = this.context._documentProps const { chunks, __NEXT_DATA__ } = this.context._documentProps
let { assetPrefix } = __NEXT_DATA__ let { assetPrefix, buildId } = __NEXT_DATA__
return ( return (
<div> <div>
{chunks.map((chunk) => ( {chunks.map((chunk) => (
...@@ -161,7 +161,7 @@ export class NextScript extends Component { ...@@ -161,7 +161,7 @@ export class NextScript extends Component {
async async
key={chunk} key={chunk}
type='text/javascript' type='text/javascript'
src={`${assetPrefix}/_next/webpack/chunks/${chunk}`} src={`${assetPrefix}/_next/${buildId}/webpack/chunks/${chunk}`}
/> />
))} ))}
</div> </div>
......
...@@ -51,10 +51,10 @@ export default async function (dir, options) { ...@@ -51,10 +51,10 @@ export default async function (dir, options) {
if (existsSync(join(nextDir, 'chunks'))) { if (existsSync(join(nextDir, 'chunks'))) {
log(' copying dynamic import chunks') log(' copying dynamic import chunks')
await mkdirp(join(outDir, '_next', 'webpack')) await mkdirp(join(outDir, '_next', buildId, 'webpack'))
await cp( await cp(
join(nextDir, 'chunks'), join(nextDir, 'chunks'),
join(outDir, '_next', 'webpack', 'chunks') join(outDir, '_next', buildId, 'webpack', 'chunks')
) )
} }
......
...@@ -5,6 +5,7 @@ import onDemandEntryHandler from './on-demand-entry-handler' ...@@ -5,6 +5,7 @@ import onDemandEntryHandler from './on-demand-entry-handler'
import webpack from './build/webpack' import webpack from './build/webpack'
import clean from './build/clean' import clean from './build/clean'
import getConfig from './config' import getConfig from './config'
import UUID from 'uuid'
import { import {
IS_BUNDLED_PAGE IS_BUNDLED_PAGE
} from './utils' } from './utils'
...@@ -23,6 +24,11 @@ export default class HotReloader { ...@@ -23,6 +24,11 @@ export default class HotReloader {
this.prevChunkNames = null this.prevChunkNames = null
this.prevFailedChunkNames = null this.prevFailedChunkNames = null
this.prevChunkHashes = null this.prevChunkHashes = null
// Here buildId could be any value.
// Our router accepts any value in the dev mode.
// But for the webpack-compiler and for the webpack-dev-server
// it should be the same value.
this.buildId = UUID.v4()
this.config = getConfig(dir, conf) this.config = getConfig(dir, conf)
} }
...@@ -40,7 +46,7 @@ export default class HotReloader { ...@@ -40,7 +46,7 @@ export default class HotReloader {
async start () { async start () {
const [compiler] = await Promise.all([ const [compiler] = await Promise.all([
webpack(this.dir, { dev: true, quiet: this.quiet }), webpack(this.dir, { buildId: this.buildId, dev: true, quiet: this.quiet }),
clean(this.dir) clean(this.dir)
]) ])
...@@ -66,7 +72,7 @@ export default class HotReloader { ...@@ -66,7 +72,7 @@ export default class HotReloader {
this.stats = null this.stats = null
const [compiler] = await Promise.all([ const [compiler] = await Promise.all([
webpack(this.dir, { dev: true, quiet: this.quiet }), webpack(this.dir, { buildId: this.buildId, dev: true, quiet: this.quiet }),
clean(this.dir) clean(this.dir)
]) ])
...@@ -173,7 +179,7 @@ export default class HotReloader { ...@@ -173,7 +179,7 @@ export default class HotReloader {
] ]
let webpackDevMiddlewareConfig = { let webpackDevMiddlewareConfig = {
publicPath: '/_next/webpack/', publicPath: `/_next/${this.buildId}/webpack/`,
noInfo: true, noInfo: true,
quiet: true, quiet: true,
clientLogLevel: 'warning', clientLogLevel: 'warning',
......
...@@ -123,14 +123,21 @@ export default class Server { ...@@ -123,14 +123,21 @@ export default class Server {
}, },
// This is to support, webpack dynamic imports in production. // This is to support, webpack dynamic imports in production.
'/_next/webpack/chunks/:name': async (req, res, params) => { '/_next/:buildId/webpack/chunks/:name': async (req, res, params) => {
res.setHeader('Cache-Control', 'max-age=365000000, immutable') if (!this.handleBuildId(params.buildId, res)) {
return this.send404(res)
}
const p = join(this.dir, this.dist, 'chunks', params.name) const p = join(this.dir, this.dist, 'chunks', params.name)
await this.serveStatic(req, res, p) await this.serveStatic(req, res, p)
}, },
// This is to support, webpack dynamic import support with HMR // This is to support, webpack dynamic import support with HMR
'/_next/webpack/:id': async (req, res, params) => { '/_next/:buildId/webpack/:id': async (req, res, params) => {
if (!this.handleBuildId(params.buildId, res)) {
return this.send404(res)
}
const p = join(this.dir, this.dist, 'chunks', params.id) const p = join(this.dir, this.dist, 'chunks', params.id)
await this.serveStatic(req, res, p) await this.serveStatic(req, res, p)
}, },
......
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