Unverified Commit b80fdfb8 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update webpack server chunks output (#22697)

This updates to output server chunks to a nested folder to prevent bundling the entire folder when tracing. This also fixes the webpack 5 tests not actually using webpack 5 since https://github.com/vercel/next.js/pull/22583 since the webpack 5 enabling check didn't account for the test environment variable used to enable webpack 5. This also clears up some deprecation warnings from webpack 5 in the mini-css-extract-plugin.

Fixes: https://github.com/vercel/next.js/issues/21297
parent ac47795d
...@@ -788,7 +788,7 @@ export default async function getBaseWebpackConfig( ...@@ -788,7 +788,7 @@ export default async function getBaseWebpackConfig(
splitChunks: isServer ? false : splitChunksConfig, splitChunks: isServer ? false : splitChunksConfig,
runtimeChunk: isServer runtimeChunk: isServer
? isWebpack5 && !isLikeServerless ? isWebpack5 && !isLikeServerless
? { name: 'webpack-runtime' } ? { name: `${dev ? '' : 'chunks/'}webpack-runtime` }
: undefined : undefined
: { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK }, : { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK },
minimize: !(dev || isServer), minimize: !(dev || isServer),
...@@ -856,10 +856,15 @@ export default async function getBaseWebpackConfig( ...@@ -856,10 +856,15 @@ export default async function getBaseWebpackConfig(
}, },
} }
: {}), : {}),
path: outputPath, path:
isServer && isWebpack5 && !dev
? path.join(outputPath, 'chunks')
: outputPath,
// On the server we don't use the chunkhash // On the server we don't use the chunkhash
filename: isServer filename: isServer
? '[name].js' ? isWebpack5 && !dev
? '../[name].js'
: '[name].js'
: `static/chunks/[name]${dev ? '' : '-[chunkhash]'}.js`, : `static/chunks/[name]${dev ? '' : '-[chunkhash]'}.js`,
library: isServer ? undefined : '_N_E', library: isServer ? undefined : '_N_E',
libraryTarget: isServer ? 'commonjs2' : 'assign', libraryTarget: isServer ? 'commonjs2' : 'assign',
...@@ -1117,7 +1122,8 @@ export default async function getBaseWebpackConfig( ...@@ -1117,7 +1122,8 @@ export default async function getBaseWebpackConfig(
contextRegExp: /(next-server|next)[\\/]dist[\\/]/, contextRegExp: /(next-server|next)[\\/]dist[\\/]/,
}), }),
isServerless && isServer && new ServerlessPlugin(), isServerless && isServer && new ServerlessPlugin(),
isServer && new PagesManifestPlugin(isLikeServerless), isServer &&
new PagesManifestPlugin({ serverless: isLikeServerless, dev }),
!isWebpack5 && !isWebpack5 &&
target === 'server' && target === 'server' &&
isServer && isServer &&
...@@ -1141,8 +1147,12 @@ export default async function getBaseWebpackConfig( ...@@ -1141,8 +1147,12 @@ export default async function getBaseWebpackConfig(
(function () { (function () {
const { const {
FontStylesheetGatheringPlugin, FontStylesheetGatheringPlugin,
} = require('./webpack/plugins/font-stylesheet-gathering-plugin') } = require('./webpack/plugins/font-stylesheet-gathering-plugin') as {
return new FontStylesheetGatheringPlugin() FontStylesheetGatheringPlugin: typeof import('./webpack/plugins/font-stylesheet-gathering-plugin').FontStylesheetGatheringPlugin
}
return new FontStylesheetGatheringPlugin({
isLikeServerless,
})
})(), })(),
config.experimental.conformance && config.experimental.conformance &&
!isWebpack5 && !isWebpack5 &&
......
...@@ -36,6 +36,11 @@ export class FontStylesheetGatheringPlugin { ...@@ -36,6 +36,11 @@ export class FontStylesheetGatheringPlugin {
compiler?: webpack.Compiler compiler?: webpack.Compiler
gatheredStylesheets: Array<string> = [] gatheredStylesheets: Array<string> = []
manifestContent: FontManifest = [] manifestContent: FontManifest = []
isLikeServerless: boolean
constructor({ isLikeServerless }: { isLikeServerless: boolean }) {
this.isLikeServerless = isLikeServerless
}
private parserHandler = ( private parserHandler = (
factory: webpack.compilation.NormalModuleFactory factory: webpack.compilation.NormalModuleFactory
...@@ -137,8 +142,7 @@ export class FontStylesheetGatheringPlugin { ...@@ -137,8 +142,7 @@ export class FontStylesheetGatheringPlugin {
this.parserHandler this.parserHandler
) )
compiler.hooks.make.tapAsync(this.constructor.name, (compilation, cb) => { compiler.hooks.make.tapAsync(this.constructor.name, (compilation, cb) => {
// @ts-ignore if (this.isLikeServerless) {
if (compilation.options.output.path.endsWith('serverless')) {
/** /**
* Inline font manifest for serverless case only. * Inline font manifest for serverless case only.
* For target: server drive the manifest through physical file and less of webpack magic. * For target: server drive the manifest through physical file and less of webpack magic.
...@@ -196,7 +200,7 @@ export class FontStylesheetGatheringPlugin { ...@@ -196,7 +200,7 @@ export class FontStylesheetGatheringPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, },
(assets: any) => { (assets: any) => {
assets[FONT_MANIFEST] = new sources.RawSource( assets['../' + FONT_MANIFEST] = new sources.RawSource(
JSON.stringify(this.manifestContent, null, ' ') JSON.stringify(this.manifestContent, null, ' ')
) )
} }
......
...@@ -219,13 +219,30 @@ class MiniCssExtractPlugin { ...@@ -219,13 +219,30 @@ class MiniCssExtractPlugin {
if (Object.keys(chunkMap).length > 0) { if (Object.keys(chunkMap).length > 0) {
const chunkMaps = chunk.getChunkMaps() const chunkMaps = chunk.getChunkMaps()
const { crossOriginLoading } = mainTemplate.outputOptions const { crossOriginLoading } = isWebpack5
const linkHrefPath = mainTemplate.getAssetPath( ? compilation.outputOptions
: mainTemplate.outputOptions
const getHash = !isWebpack5
? (...args) => mainTemplate.renderCurrentHashCode(...args)
: (curHash, length) => {
if (length) {
return `${webpack.RuntimeGlobals.getFullHash} ? ${
webpack.RuntimeGlobals.getFullHash
}().slice(0, ${length}) : ${curHash.slice(0, length)}`
}
return `${webpack.RuntimeGlobals.getFullHash} ? ${webpack.RuntimeGlobals.getFullHash}() : ${curHash}`
}
const getAssetPath = isWebpack5
? (...args) => compilation.getAssetPath(...args)
: (...args) => mainTemplate.getAssetPath(...args)
const linkHrefPath = getAssetPath(
JSON.stringify(this.options.chunkFilename), JSON.stringify(this.options.chunkFilename),
{ {
hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hash: `" + ${getHash(hash)} + "`,
hashWithLength: (length) => hashWithLength: (length) => `" + ${getHash(hash, length)} + "`,
`" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
chunk: { chunk: {
id: '" + chunkId + "', id: '" + chunkId + "',
hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
...@@ -286,7 +303,9 @@ class MiniCssExtractPlugin { ...@@ -286,7 +303,9 @@ class MiniCssExtractPlugin {
'promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {', 'promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {',
Template.indent([ Template.indent([
`var href = ${linkHrefPath};`, `var href = ${linkHrefPath};`,
`var fullhref = ${mainTemplate.requireFn}.p + href;`, `var fullhref = ${
isWebpack5 ? '__webpack_require__' : mainTemplate.requireFn
}.p + href;`,
'var existingLinkTags = document.getElementsByTagName("link");', 'var existingLinkTags = document.getElementsByTagName("link");',
'for(var i = 0; i < existingLinkTags.length; i++) {', 'for(var i = 0; i < existingLinkTags.length; i++) {',
Template.indent([ Template.indent([
......
...@@ -13,9 +13,11 @@ export type PagesManifest = { [page: string]: string } ...@@ -13,9 +13,11 @@ export type PagesManifest = { [page: string]: string }
// It's also used by next export to provide defaultPathMap // It's also used by next export to provide defaultPathMap
export default class PagesManifestPlugin implements webpack.Plugin { export default class PagesManifestPlugin implements webpack.Plugin {
serverless: boolean serverless: boolean
dev: boolean
constructor(serverless: boolean) { constructor({ serverless, dev }: { serverless: boolean; dev: boolean }) {
this.serverless = serverless this.serverless = serverless
this.dev = dev
} }
createAssets(compilation: any, assets: any) { createAssets(compilation: any, assets: any) {
...@@ -45,12 +47,17 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -45,12 +47,17 @@ export default class PagesManifestPlugin implements webpack.Plugin {
} }
// Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency. // Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
pages[pagePath] = files[0].replace(/\\/g, '/') pages[pagePath] = files[0]
if (isWebpack5 && !this.dev) {
pages[pagePath] = pages[pagePath].slice(3)
}
pages[pagePath] = pages[pagePath].replace(/\\/g, '/')
} }
assets[PAGES_MANIFEST] = new sources.RawSource( assets[
JSON.stringify(pages, null, 2) `${isWebpack5 && !this.dev ? '../' : ''}` + PAGES_MANIFEST
) ] = new sources.RawSource(JSON.stringify(pages, null, 2))
} }
apply(compiler: webpack.Compiler): void { apply(compiler: webpack.Compiler): void {
......
...@@ -27,6 +27,10 @@ export async function shouldLoadWithWebpack5( ...@@ -27,6 +27,10 @@ export async function shouldLoadWithWebpack5(
cwd: dir, cwd: dir,
}) })
if (Number(process.env.NEXT_PRIVATE_TEST_WEBPACK5_MODE) > 0) {
return true
}
// No `next.config.js`: // No `next.config.js`:
if (!path?.length) { if (!path?.length) {
return false // TODO: return true to default to webpack 5 return false // TODO: return true to default to webpack 5
......
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