Unverified Commit 450d4bd0 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Experimental: React Refresh Support (#12008)

* Add Fast Refresh Support

* Add Basic Acceptance Test

* Increase delay

* fix version

* Ignore test files

* Update packages/next/build/webpack/loaders/next-babel-loader.js

* Copy tests

* Redo test style

* drop directory

* fix compile

* fix remove function

* Update helpers
parent 86236bc7
......@@ -6,3 +6,4 @@ examples/with-ioc/**
examples/with-kea/**
packages/next/compiled/**/*
packages/react-refresh-utils/**/*.js
**/__tmp__/**
......@@ -5,3 +5,4 @@ node_modules
packages/next/compiled/**
packages/react-refresh-utils/**/*.js
packages/react-refresh-utils/**/*.d.ts
**/__tmp__/**
......@@ -41,6 +41,7 @@
"@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "0.18.0",
"@types/cheerio": "0.22.16",
"@types/fs-extra": "8.1.0",
"@types/http-proxy": "1.17.3",
"@types/jest": "24.0.13",
"@types/string-hash": "1.1.1",
......
......@@ -133,7 +133,12 @@ export function createEntrypoints(
const pageLoaderOpts: ClientPagesLoaderOptions = {
page,
absolutePagePath,
hotRouterUpdates: dev, // Hot router updates only apply in development mode
hotRouterUpdates:
// Hot router updates only apply in development mode
dev &&
// However, React Refresh has its own hot module runtime, so we can't
// let them collide.
config.experimental.reactRefresh !== true,
}
const pageLoader = `next-client-pages-loader?${stringify(
pageLoaderOpts
......
import ReactRefreshWebpackPlugin from '@next/react-refresh-utils/ReactRefreshWebpackPlugin'
import crypto from 'crypto'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import { readFileSync } from 'fs'
......@@ -151,6 +152,10 @@ export default async function getBaseWebpackConfig(
}
}
}
const hasReactRefresh =
dev && !isServer && config.experimental.reactRefresh === true
const distDir = path.join(dir, config.distDir)
const defaultLoaders = {
babel: {
......@@ -164,6 +169,7 @@ export default async function getBaseWebpackConfig(
babelPresetPlugins,
hasModern: !!config.experimental.modern,
development: dev,
hasReactRefresh,
},
},
// Backwards compat
......@@ -759,12 +765,21 @@ export default async function getBaseWebpackConfig(
},
},
defaultLoaders.babel,
hasReactRefresh
? require.resolve('@next/react-refresh-utils/loader')
: '',
].filter(Boolean)
: hasReactRefresh
? [
defaultLoaders.babel,
require.resolve('@next/react-refresh-utils/loader'),
]
: defaultLoaders.babel,
},
].filter(Boolean),
},
plugins: [
hasReactRefresh && new ReactRefreshWebpackPlugin(),
// This plugin makes sure `output.filename` is used for entry chunks
new ChunkNamesPlugin(),
new webpack.DefinePlugin({
......
import babelLoader from 'next/dist/compiled/babel-loader'
import { basename, join } from 'path'
import hash from 'next/dist/compiled/string-hash'
import { basename, join } from 'path'
// increment 'j' to invalidate cache
// increment 'k' to invalidate cache
// eslint-disable-next-line no-useless-concat
const cacheKey = 'babel-cache-' + 'j' + '-'
const cacheKey = 'babel-cache-' + 'k' + '-'
const nextBabelPreset = require('../../babel/preset')
const getModernOptions = (babelOptions = {}) => {
......@@ -59,6 +59,7 @@ module.exports = babelLoader.custom(babel => {
hasModern: opts.hasModern,
babelPresetPlugins: opts.babelPresetPlugins,
development: opts.development,
hasReactRefresh: opts.hasReactRefresh,
}
const filename = join(opts.cwd, 'noop.js')
const loader = Object.assign(
......@@ -73,6 +74,7 @@ module.exports = babelLoader.custom(babel => {
(opts.hasModern ? '-has-modern' : '') +
'-new-polyfills' +
(opts.development ? '-development' : '-production') +
(opts.hasReactRefresh ? '-react-refresh' : '') +
JSON.stringify(
babel.loadPartialConfig({
filename,
......@@ -95,6 +97,7 @@ module.exports = babelLoader.custom(babel => {
delete loader.pagesDir
delete loader.babelPresetPlugins
delete loader.development
delete loader.hasReactRefresh
return { loader, custom }
},
config(
......@@ -108,6 +111,7 @@ module.exports = babelLoader.custom(babel => {
pagesDir,
babelPresetPlugins,
development,
hasReactRefresh,
},
}
) {
......@@ -135,6 +139,14 @@ module.exports = babelLoader.custom(babel => {
options.plugins = options.plugins || []
if (hasReactRefresh) {
const reactRefreshPlugin = babel.createConfigItem(
[require('react-refresh/babel')],
{ type: 'plugin' }
)
options.plugins.unshift(reactRefreshPlugin)
}
if (!isServer && isPageFile) {
const pageConfigPlugin = babel.createConfigItem(
[require('../../babel/plugins/next-page-config')],
......
......@@ -6,6 +6,7 @@ import {
CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
IS_BUNDLED_PAGE_REGEX,
ROUTE_NAME_REGEX,
} from '../../../next-server/lib/constants'
......@@ -79,6 +80,11 @@ export default class BuildManifestPlugin {
)
const polyfillFiles: string[] = polyfillChunk ? polyfillChunk.files : []
const reactRefreshChunk = chunks.find(
c => c.name === CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
)
assetMap.devFiles.push(...(reactRefreshChunk?.files ?? []))
for (const filePath of Object.keys(compilation.assets)) {
const path = filePath.replace(/\\/g, '/')
if (/^static\/development\/dll\//.test(path)) {
......
......@@ -26,12 +26,12 @@
// can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
import { getEventSourceWrapper } from './eventsource'
import formatWebpackMessages from './format-webpack-messages'
import fetch from 'next/dist/build/polyfills/unfetch'
import * as ErrorOverlay from 'next/dist/compiled/react-error-overlay'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { getEventSourceWrapper } from './eventsource'
import formatWebpackMessages from './format-webpack-messages'
import { rewriteStacktrace } from './source-map-support'
import fetch from 'next/dist/build/polyfills/unfetch'
// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
......@@ -365,6 +365,15 @@ function tryApplyUpdates(onHotUpdateSuccess) {
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdates()
} else {
if (process.env.__NEXT_TEST_MODE) {
afterApplyUpdates(() => {
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB()
self.__NEXT_HMR_CB = null
}
})
}
}
}
......
......@@ -21,6 +21,8 @@ export const AMP_RENDER_TARGET = '__NEXT_AMP_RENDER_TARGET__'
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/react-refresh.js
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/react-refresh.js`
// static/runtime/amp.js
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/amp.js`
// static/runtime/webpack.js
......
......@@ -55,6 +55,7 @@ const defaultConfig: { [key: string]: any } = {
sassOptions: {},
pageEnv: false,
measureFid: false,
reactRefresh: false,
},
future: {
excludeDefaultMomentLocales: false,
......
......@@ -75,6 +75,7 @@
"@babel/preset-typescript": "7.7.2",
"@babel/runtime": "7.7.2",
"@babel/types": "7.7.4",
"@next/react-refresh-utils": "9.3.6-canary.4",
"babel-plugin-syntax-jsx": "6.18.0",
"babel-plugin-transform-define": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.4.24",
......@@ -92,6 +93,7 @@
"prop-types": "15.7.2",
"prop-types-exact": "1.2.0",
"react-is": "16.8.6",
"react-refresh": "0.8.1",
"resolve-url-loader": "3.1.1",
"sass-loader": "8.0.2",
"style-loader": "1.0.0",
......
......@@ -14,6 +14,7 @@ import { recursiveDelete } from '../lib/recursive-delete'
import {
BLOCKED_PAGES,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
IS_BUNDLED_PAGE_REGEX,
ROUTE_NAME_REGEX,
} from '../next-server/lib/constants'
......@@ -268,6 +269,10 @@ export default class HotReloader {
join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')
)
additionalClientEntrypoints[
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
] = require.resolve(`@next/react-refresh-utils/runtime`)
return Promise.all([
getBaseWebpackConfig(this.dir, {
dev: true,
......@@ -489,7 +494,7 @@ export default class HotReloader {
pagesDir: this.pagesDir,
reload: this.reload.bind(this),
pageExtensions: this.config.pageExtensions,
hotRouterUpdates: true,
hotRouterUpdates: this.config.experimental.reactRefresh !== true,
...(this.config.onDemandEntries as {
maxInactiveAge: number
pagesBufferLength: number
......
/* global jasmine */
/* eslint-env jest */
import { sandbox } from './helpers'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
test('basic: can edit a component without losing state', async () => {
const [session, cleanup] = await sandbox()
await session.patch(
'index.js',
`
import { useCallback, useState } from 'react'
export default function Index() {
const [count, setCount] = useState(0)
const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</main>
)
}
`
)
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('1')
await session.patch(
'index.js',
`
import { useCallback, useState } from 'react'
export default function Index() {
const [count, setCount] = useState(0)
const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</main>
)
}
`
)
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Count: 1')
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Count: 2')
await cleanup()
})
import * as fs from 'fs-extra'
import nanoid from 'nanoid'
import { findPort, killApp, launchApp } from 'next-test-utils'
import webdriver from 'next-webdriver'
import path from 'path'
const rootSandboxDirectory = path.join(__dirname, '__tmp__')
export async function sandbox(id = nanoid()) {
const sandboxDirectory = path.join(rootSandboxDirectory, id)
const pagesDirectory = path.join(sandboxDirectory, 'pages')
await fs.remove(sandboxDirectory)
await fs.mkdirp(pagesDirectory)
await fs.writeFile(
path.join(pagesDirectory, 'index.js'),
`export { default } from '../index';`
)
await fs.writeFile(
path.join(sandboxDirectory, 'index.js'),
`export default () => 'new sandbox';`
)
const appPort = await findPort()
const app = await launchApp(sandboxDirectory, appPort)
const browser = await webdriver(appPort, '/')
return [
{
async patch(fileName, content) {
// Register an event for HMR completion
await browser.executeScript(function() {
window.__HMR_STATE = 'pending'
var timeout = setTimeout(() => {
window.__HMR_STATE = 'timeout'
}, 5250)
window.__NEXT_HMR_CB = function() {
clearTimeout(timeout)
window.__HMR_STATE = 'success'
}
})
// Update the file on filesystem
const fullFileName = path.join(sandboxDirectory, fileName)
const dir = path.dirname(fullFileName)
await fs.mkdirp(dir)
await fs.writeFile(fullFileName, content)
for (;;) {
const status = await browser.executeScript(() => window.__HMR_STATE)
if (!status) {
await new Promise(resolve => setTimeout(resolve, 750))
// Wait for application to re-hydrate:
await browser.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1]
if (window.__NEXT_HYDRATED) {
callback()
} else {
var timeout = setTimeout(callback, 10 * 1000)
window.__NEXT_HYDRATED_CB = function() {
clearTimeout(timeout)
callback()
}
}
})
console.log('Application re-loaded.')
// Slow down tests a bit:
await new Promise(resolve => setTimeout(resolve, 250))
return false
}
if (status === 'success') {
console.log('Hot update complete.')
break
}
if (status !== 'pending') {
throw new Error(`Application is in inconsistent state: ${status}.`)
}
await new Promise(resolve => setTimeout(resolve, 30))
}
// Slow down tests a bit:
await new Promise(resolve => setTimeout(resolve, 250))
return true
},
async remove(fileName) {
const fullFileName = path.join(sandboxDirectory, fileName)
await fs.remove(fullFileName)
},
async evaluate() {
const input = arguments[0]
if (typeof input === 'function') {
const result = await browser.executeScript(input)
await new Promise(resolve => setTimeout(resolve, 30))
return result
} else {
throw new Error(
`You must pass a function to be evaluated in the browser.`
)
}
},
},
function cleanup() {
async function _cleanup() {
await browser.close()
await killApp(app)
}
_cleanup().catch(() => {})
},
]
}
module.exports = {
experimental: {
reactRefresh: true,
},
}
interface Chain {
elementByCss: () => Chain
elementByCss: (selector: string) => Chain
elementById: () => Chain
getValue: () => Chain
text: () => Chain
......
......@@ -2603,6 +2603,13 @@
resolved "https://registry.yarnpkg.com/@types/fresh/-/fresh-0.5.0.tgz#4d09231027d69c4369cfb01a9af5ef083d0d285f"
integrity sha512-eGPzuyc6wZM3sSHJdF7NM2jW6B/xsB014Rqg/iDa6xY02mlfy1w/TE2sYhR8vbHxkzJOXiGo6NuIk3xk35vsgQ==
"@types/fs-extra@8.1.0":
version "8.1.0"
resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-8.1.0.tgz#1114834b53c3914806cd03b3304b37b3bd221a4d"
integrity sha512-UoOfVEzAUpeSPmjm7h1uk5MH6KZma2z2O7a75onTGjnNvAvMVrPzPL/vBbT65iIGHWj6rokwfmYcmxmlSf2uwg==
dependencies:
"@types/node" "*"
"@types/glob@*", "@types/glob@^7.1.1":
version "7.1.1"
resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575"
......
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