Unverified Commit f15cfeba authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

AMP automatic page refreshing in dev (#6392)

* AMP page reload

* Fix comment

* Skip dev files in production

* Polyfill event source

* Add HMR test for AMP

* Use webdriver

* Use a dynamic server for HMR test

* ffs
parent 78d560e5
......@@ -18,6 +18,8 @@ export const CLIENT_STATIC_FILES_RUNTIME = 'runtime'
export const CLIENT_STATIC_FILES_RUNTIME_PATH = `${CLIENT_STATIC_FILES_PATH}/${CLIENT_STATIC_FILES_RUNTIME}`
// static/runtime/main.js
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/main.js`
// static/runtime/amp.js
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/amp.js`
// static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/webpack.js`
// matches static/<buildid>/pages/<page>.js
......
/* globals __webpack_hash__ */
import EventSourcePolyfill from './event-source-polyfill'
import { getEventSourceWrapper } from './dev-error-overlay/eventsource'
if (!window.EventSource) {
window.EventSource = EventSourcePolyfill
}
const data = JSON.parse(document.getElementById('__NEXT_DATA__').textContent)
const { assetPrefix } = data
getEventSourceWrapper({
path: `${assetPrefix || ''}/_next/webpack-hmr`
}).addMessageListener(event => {
if (event.data === '\uD83D\uDC93') {
return
}
try {
const message = JSON.parse(event.data)
if (message.action === 'sync' || message.action === 'built') {
if (!message.hash) {
return
}
/* eslint-disable-next-line camelcase */
if (message.hash !== __webpack_hash__) {
document.location.reload(true)
}
} else if (message.action === 'reloadPage') {
document.location.reload(true)
}
} catch (ex) {
console.warn('Invalid HMR message: ' + event.data + '\n' + ex)
}
})
/* eslint-disable */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {htmlEscapeJsonString} from '../server/htmlescape'
import { htmlEscapeJsonString } from '../server/htmlescape'
import flush from 'styled-jsx/server'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
} from 'next-server/constants'
export default class Document extends Component {
static childContextTypes = {
......@@ -255,8 +259,43 @@ export class NextScript extends Component {
const { staticMarkup, assetPrefix, amphtml, devFiles, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
if(amphtml) {
return null
if (amphtml) {
if (process.env.NODE_ENV === 'production') {
return null
}
const devFiles = [
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
]
return (
<>
{staticMarkup ? null : (
<script
id="__NEXT_DATA__"
type="application/json"
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
dangerouslySetInnerHTML={{
__html: NextScript.getInlineScriptSource(
this.context._documentProps
),
}}
/>
)}
{devFiles
? devFiles.map(file => (
<script
key={file}
src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
))
: null}
</>
)
}
const { page, buildId } = __NEXT_DATA__
......
......@@ -6,7 +6,8 @@ import rimrafModule from 'rimraf'
import onDemandEntryHandler, { normalizePage } from './on-demand-entry-handler'
import webpack from 'webpack'
import getBaseWebpackConfig from '../build/webpack-config'
import { IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES } from 'next-server/constants'
import { IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES, CLIENT_STATIC_FILES_RUNTIME_AMP } from 'next-server/constants'
import { NEXT_PROJECT_ROOT_DIST_CLIENT } from '../lib/constants'
import { route } from 'next-server/dist/server/router'
import { promisify } from 'util'
import { createPagesMapping, createEntrypoints } from '../build/entries'
......@@ -173,8 +174,14 @@ export default class HotReloader {
const pages = createPagesMapping(pagePaths.filter(i => i !== null), this.config.pageExtensions)
const entrypoints = createEntrypoints(pages, 'server', this.buildId, this.config)
let additionalClientEntrypoints = {}
if (this.config.experimental.amp) {
additionalClientEntrypoints[CLIENT_STATIC_FILES_RUNTIME_AMP] = join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'amp-dev')
}
return [
getBaseWebpackConfig(this.dir, { dev: true, isServer: false, config: this.config, buildId: this.buildId, entrypoints: entrypoints.client }),
getBaseWebpackConfig(this.dir, { dev: true, isServer: false, config: this.config, buildId: this.buildId, entrypoints: { ...entrypoints.client, ...additionalClientEntrypoints } }),
getBaseWebpackConfig(this.dir, { dev: true, isServer: true, config: this.config, buildId: this.buildId, entrypoints: entrypoints.server })
]
}
......
export default () => {
return (
<div className='hmr-amp-page'>
<p>This is the hot AMP page.</p>
</div>
)
}
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import { readFileSync, writeFileSync } from 'fs'
import {
nextServer,
nextBuild,
startApp,
stopApp,
renderViaHTTP
renderViaHTTP,
check,
getBrowserBodyText,
findPort,
launchApp,
killApp
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
import amphtmlValidator from 'amphtml-validator'
const appDir = join(__dirname, '../')
......@@ -149,4 +156,56 @@ describe('AMP Usage', () => {
)
})
})
describe('editing a page', () => {
let dynamicAppPort
let ampDynamic
beforeAll(async () => {
dynamicAppPort = await findPort()
ampDynamic = await launchApp(join(__dirname, '../'), dynamicAppPort)
})
afterAll(() => killApp(ampDynamic))
it('should detect the changes and display it', async () => {
let browser
try {
browser = await webdriver(dynamicAppPort, '/hmr/test')
const text = await browser.elementByCss('p').text()
expect(text).toBe('This is the hot AMP page.')
const hmrTestPagePath = join(
__dirname,
'../',
'pages',
'hmr',
'test.js'
)
const originalContent = readFileSync(hmrTestPagePath, 'utf8')
const editedContent = originalContent.replace(
'This is the hot AMP page',
'This is a cold AMP page'
)
// change the content
writeFileSync(hmrTestPagePath, editedContent, 'utf8')
await check(
() => getBrowserBodyText(browser),
/This is a cold AMP page/
)
// add the original content
writeFileSync(hmrTestPagePath, originalContent, 'utf8')
await check(
() => getBrowserBodyText(browser),
/This is the hot AMP page/
)
} finally {
if (browser) {
browser.close()
}
}
})
})
})
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