Unverified Commit 2c9b484f authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Auto-restart dev server when next.config.js changes (#47912)

This is a follow-up PR on https://github.com/vercel/next.js/pull/46577
after it got nasty conflicts.

Basically, just restart `dev` when `next.config.ts` it will just restart
instead of printing that message asking you to restart.
fix NEXT-639
parent af694f66
...@@ -88,20 +88,22 @@ process.on('SIGTERM', handleSessionStop) ...@@ -88,20 +88,22 @@ process.on('SIGTERM', handleSessionStop)
let unwatchConfigFiles: () => void let unwatchConfigFiles: () => void
function watchConfigFiles(dirToWatch: string) { function watchConfigFiles(
dirToWatch: string,
onChange = (filename: string) =>
Log.warn(
`\n> Found a change in ${path.basename(
filename
)}. Restart the server to see the changes in effect.`
)
) {
if (unwatchConfigFiles) { if (unwatchConfigFiles) {
unwatchConfigFiles() unwatchConfigFiles()
} }
const wp = new Watchpack() const wp = new Watchpack()
wp.watch({ files: CONFIG_FILES.map((file) => path.join(dirToWatch, file)) }) wp.watch({ files: CONFIG_FILES.map((file) => path.join(dirToWatch, file)) })
wp.on('change', (filename) => { wp.on('change', onChange)
console.log(
`\n> Found a change in ${path.basename(
filename
)}. Restart the server to see the changes in effect.`
)
})
unwatchConfigFiles = () => wp.close() unwatchConfigFiles = () => wp.close()
} }
...@@ -285,12 +287,26 @@ const nextDev: CliCommand = async (argv) => { ...@@ -285,12 +287,26 @@ const nextDev: CliCommand = async (argv) => {
} }
return server return server
} else { } else {
let cleanupFns: (() => Promise<void> | void)[] = []
const runDevServer = async () => {
const oldCleanupFns = cleanupFns
cleanupFns = []
await Promise.allSettled(oldCleanupFns.map((fn) => fn()))
try { try {
let shouldFilter = false let shouldFilter = false
let devServerTeardown: (() => Promise<void>) | undefined let devServerTeardown: (() => Promise<void>) | undefined
let config: NextConfig | undefined let config: NextConfig | undefined
watchConfigFiles(devServerOptions.dir) watchConfigFiles(devServerOptions.dir, (filename) => {
Log.warn(
`\n> Found a change in ${path.basename(
filename
)}. Restarting the server to apply the changes...`
)
runDevServer()
})
cleanupFns.push(unwatchConfigFiles)
const setupFork = async (newDir?: string) => { const setupFork = async (newDir?: string) => {
// if we're using workers we can auto restart on config changes // if we're using workers we can auto restart on config changes
...@@ -373,6 +389,7 @@ const nextDev: CliCommand = async (argv) => { ...@@ -373,6 +389,7 @@ const nextDev: CliCommand = async (argv) => {
) )
} }
} }
cleanupFns.push(() => devServerTeardown?.())
await setupFork() await setupFork()
await preflight() await preflight()
...@@ -386,6 +403,7 @@ const nextDev: CliCommand = async (argv) => { ...@@ -386,6 +403,7 @@ const nextDev: CliCommand = async (argv) => {
: [] : []
const instrumentationFileWatcher = new Watchpack({}) const instrumentationFileWatcher = new Watchpack({})
cleanupFns.push(() => instrumentationFileWatcher.close())
instrumentationFileWatcher.watch({ instrumentationFileWatcher.watch({
files: instrumentationFilePaths, files: instrumentationFilePaths,
...@@ -450,6 +468,7 @@ const nextDev: CliCommand = async (argv) => { ...@@ -450,6 +468,7 @@ const nextDev: CliCommand = async (argv) => {
return !(entry.split('/').length <= watchedEntryLength) return !(entry.split('/').length <= watchedEntryLength)
}, },
}) })
cleanupFns.push(() => projectFolderWatcher.close())
projectFolderWatcher.watch({ directories: [parentDir], startTime: 0 }) projectFolderWatcher.watch({ directories: [parentDir], startTime: 0 })
...@@ -517,6 +536,8 @@ const nextDev: CliCommand = async (argv) => { ...@@ -517,6 +536,8 @@ const nextDev: CliCommand = async (argv) => {
process.exit(1) process.exit(1)
} }
} }
await runDevServer()
}
} }
export { nextDev } export { nextDev }
import { createNext } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
import { NextInstance } from 'test/lib/next-modes/base'
describe('watch-config-file', () => { createNextDescribe(
let next: NextInstance 'watch-config-file',
{
beforeAll(async () => {
next = await createNext({
files: { files: {
'pages/index.js': ` 'pages/index.js': `
export default function Page() { export default function Page() {
...@@ -21,28 +18,37 @@ describe('watch-config-file', () => { ...@@ -21,28 +18,37 @@ describe('watch-config-file', () => {
module.exports = nextConfig module.exports = nextConfig
`, `,
}, },
dependencies: {}, },
skipStart: true, ({ next }) => {
})
})
afterAll(() => next.destroy())
it('should output config file change', async () => { it('should output config file change', async () => {
// next dev test-dir await check(
await next.start(true) async () => next.cliOutput,
let i = 1 /compiled client and server successfully/
)
await check(async () => {
await next.patchFile( await next.patchFile(
'next.config.js', 'next.config.js',
` `
/** changed - ${i} **/
const nextConfig = { const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
} }
module.exports = nextConfig` module.exports = nextConfig`
) )
return next.cliOutput
}, /Found a change in next.config.js. Restart the server to see the changes in effect./) await check(
async () => next.cliOutput,
/Found a change in next\.config\.js\. Restarting the server to apply the changes\.\.\./
)
await check(() => next.fetch('/about').then((res) => res.status), 200)
}) })
}) }
)
...@@ -88,7 +88,7 @@ export class NextDevInstance extends NextInstance { ...@@ -88,7 +88,7 @@ export class NextDevInstance extends NextInstance {
msg, msg,
}) })
} }
this.off('stdout', readyCb) // server might reload so we keep listening
resolve() resolve()
} }
} }
......
...@@ -551,7 +551,7 @@ export async function check( ...@@ -551,7 +551,7 @@ export async function check(
for (let tries = 0; tries < maxRetries; tries++) { for (let tries = 0; tries < maxRetries; tries++) {
try { try {
content = await contentFn() content = await contentFn()
if (typeof regex === 'string') { if (typeof regex !== typeof /regex/) {
if (regex === content) { if (regex === content) {
return true return true
} }
......
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