Unverified Commit 754ec664 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Run Fast Refresh Loader in Babel Loader (#15851)

Next.js plugins like `@next/mdx` inject additional webpack loaders to compile files, but they omit the necessary loader for Fast Refresh to work.

Instead of making these files deopt out of Fast Refresh, we can automatically detect and inject the loader in these cases.

Fixes #13574
parent fcc4d8cd
...@@ -27,6 +27,7 @@ import { ...@@ -27,6 +27,7 @@ import {
import { execOnce } from '../next-server/lib/utils' import { execOnce } from '../next-server/lib/utils'
import { findPageFile } from '../server/lib/find-page-file' import { findPageFile } from '../server/lib/find-page-file'
import { WebpackEntrypoints } from './entries' import { WebpackEntrypoints } from './entries'
import * as Log from './output/log'
import { import {
collectPlugins, collectPlugins,
PluginMetaData, PluginMetaData,
...@@ -138,6 +139,46 @@ type ClientEntries = { ...@@ -138,6 +139,46 @@ type ClientEntries = {
[key: string]: string | string[] [key: string]: string | string[]
} }
export function attachReactRefresh(
webpackConfig: webpack.Configuration,
targetLoader: webpack.RuleSetUseItem
) {
let injections = 0
const reactRefreshLoaderName = '@next/react-refresh-utils/loader'
const reactRefreshLoader = require.resolve(reactRefreshLoaderName)
webpackConfig.module?.rules.forEach((rule) => {
const curr = rule.use
// When the user has configured `defaultLoaders.babel` for a input file:
if (curr === targetLoader) {
++injections
rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem]
} else if (
Array.isArray(curr) &&
curr.some((r) => r === targetLoader) &&
// Check if loader already exists:
!curr.some(
(r) => r === reactRefreshLoader || r === reactRefreshLoaderName
)
) {
++injections
const idx = curr.findIndex((r) => r === targetLoader)
// Clone to not mutate user input
rule.use = [...curr]
// inject / input: [other, babel] output: [other, refresh, babel]:
rule.use.splice(idx, 0, reactRefreshLoader)
}
})
if (injections) {
Log.info(
`automatically enabled Fast Refresh for ${injections} custom loader${
injections > 1 ? 's' : ''
}`
)
}
}
export default async function getBaseWebpackConfig( export default async function getBaseWebpackConfig(
dir: string, dir: string,
{ {
...@@ -1180,6 +1221,11 @@ export default async function getBaseWebpackConfig( ...@@ -1180,6 +1221,11 @@ export default async function getBaseWebpackConfig(
await __overrideCssConfiguration(dir, !dev, webpackConfig) await __overrideCssConfiguration(dir, !dev, webpackConfig)
} }
// Inject missing React Refresh loaders so that development mode is fast:
if (hasReactRefresh) {
attachReactRefresh(webpackConfig, defaultLoaders.babel)
}
// check if using @zeit/next-typescript and show warning // check if using @zeit/next-typescript and show warning
if ( if (
isServer && isServer &&
......
...@@ -280,3 +280,41 @@ test('shows an overlay for a server-side error', async () => { ...@@ -280,3 +280,41 @@ test('shows an overlay for a server-side error', async () => {
await cleanup() await cleanup()
}) })
// https://github.com/vercel/next.js/issues/13574
test('custom loader (mdx) should have Fast Refresh enabled', async () => {
const files = new Map()
files.set(
'next.config.js',
`
const withMDX = require("@next/mdx")({
extension: /\\.mdx?$/,
});
module.exports = withMDX({
pageExtensions: ["js", "mdx"],
});
`
)
files.set('pages/index.mdx', `Hello World!`)
const [session, cleanup] = await sandbox(undefined, files, false)
expect(
await session.evaluate(() => document.querySelector('#__next').textContent)
).toBe('Hello World!')
let didNotReload = await session.patch('pages/index.mdx', `Hello Foo!`)
expect(didNotReload).toBe(true)
expect(await session.hasRedbox()).toBe(false)
expect(
await session.evaluate(() => document.querySelector('#__next').textContent)
).toBe('Hello Foo!')
didNotReload = await session.patch('pages/index.mdx', `Hello Bar!`)
expect(didNotReload).toBe(true)
expect(await session.hasRedbox()).toBe(false)
expect(
await session.evaluate(() => document.querySelector('#__next').textContent)
).toBe('Hello Bar!')
await cleanup()
})
...@@ -6,13 +6,18 @@ import path from 'path' ...@@ -6,13 +6,18 @@ import path from 'path'
const rootSandboxDirectory = path.join(__dirname, '__tmp__') const rootSandboxDirectory = path.join(__dirname, '__tmp__')
export async function sandbox(id = nanoid(), initialFiles = new Map()) { export async function sandbox(
id = nanoid(),
initialFiles = new Map(),
defaultFiles = true
) {
const sandboxDirectory = path.join(rootSandboxDirectory, id) const sandboxDirectory = path.join(rootSandboxDirectory, id)
const pagesDirectory = path.join(sandboxDirectory, 'pages') const pagesDirectory = path.join(sandboxDirectory, 'pages')
await fs.remove(sandboxDirectory) await fs.remove(sandboxDirectory)
await fs.mkdirp(pagesDirectory) await fs.mkdirp(pagesDirectory)
if (defaultFiles) {
await fs.writeFile( await fs.writeFile(
path.join(pagesDirectory, 'index.js'), path.join(pagesDirectory, 'index.js'),
`export { default } from '../index';` `export { default } from '../index';`
...@@ -21,7 +26,9 @@ export async function sandbox(id = nanoid(), initialFiles = new Map()) { ...@@ -21,7 +26,9 @@ export async function sandbox(id = nanoid(), initialFiles = new Map()) {
path.join(sandboxDirectory, 'index.js'), path.join(sandboxDirectory, 'index.js'),
`export default () => 'new sandbox';` `export default () => 'new sandbox';`
) )
}
for (const [k, v] of initialFiles.entries()) { for (const [k, v] of initialFiles.entries()) {
await fs.mkdirp(path.dirname(path.join(sandboxDirectory, k)))
await fs.writeFile(path.join(sandboxDirectory, k), v) await fs.writeFile(path.join(sandboxDirectory, k), v)
} }
......
/* eslint-env jest */
import { attachReactRefresh } from 'next/dist/build/webpack-config'
describe('webpack-config attachReactRefresh', () => {
it('should skip adding when unrelated', () => {
const input = { module: { rules: [{ use: 'a' }] } }
const expected = { module: { rules: [{ use: 'a' }] } }
attachReactRefresh(input, 'rr')
expect(input).toEqual(expected)
})
it('should skip adding when existing (shorthand)', () => {
const input = {
module: {
rules: [{ use: ['@next/react-refresh-utils/loader', 'rr'] }],
},
}
const expected = {
module: {
rules: [{ use: ['@next/react-refresh-utils/loader', 'rr'] }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toEqual(expected)
})
it('should skip adding when existing (longhand)', () => {
const input = {
module: {
rules: [
{ use: [require.resolve('@next/react-refresh-utils/loader'), 'rr'] },
],
},
}
const expected = {
module: {
rules: [
{ use: [require.resolve('@next/react-refresh-utils/loader'), 'rr'] },
],
},
}
attachReactRefresh(input, 'rr')
expect(input).toEqual(expected)
})
it('should add when missing (single, non-array)', () => {
const input = {
module: {
rules: [{ use: 'rr' }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
expect.stringMatching(/react-refresh-utils[\\/]loader\.js/),
'rr',
],
},
],
},
})
})
it('should add when missing (single, array)', () => {
const input = {
module: {
rules: [{ use: ['rr'] }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
expect.stringMatching(/react-refresh-utils[\\/]loader\.js/),
'rr',
],
},
],
},
})
})
it('should add when missing (before, array)', () => {
const input = {
module: {
rules: [{ use: ['bla', 'rr'] }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
'bla',
expect.stringMatching(/react-refresh-utils[\\/]loader\.js/),
'rr',
],
},
],
},
})
})
it('should add when missing (after, array)', () => {
const input = {
module: {
rules: [{ use: ['rr', 'bla'] }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
expect.stringMatching(/react-refresh-utils[\\/]loader\.js/),
'rr',
'bla',
],
},
],
},
})
})
it('should add when missing (multi, array)', () => {
const input = {
module: {
rules: [{ use: ['hehe', 'haha', 'rawr', 'rr', 'lol', 'bla'] }],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
'hehe',
'haha',
'rawr',
expect.stringMatching(/react-refresh-utils[\\/]loader\.js/),
'rr',
'lol',
'bla',
],
},
],
},
})
})
it('should skip when present (multi, array)', () => {
const input = {
module: {
rules: [
{
use: [
'hehe',
'haha',
'@next/react-refresh-utils/loader',
'rr',
'lol',
'bla',
],
},
],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
'hehe',
'haha',
'@next/react-refresh-utils/loader',
'rr',
'lol',
'bla',
],
},
],
},
})
})
it('should skip when present (multi, array, wrong order)', () => {
const input = {
module: {
rules: [
{
use: [
'hehe',
'haha',
'rr',
'lol',
'@next/react-refresh-utils/loader',
'bla',
],
},
],
},
}
attachReactRefresh(input, 'rr')
expect(input).toMatchObject({
module: {
rules: [
{
use: [
'hehe',
'haha',
'rr',
'lol',
'@next/react-refresh-utils/loader',
'bla',
],
},
],
},
})
})
})
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