rsnext/packages/next/server/hot-reloader.ts

510 lines
15 KiB
TypeScript
Raw Normal View History

import { getOverlayMiddleware } from '@next/react-dev-overlay/lib/middleware'
import { NextHandleFunction } from 'connect'
import { IncomingMessage, ServerResponse } from 'http'
import WebpackHotMiddleware from 'next/dist/compiled/webpack-hot-middleware'
import { join, normalize, relative as relativePath, sep } from 'path'
import { UrlObject } from 'url'
import webpack from 'webpack'
import { createEntrypoints, createPagesMapping } from '../build/entries'
import { watchCompilers } from '../build/output'
import getBaseWebpackConfig from '../build/webpack-config'
import { API_ROUTE, NEXT_PROJECT_ROOT_DIST_CLIENT } from '../lib/constants'
import { recursiveDelete } from '../lib/recursive-delete'
import {
BLOCKED_PAGES,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
} from '../next-server/lib/constants'
import { __ApiPreviewProps } from '../next-server/server/api-utils'
import { route } from '../next-server/server/router'
import errorOverlayMiddleware from './lib/error-overlay-middleware'
import { findPageFile } from './lib/find-page-file'
import onDemandEntryHandler, {
entries,
BUILDING,
} from './on-demand-entry-handler'
Fix pages/index.js and pages/index/index.js behavior (#13699) Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently. It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened: - `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx` - `denormalizePagePath` is the inverse operation of `normalizePagePath`. Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle. Some potential follow up on this PR: - [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`. - There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all. - a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`. - It looks to me like some logic that's spread across the project can be centralized in 4 functions - `getRouteFromEntrypoint` (part of this PR) - its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`) - `getRouteFromPageFile` - its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`) It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly. - revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
2020-06-04 19:32:45 +02:00
import {
denormalizePagePath,
normalizePathSep,
} from '../next-server/server/normalize-page-path'
import getRouteFromEntrypoint from '../next-server/server/get-route-from-entrypoint'
import { isWriteable } from '../build/is-writeable'
import { ClientPagesLoaderOptions } from '../build/webpack/loaders/next-client-pages-loader'
import { stringify } from 'querystring'
export async function renderScriptError(res: ServerResponse, error: Error) {
// Asks CDNs and others to not to cache the errored page
res.setHeader(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
if (
(error as any).code === 'ENOENT' ||
error.message === 'INVALID_BUILD_ID'
) {
res.statusCode = 404
res.end('404 - Not Found')
return
}
console.error(error.stack)
res.statusCode = 500
res.end('500 - Internal Error')
}
2018-10-02 00:55:31 +02:00
function addCorsSupport(req: IncomingMessage, res: ServerResponse) {
const isApiRoute = req.url!.match(API_ROUTE)
// API routes handle their own CORS headers
if (isApiRoute) {
return { preflight: false }
}
2018-10-02 00:55:31 +02:00
if (!req.headers.origin) {
return { preflight: false }
}
res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET')
// Based on https://github.com/primus/access-control/blob/4cf1bc0e54b086c91e6aa44fb14966fa5ef7549c/index.js#L158
if (req.headers['access-control-request-headers']) {
res.setHeader(
'Access-Control-Allow-Headers',
req.headers['access-control-request-headers'] as string
)
2018-10-02 00:55:31 +02:00
}
if (req.method === 'OPTIONS') {
res.writeHead(200)
res.end()
return { preflight: true }
}
return { preflight: false }
}
const matchNextPageBundleRequest = route(
'/_next/static/pages/:path*.js(\\.map|)'
)
// Recursively look up the issuer till it ends up at the root
function findEntryModule(issuer: any): any {
if (issuer.issuer) {
return findEntryModule(issuer.issuer)
}
return issuer
}
function erroredPages(compilation: webpack.compilation.Compilation) {
const failedPages: { [page: string]: any[] } = {}
for (const error of compilation.errors) {
if (!error.origin) {
continue
}
const entryModule = findEntryModule(error.origin)
const { name } = entryModule
if (!name) {
continue
}
// Only pages have to be reloaded
if (!getRouteFromEntrypoint(name)) {
continue
}
const enhancedName = getRouteFromEntrypoint(name)
if (!enhancedName) {
continue
}
if (!failedPages[enhancedName]) {
failedPages[enhancedName] = []
}
failedPages[enhancedName].push(error)
}
return failedPages
}
2016-10-14 17:05:08 +02:00
export default class HotReloader {
private dir: string
private buildId: string
private middlewares: any[]
private pagesDir: string
private webpackHotMiddleware:
| (NextHandleFunction & WebpackHotMiddleware.EventStream)
| null
private config: any
private stats: any
private serverStats: any
private serverPrevDocumentHash: string | null
private prevChunkNames?: Set<any>
private onDemandEntries: any
private previewProps: __ApiPreviewProps
private watcher: any
constructor(
dir: string,
{
config,
pagesDir,
buildId,
previewProps,
}: {
config: object
pagesDir: string
buildId: string
previewProps: __ApiPreviewProps
}
) {
this.buildId = buildId
2016-10-17 09:05:46 +02:00
this.dir = dir
this.middlewares = []
this.pagesDir = pagesDir
this.webpackHotMiddleware = null
2016-10-19 14:41:45 +02:00
this.stats = null
this.serverStats = null
this.serverPrevDocumentHash = null
this.config = config
this.previewProps = previewProps
2016-10-17 09:05:46 +02:00
}
public async run(
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlObject
) {
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
// Usually CORS support is not needed for the hot-reloader (this is dev only feature)
// With when the app runs for multi-zones support behind a proxy,
// the current page is trying to access this URL via assetPrefix.
// That's when the CORS support is needed.
const { preflight } = addCorsSupport(req, res)
if (preflight) {
return
}
// When a request comes in that is a page bundle, e.g. /_next/static/<buildid>/pages/index.js
// we have to compile the page using on-demand-entries, this middleware will handle doing that
// by adding the page to on-demand-entries, waiting till it's done
// and then the bundle will be served like usual by the actual route in server/index.js
const handlePageBundleRequest = async (
pageBundleRes: ServerResponse,
parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl
const params: { path: string[] } | null = matchNextPageBundleRequest(
pathname
)
if (!params) {
return {}
}
Fix pages/index.js and pages/index/index.js behavior (#13699) Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently. It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened: - `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx` - `denormalizePagePath` is the inverse operation of `normalizePagePath`. Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle. Some potential follow up on this PR: - [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`. - There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all. - a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`. - It looks to me like some logic that's spread across the project can be centralized in 4 functions - `getRouteFromEntrypoint` (part of this PR) - its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`) - `getRouteFromPageFile` - its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`) It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly. - revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
2020-06-04 19:32:45 +02:00
const page = denormalizePagePath(`/${params.path.join('/')}`)
if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) {
try {
await this.ensurePage(page)
} catch (error) {
await renderScriptError(pageBundleRes, error)
return { finished: true }
}
const errors = await this.getCompilationErrors(page)
if (errors.length > 0) {
await renderScriptError(pageBundleRes, errors[0])
return { finished: true }
}
}
return {}
}
const { finished } = await handlePageBundleRequest(res, parsedUrl)
for (const fn of this.middlewares) {
await new Promise((resolve, reject) => {
fn(req, res, (err: Error) => {
if (err) return reject(err)
resolve()
})
})
}
return { finished }
2016-10-17 09:05:46 +02:00
}
private async clean(): Promise<void> {
return recursiveDelete(join(this.dir, this.config.distDir), /^cache/)
}
private async getWebpackConfig() {
const pagePaths = await Promise.all([
findPageFile(this.pagesDir, '/_app', this.config.pageExtensions),
findPageFile(this.pagesDir, '/_document', this.config.pageExtensions),
])
const pages = createPagesMapping(
2020-05-18 21:24:37 +02:00
pagePaths.filter((i) => i !== null) as string[],
this.config.pageExtensions
)
const entrypoints = createEntrypoints(
pages,
'server',
this.buildId,
this.previewProps,
this.config,
[]
)
let additionalClientEntrypoints: { [file: string]: string } = {}
additionalClientEntrypoints[CLIENT_STATIC_FILES_RUNTIME_AMP] =
`.${sep}` +
relativePath(
this.dir,
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,
isServer: false,
config: this.config,
buildId: this.buildId,
pagesDir: this.pagesDir,
entrypoints: { ...entrypoints.client, ...additionalClientEntrypoints },
}),
getBaseWebpackConfig(this.dir, {
dev: true,
isServer: true,
config: this.config,
buildId: this.buildId,
pagesDir: this.pagesDir,
entrypoints: entrypoints.server,
}),
])
}
public async start(): Promise<void> {
await this.clean()
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
const configs = await this.getWebpackConfig()
for (const config of configs) {
const defaultEntry = config.entry
config.entry = async (...args) => {
// @ts-ignore entry is always a functon
const entrypoints = await defaultEntry(...args)
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
const isClientCompilation = config.name === 'client'
await Promise.all(
Object.keys(entries).map(async (page) => {
if (isClientCompilation && page.match(API_ROUTE)) {
return
}
const {
serverBundlePath,
clientBundlePath,
absolutePagePath,
} = entries[page]
const pageExists = await isWriteable(absolutePagePath)
if (!pageExists) {
// page was removed
delete entries[page]
return
}
2016-10-17 09:05:46 +02:00
entries[page].status = BUILDING
const pageLoaderOpts: ClientPagesLoaderOptions = {
page,
absolutePagePath,
}
entrypoints[
isClientCompilation ? clientBundlePath : serverBundlePath
] = isClientCompilation
? `next-client-pages-loader?${stringify(pageLoaderOpts)}!`
: absolutePagePath
})
)
return entrypoints
}
}
const multiCompiler = webpack(configs)
watchCompilers(multiCompiler.compilers[0], multiCompiler.compilers[1])
// This plugin watches for changes to _document.js and notifies the client side that it should reload the page
multiCompiler.compilers[1].hooks.done.tap(
'NextjsHotReloaderForServer',
2020-05-18 21:24:37 +02:00
(stats) => {
this.serverStats = stats
2016-10-24 09:22:15 +02:00
const { compilation } = stats
// We only watch `_document` for changes on the server compilation
// the rest of the files will be triggered by the client compilation
const documentChunk = compilation.chunks.find(
(c) => c.name === normalize(`pages/_document`)
)
// If the document chunk can't be found we do nothing
if (!documentChunk) {
console.warn('_document.js chunk not found')
return
}
// Initial value
if (this.serverPrevDocumentHash === null) {
this.serverPrevDocumentHash = documentChunk.hash
return
}
// If _document.js didn't change we don't trigger a reload
if (documentChunk.hash === this.serverPrevDocumentHash) {
return
}
// Notify reload to reload the page, as _document.js was changed (different hash)
this.send('reloadPage')
this.serverPrevDocumentHash = documentChunk.hash
}
)
2016-10-14 17:05:08 +02:00
multiCompiler.compilers[0].hooks.done.tap(
'NextjsHotReloaderForClient',
2020-05-18 21:24:37 +02:00
(stats) => {
const { compilation } = stats
const chunkNames = new Set(
compilation.chunks
2020-05-18 21:24:37 +02:00
.map((c) => c.name)
.filter((name) => !!getRouteFromEntrypoint(name))
)
if (this.prevChunkNames) {
// detect chunks which have to be replaced with a new template
// e.g, pages/index.js <-> pages/_error.js
const addedPages = diff(chunkNames, this.prevChunkNames!)
const removedPages = diff(this.prevChunkNames!, chunkNames)
if (addedPages.size > 0) {
for (const addedPage of addedPages) {
Fix pages/index.js and pages/index/index.js behavior (#13699) Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently. It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened: - `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx` - `denormalizePagePath` is the inverse operation of `normalizePagePath`. Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle. Some potential follow up on this PR: - [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`. - There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all. - a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`. - It looks to me like some logic that's spread across the project can be centralized in 4 functions - `getRouteFromEntrypoint` (part of this PR) - its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`) - `getRouteFromPageFile` - its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`) It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly. - revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
2020-06-04 19:32:45 +02:00
const page = getRouteFromEntrypoint(addedPage)
this.send('addedPage', page)
}
}
if (removedPages.size > 0) {
for (const removedPage of removedPages) {
Fix pages/index.js and pages/index/index.js behavior (#13699) Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently. It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened: - `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx` - `denormalizePagePath` is the inverse operation of `normalizePagePath`. Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle. Some potential follow up on this PR: - [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`. - There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all. - a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`. - It looks to me like some logic that's spread across the project can be centralized in 4 functions - `getRouteFromEntrypoint` (part of this PR) - its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`) - `getRouteFromPageFile` - its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`) It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly. - revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
2020-06-04 19:32:45 +02:00
const page = getRouteFromEntrypoint(removedPage)
this.send('removedPage', page)
}
}
}
2016-10-24 17:20:50 +02:00
this.stats = stats
this.prevChunkNames = chunkNames
}
)
2016-10-19 14:41:45 +02:00
this.webpackHotMiddleware = WebpackHotMiddleware(
multiCompiler.compilers[0],
{
path: '/_next/webpack-hmr',
log: false,
heartbeat: 2500,
}
)
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
let booted = false
this.watcher = await new Promise((resolve) => {
const watcher = multiCompiler.watch(
// @ts-ignore webpack supports an array of watchOptions when using a multiCompiler
configs.map((config) => config.watchOptions!),
// Errors are handled separately
(_err: any) => {
if (!booted) {
booted = true
resolve(watcher)
}
}
)
})
this.onDemandEntries = onDemandEntryHandler(this.watcher, multiCompiler, {
pagesDir: this.pagesDir,
pageExtensions: this.config.pageExtensions,
...(this.config.onDemandEntries as {
maxInactiveAge: number
pagesBufferLength: number
}),
})
this.middlewares = [
// must come before hotMiddleware
this.onDemandEntries.middleware(),
this.webpackHotMiddleware,
errorOverlayMiddleware({ dir: this.dir }),
getOverlayMiddleware({
rootDirectory: this.dir,
stats: () => this.stats,
serverStats: () => this.serverStats,
}),
]
2016-10-14 17:05:08 +02:00
}
public async stop(): Promise<void> {
return new Promise((resolve, reject) => {
this.watcher.close((err: any) => (err ? reject(err) : resolve()))
2016-10-14 17:05:08 +02:00
})
}
public async getCompilationErrors(page: string) {
Fix pages/index.js and pages/index/index.js behavior (#13699) Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently. It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened: - `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx` - `denormalizePagePath` is the inverse operation of `normalizePagePath`. Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle. Some potential follow up on this PR: - [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`. - There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all. - a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`. - It looks to me like some logic that's spread across the project can be centralized in 4 functions - `getRouteFromEntrypoint` (part of this PR) - its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`) - `getRouteFromPageFile` - its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`) It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly. - revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
2020-06-04 19:32:45 +02:00
const normalizedPage = normalizePathSep(page)
if (this.stats.hasErrors()) {
const { compilation } = this.stats
const failedPages = erroredPages(compilation)
// If there is an error related to the requesting page we display it instead of the first error
if (
failedPages[normalizedPage] &&
failedPages[normalizedPage].length > 0
) {
return failedPages[normalizedPage]
2016-10-19 14:41:45 +02:00
}
// If none were found we still have to show the other errors
return this.stats.compilation.errors
2016-10-19 14:41:45 +02:00
}
return []
2016-10-19 14:41:45 +02:00
}
private send(action: string, ...args: any[]): void {
this.webpackHotMiddleware!.publish({ action, data: args })
2016-10-24 09:22:15 +02:00
}
public async ensurePage(page: string) {
// Make sure we don't re-build or dispose prebuilt pages
if (page !== '/_error' && BLOCKED_PAGES.indexOf(page) !== -1) {
return
}
return this.onDemandEntries.ensurePage(page)
}
2016-10-14 17:05:08 +02:00
}
2016-10-19 14:41:45 +02:00
function diff(a: Set<any>, b: Set<any>) {
2020-05-18 21:24:37 +02:00
return new Set([...a].filter((v) => !b.has(v)))
2016-10-24 09:22:15 +02:00
}