Unverified Commit 210a6980 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Solve large portion of webpack 5 deprecation warnings (#15806)

- Using `namedChunks` where possible, this will also allow for faster access to the chunks as we no longer have to look them up like we did before using `find`
- Using the new asset hooks introduced in the latest webpack beta
- Using the new externals function signature
parent ed0a47b1
...@@ -501,15 +501,8 @@ export default async function getBaseWebpackConfig( ...@@ -501,15 +501,8 @@ export default async function getBaseWebpackConfig(
}, },
config.conformance config.conformance
) )
let webpackConfig: webpack.Configuration = {
externals: !isServer function handleExternals(context: any, request: any, callback: any) {
? // make sure importing "next" is handled gracefully for client
// bundles in case a user imported types and it wasn't removed
// TODO: should we warn/error for this instead?
['next']
: !isServerless
? [
(context, request, callback) => {
if (request === 'next') { if (request === 'next') {
return callback(undefined, `commonjs ${request}`) return callback(undefined, `commonjs ${request}`)
} }
...@@ -647,7 +640,21 @@ export default async function getBaseWebpackConfig( ...@@ -647,7 +640,21 @@ export default async function getBaseWebpackConfig(
// Default behavior: bundle the code! // Default behavior: bundle the code!
callback() callback()
}, }
let webpackConfig: webpack.Configuration = {
externals: !isServer
? // make sure importing "next" is handled gracefully for client
// bundles in case a user imported types and it wasn't removed
// TODO: should we warn/error for this instead?
['next']
: !isServerless
? [
isWebpack5
? ({ context, request }, callback) =>
handleExternals(context, request, callback)
: (context, request, callback) =>
handleExternals(context, request, callback),
] ]
: [ : [
// When the 'serverless' target is used all node_modules will be compiled into the output bundles // When the 'serverless' target is used all node_modules will be compiled into the output bundles
......
import devalue from 'next/dist/compiled/devalue' import devalue from 'next/dist/compiled/devalue'
import { Compiler, compilation as CompilationType } from 'webpack' import webpack, { Compiler, compilation as CompilationType } from 'webpack'
import { RawSource } from 'webpack-sources' import { RawSource } from 'webpack-sources'
import { import {
BUILD_MANIFEST, BUILD_MANIFEST,
...@@ -13,6 +13,8 @@ import { BuildManifest } from '../../../next-server/server/get-page-files' ...@@ -13,6 +13,8 @@ import { BuildManifest } from '../../../next-server/server/get-page-files'
import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint' import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin' import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
const isWebpack5 = parseInt(webpack.version!) === 5
// This function takes the asset map generated in BuildManifestPlugin and creates a // This function takes the asset map generated in BuildManifestPlugin and creates a
// reduced version to send to the client. // reduced version to send to the client.
function generateClientManifest( function generateClientManifest(
...@@ -45,6 +47,17 @@ function isJsFile(file: string): boolean { ...@@ -45,6 +47,17 @@ function isJsFile(file: string): boolean {
return !file.endsWith('.hot-update.js') && file.endsWith('.js') return !file.endsWith('.hot-update.js') && file.endsWith('.js')
} }
function getFilesArray(files: any) {
if (!files) {
return []
}
if (isWebpack5) {
return Array.from(files)
}
return files
}
// This plugin creates a build-manifest.json for all assets that are being output // This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production // It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin { export default class BuildManifestPlugin {
...@@ -56,11 +69,9 @@ export default class BuildManifestPlugin { ...@@ -56,11 +69,9 @@ export default class BuildManifestPlugin {
this.modern = options.modern this.modern = options.modern
} }
apply(compiler: Compiler) { createAssets(compilation: any, assets: any) {
compiler.hooks.emit.tapAsync( const namedChunks: Map<string, CompilationType.Chunk> =
'NextJsBuildManifest', compilation.namedChunks
(compilation: any, callback: any) => {
const chunks: CompilationType.Chunk[] = compilation.chunks
const assetMap: BuildManifest = { const assetMap: BuildManifest = {
polyfillFiles: [], polyfillFiles: [],
devFiles: [], devFiles: [],
...@@ -82,27 +93,26 @@ export default class BuildManifestPlugin { ...@@ -82,27 +93,26 @@ export default class BuildManifestPlugin {
} }
} }
const mainJsChunk = chunks.find( const mainJsChunk = namedChunks.get(CLIENT_STATIC_FILES_RUNTIME_MAIN)
(c) => c.name === CLIENT_STATIC_FILES_RUNTIME_MAIN
)
const mainJsFiles: string[] = mainJsChunk?.files.filter(isJsFile) ?? []
const polyfillChunk = chunks.find( const mainJsFiles: string[] = getFilesArray(mainJsChunk?.files).filter(
(c) => c.name === CLIENT_STATIC_FILES_RUNTIME_POLYFILLS isJsFile
) )
const polyfillChunk = namedChunks.get(CLIENT_STATIC_FILES_RUNTIME_POLYFILLS)
// Create a separate entry for polyfills // Create a separate entry for polyfills
assetMap.polyfillFiles = polyfillChunk?.files.filter(isJsFile) ?? [] assetMap.polyfillFiles = getFilesArray(polyfillChunk?.files).filter(
isJsFile
)
const reactRefreshChunk = chunks.find( const reactRefreshChunk = namedChunks.get(
(c) => c.name === CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) )
assetMap.devFiles = reactRefreshChunk?.files.filter(isJsFile) ?? [] assetMap.devFiles = getFilesArray(reactRefreshChunk?.files).filter(isJsFile)
for (const entrypoint of compilation.entrypoints.values()) { for (const entrypoint of compilation.entrypoints.values()) {
const isAmpRuntime = const isAmpRuntime = entrypoint.name === CLIENT_STATIC_FILES_RUNTIME_AMP
entrypoint.name === CLIENT_STATIC_FILES_RUNTIME_AMP
if (isAmpRuntime) { if (isAmpRuntime) {
for (const file of entrypoint.getFiles()) { for (const file of entrypoint.getFiles()) {
...@@ -153,14 +163,12 @@ export default class BuildManifestPlugin { ...@@ -153,14 +163,12 @@ export default class BuildManifestPlugin {
const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js` const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js`
assetMap.lowPriorityFiles.push(ssgManifestPath) assetMap.lowPriorityFiles.push(ssgManifestPath)
compilation.assets[ssgManifestPath] = new RawSource(srcEmptySsgManifest) assets[ssgManifestPath] = new RawSource(srcEmptySsgManifest)
if (this.modern) { if (this.modern) {
const ssgManifestPathModern = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.module.js` const ssgManifestPathModern = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.module.js`
assetMap.lowPriorityFiles.push(ssgManifestPathModern) assetMap.lowPriorityFiles.push(ssgManifestPathModern)
compilation.assets[ssgManifestPathModern] = new RawSource( assets[ssgManifestPathModern] = new RawSource(srcEmptySsgManifest)
srcEmptySsgManifest
)
} }
assetMap.pages = Object.keys(assetMap.pages) assetMap.pages = Object.keys(assetMap.pages)
...@@ -168,13 +176,11 @@ export default class BuildManifestPlugin { ...@@ -168,13 +176,11 @@ export default class BuildManifestPlugin {
// eslint-disable-next-line // eslint-disable-next-line
.reduce((a, c) => ((a[c] = assetMap.pages[c]), a), {} as any) .reduce((a, c) => ((a[c] = assetMap.pages[c]), a), {} as any)
compilation.assets[BUILD_MANIFEST] = new RawSource( assets[BUILD_MANIFEST] = new RawSource(JSON.stringify(assetMap, null, 2))
JSON.stringify(assetMap, null, 2)
)
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js` const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
compilation.assets[clientManifestPath] = new RawSource( assets[clientManifestPath] = new RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest( `self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap, assetMap,
false false
...@@ -184,15 +190,37 @@ export default class BuildManifestPlugin { ...@@ -184,15 +190,37 @@ export default class BuildManifestPlugin {
if (this.modern) { if (this.modern) {
const modernClientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.module.js` const modernClientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.module.js`
compilation.assets[modernClientManifestPath] = new RawSource( assets[modernClientManifestPath] = new RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest( `self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap, assetMap,
true true
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()` )};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
) )
} }
callback()
return assets
}
apply(compiler: Compiler) {
if (isWebpack5) {
compiler.hooks.make.tap('NextJsBuildManifest', (compilation) => {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
compilation.hooks.processAssets.tap(
{
name: 'NextJsBuildManifest',
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compilation, assets)
} }
) )
})
return
}
compiler.hooks.emit.tap('NextJsBuildManifest', (compilation: any) => {
this.createAssets(compilation, compilation.assets)
})
} }
} }
import { Compiler, Plugin } from 'webpack' import webpack, { Compiler, Plugin } from 'webpack'
import { RawSource } from 'webpack-sources' import { RawSource } from 'webpack-sources'
import { PAGES_MANIFEST } from '../../../next-server/lib/constants' import { PAGES_MANIFEST } from '../../../next-server/lib/constants'
import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint' import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
export type PagesManifest = { [page: string]: string } export type PagesManifest = { [page: string]: string }
const isWebpack5 = parseInt(webpack.version!) === 5
// This plugin creates a pages-manifest.json from page entrypoints. // This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR // This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
// It's also used by next export to provide defaultPathMap // It's also used by next export to provide defaultPathMap
...@@ -15,16 +17,12 @@ export default class PagesManifestPlugin implements Plugin { ...@@ -15,16 +17,12 @@ export default class PagesManifestPlugin implements Plugin {
this.serverless = serverless this.serverless = serverless
} }
apply(compiler: Compiler): void { createAssets(compilation: any, assets: any) {
compiler.hooks.emit.tap('NextJsPagesManifest', (compilation) => {
const entrypoints = compilation.entrypoints const entrypoints = compilation.entrypoints
const pages: PagesManifest = {} const pages: PagesManifest = {}
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
const pagePath = getRouteFromEntrypoint( const pagePath = getRouteFromEntrypoint(entrypoint.name, this.serverless)
entrypoint.name,
this.serverless
)
if (!pagePath) { if (!pagePath) {
continue continue
...@@ -49,9 +47,29 @@ export default class PagesManifestPlugin implements Plugin { ...@@ -49,9 +47,29 @@ export default class PagesManifestPlugin implements Plugin {
pages[pagePath] = files[0].replace(/\\/g, '/') pages[pagePath] = files[0].replace(/\\/g, '/')
} }
compilation.assets[PAGES_MANIFEST] = new RawSource( assets[PAGES_MANIFEST] = new RawSource(JSON.stringify(pages, null, 2))
JSON.stringify(pages, null, 2) }
apply(compiler: Compiler): void {
if (isWebpack5) {
compiler.hooks.make.tap('NextJsPagesManifest', (compilation) => {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
compilation.hooks.processAssets.tap(
{
name: 'NextJsPagesManifest',
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compilation, assets)
}
) )
}) })
return
}
compiler.hooks.emit.tap('NextJsPagesManifest', (compilation: any) => {
this.createAssets(compilation, compilation.assets)
})
} }
} }
...@@ -21,12 +21,30 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR ...@@ -21,12 +21,30 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
// Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132 // Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132
// Modified to strip out unneeded results for Next's specific use case // Modified to strip out unneeded results for Next's specific use case
import { import webpack, {
Compiler, Compiler,
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
compilation as CompilationType, compilation as CompilationType,
} from 'webpack' } from 'webpack'
const isWebpack5 = parseInt(webpack.version!) === 5
function getModulesIterable(compilation: any, chunk: any) {
if (isWebpack5) {
return compilation.chunkGraph.getChunkModulesIterable(chunk)
}
return chunk.modulesIterable
}
function getModuleId(compilation: any, module: any) {
if (isWebpack5) {
return compilation.chunkGraph.getModuleId(module)
}
return module.id
}
function buildManifest( function buildManifest(
_compiler: Compiler, _compiler: Compiler,
compilation: CompilationType.Compilation compilation: CompilationType.Compilation
...@@ -47,8 +65,8 @@ function buildManifest( ...@@ -47,8 +65,8 @@ function buildManifest(
return return
} }
for (const module of chunk.modulesIterable) { for (const module of getModulesIterable(compilation, chunk)) {
let id = module.id let id = getModuleId(compilation, module)
if (!manifest[request]) { if (!manifest[request]) {
manifest[request] = [] manifest[request] = []
...@@ -88,13 +106,10 @@ export class ReactLoadablePlugin { ...@@ -88,13 +106,10 @@ export class ReactLoadablePlugin {
this.filename = opts.filename this.filename = opts.filename
} }
apply(compiler: Compiler) { createAssets(compiler: any, compilation: any, assets: any) {
compiler.hooks.emit.tapAsync(
'ReactLoadableManifest',
(compilation, callback) => {
const manifest = buildManifest(compiler, compilation) const manifest = buildManifest(compiler, compilation)
var json = JSON.stringify(manifest, null, 2) var json = JSON.stringify(manifest, null, 2)
compilation.assets[this.filename] = { assets[this.filename] = {
source() { source() {
return json return json
}, },
...@@ -102,8 +117,29 @@ export class ReactLoadablePlugin { ...@@ -102,8 +117,29 @@ export class ReactLoadablePlugin {
return json.length return json.length
}, },
} }
callback() return assets
}
apply(compiler: Compiler) {
if (isWebpack5) {
compiler.hooks.make.tap('ReactLoadableManifest', (compilation) => {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
compilation.hooks.processAssets.tap(
{
name: 'ReactLoadableManifest',
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compiler, compilation, assets)
} }
) )
})
return
}
compiler.hooks.emit.tap('ReactLoadableManifest', (compilation: any) => {
this.createAssets(compiler, compilation, compilation.assets)
})
} }
} }
...@@ -29,13 +29,18 @@ export class ServerlessPlugin { ...@@ -29,13 +29,18 @@ export class ServerlessPlugin {
// Async chunks are usages of import() for example // Async chunks are usages of import() for example
const dynamicChunks = chunk.getAllAsyncChunks() const dynamicChunks = chunk.getAllAsyncChunks()
for (const dynamicChunk of dynamicChunks) { for (const dynamicChunk of dynamicChunks) {
for (const module of dynamicChunk.modulesIterable) {
if (isWebpack5) { if (isWebpack5) {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
for (const module of compilation.chunkGraph.getChunkModulesIterable(
chunk
)) {
// Add module back into the entry chunk // Add module back into the entry chunk
chunk.addModule(module) chunk.addModule(module)
}
continue continue
} }
for (const module of dynamicChunk.modulesIterable) {
// Webpack 4 has separate GraphHelpers // Webpack 4 has separate GraphHelpers
GraphHelpers.connectChunkAndModule(chunk, module) GraphHelpers.connectChunkAndModule(chunk, module)
} }
......
...@@ -368,9 +368,7 @@ export default class HotReloader { ...@@ -368,9 +368,7 @@ export default class HotReloader {
// We only watch `_document` for changes on the server compilation // We only watch `_document` for changes on the server compilation
// the rest of the files will be triggered by the client compilation // the rest of the files will be triggered by the client compilation
const documentChunk = compilation.chunks.find( const documentChunk = compilation.namedChunks.get('pages/_document')
(c) => c.name === `pages/_document`
)
// If the document chunk can't be found we do nothing // If the document chunk can't be found we do nothing
if (!documentChunk) { if (!documentChunk) {
console.warn('_document.js chunk not found') console.warn('_document.js chunk not found')
...@@ -409,9 +407,9 @@ export default class HotReloader { ...@@ -409,9 +407,9 @@ export default class HotReloader {
const { compilation } = stats const { compilation } = stats
const chunkNames = new Set( const chunkNames = new Set(
compilation.chunks [...compilation.namedChunks.keys()].filter(
.map((c) => c.name) (name) => !!getRouteFromEntrypoint(name)
.filter((name) => !!getRouteFromEntrypoint(name)) )
) )
if (this.prevChunkNames) { if (this.prevChunkNames) {
......
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