Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

partially migrate to webpack 5 types #30189

Merged
merged 7 commits into from
Oct 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/next/build/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type webpack5 from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../trace'

export type CompilerResult = {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env'
import { NextConfigComplete } from '../server/config-shared'
import type webpack5 from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'

type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
type PagesMapping = {
Expand Down
5 changes: 4 additions & 1 deletion packages/next/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ import { NextConfigComplete } from '../server/config-shared'
import isError, { NextError } from '../lib/is-error'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'

const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/

Expand Down Expand Up @@ -1777,7 +1778,9 @@ export default async function build(
})
)

const telemetryPlugin = clientConfig.plugins?.find(isTelemetryPlugin)
const telemetryPlugin = (
clientConfig as webpack.Configuration
).plugins?.find(isTelemetryPlugin)
if (telemetryPlugin) {
const events = eventBuildFeatureUsage(telemetryPlugin)
telemetry.record(events)
Expand Down
50 changes: 24 additions & 26 deletions packages/next/build/output/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import textTable from 'next/dist/compiled/text-table'
import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages'
import { OutputState, store as consoleStore } from './store'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'

export function startedDevelopmentServer(appUrl: string, bindAddr: string) {
consoleStore.setState({ appUrl, bindAddr })
}

let previousClient: import('webpack').Compiler | null = null
let previousServer: import('webpack').Compiler | null = null
let previousClient: webpack5.Compiler | null = null
let previousServer: webpack5.Compiler | null = null

type CompilerDiagnostics = {
modules: number
Expand Down Expand Up @@ -207,8 +208,8 @@ export function ampValidation(
}

export function watchCompilers(
client: import('webpack').Compiler,
server: import('webpack').Compiler
client: webpack5.Compiler,
server: webpack5.Compiler
) {
if (previousClient === client && previousServer === server) {
return
Expand All @@ -229,29 +230,26 @@ export function watchCompilers(
onEvent({ loading: true })
})

compiler.hooks.done.tap(
`NextJsDone-${key}`,
(stats: import('webpack5').Stats) => {
buildStore.setState({ amp: {} })

const { errors, warnings } = formatWebpackMessages(
stats.toJson({
preset: 'error-warnings',
moduleTrace: true,
})
)

const hasErrors = !!errors?.length
const hasWarnings = !!warnings?.length

onEvent({
loading: false,
modules: stats.compilation.modules.size,
errors: hasErrors ? errors : null,
warnings: hasWarnings ? warnings : null,
compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: webpack5.Stats) => {
buildStore.setState({ amp: {} })

const { errors, warnings } = formatWebpackMessages(
stats.toJson({
preset: 'error-warnings',
moduleTrace: true,
})
}
)
)

const hasErrors = !!errors?.length
const hasWarnings = !!warnings?.length

onEvent({
loading: false,
modules: stats.compilation.modules.size,
errors: hasErrors ? errors : null,
warnings: hasWarnings ? warnings : null,
})
})
}

tapCompiler('client', client, (status) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { readFileSync } from 'fs'
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import semver from 'next/dist/compiled/semver'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type webpack5 from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import path, { join as pathJoin, relative as relativePath } from 'path'
import escapeRegExp from 'next/dist/compiled/escape-string-regexp'
import {
Expand Down
3 changes: 2 additions & 1 deletion packages/next/build/webpack/plugins/css-minimizer-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import cssnanoSimple from 'cssnano-simple'
import postcssScss from 'next/dist/compiled/postcss-scss'
import postcss, { Parser } from 'postcss'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { spans } from './profiling-plugin'

// https://github.com/NMFR/optimize-css-assets-webpack-plugin/blob/0a410a9bf28c7b0e81a3470a13748e68ca2f50aa/src/index.js#L20
Expand Down Expand Up @@ -54,7 +55,7 @@ export class CssMinimizerPlugin {
})
}

apply(compiler: webpack.Compiler) {
apply(compiler: webpack5.Compiler) {
compiler.hooks.compilation.tap('CssMinimizerPlugin', (compilation: any) => {
const cache = compilation.getCache('CssMinimizerPlugin')
compilation.hooks.processAssets.tapPromise(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from 'next/dist/compiled/@vercel/nft'
import { TRACE_OUTPUT_VERSION } from '../../../shared/lib/constants'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
nextImageLoaderRegex,
NODE_ESM_RESOLVE_OPTIONS,
Expand All @@ -26,11 +27,11 @@ const TRACE_IGNORES = [
function getModuleFromDependency(
compilation: any,
dep: any
): webpack.Module & { resource?: string } {
): webpack5.Module & { resource?: string } {
return compilation.moduleGraph.getModule(dep)
}

export class TraceEntryPointsPlugin implements webpack.Plugin {
export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance {
private appDir: string
private entryTraces: Map<string, Set<string>>
private excludeFiles: string[]
Expand Down Expand Up @@ -100,7 +101,7 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
}

tapfinishModules(
compilation: webpack.compilation.Compilation,
compilation: webpack5.Compilation,
traceEntrypointsPluginSpan: Span,
doResolve?: (
request: string,
Expand All @@ -126,9 +127,7 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
const depModMap = new Map<string, any>()

finishModulesSpan.traceChild('get-entries').traceFn(() => {
compilation.entries.forEach((entry) => {
const name = entry.name || entry.options?.name

compilation.entries.forEach((entry, name) => {
if (name?.replace(/\\/g, '/').startsWith('pages/')) {
for (const dep of entry.dependencies) {
if (!dep) continue
Expand Down Expand Up @@ -369,7 +368,7 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
)
}

apply(compiler: webpack.Compiler) {
apply(compiler: webpack5.Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const compilationSpan = spans.get(compilation) || spans.get(compiler)!
const traceEntrypointsPluginSpan = compilationSpan.traceChild(
Expand Down Expand Up @@ -420,7 +419,7 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
missingDependencies: compilation.missingDependencies,
contextDependencies: compilation.contextDependencies,
},
async (err: any, result: string, resContext: any) => {
async (err: any, result?: string | false, resContext?: any) => {
if (err) return reject(err)

if (!result) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import type { Compiler, WebpackPluginInstance } from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { clearSandboxCache } from '../../../server/web/sandbox'
import { realpathSync } from 'fs'
import path from 'path'
import isError from '../../../lib/is-error'

type Compiler = webpack5.Compiler
type WebpackPluginInstance = webpack5.WebpackPluginInstance

const originModules = [
require.resolve('../../../server/require'),
require.resolve('../../../server/load-components'),
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/webpack/plugins/profiling-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NormalModule } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../../../trace'
import type webpack from 'webpack'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'

const pluginName = 'ProfilingPlugin'
export const spans = new WeakMap<webpack.Compilation | webpack.Compiler, Span>()
Expand Down
10 changes: 5 additions & 5 deletions packages/next/build/webpack/plugins/telemetry-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Compiler, Compilation } from 'webpack'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'

type Feature = 'next/image' | 'next/script' | 'next/dynamic'

Expand Down Expand Up @@ -34,7 +34,7 @@ const FEATURE_MODULE_MAP: ReadonlyMap<Feature, string> = new Map([
* certain features (e.g. next/image and next/script) and record how many times
* they are imported.
*/
export class TelemetryPlugin {
export class TelemetryPlugin implements webpack.WebpackPluginInstance {
private usageTracker = new Map<Feature, FeatureUsage>()

constructor() {
Expand All @@ -46,13 +46,13 @@ export class TelemetryPlugin {
}
}

apply(compiler: Compiler): void {
apply(compiler: webpack.Compiler): void {
compiler.hooks.make.tapAsync(
TelemetryPlugin.name,
async (compilation: Compilation, callback: () => void) => {
async (compilation: webpack.Compilation, callback: () => void) => {
compilation.hooks.finishModules.tapAsync(
TelemetryPlugin.name,
async (modules: Set<Module>, modulesFinish: () => void) => {
async (modules: Iterable<Module>, modulesFinish: () => void) => {
for (const module of modules) {
const feature = findFeatureInModule(module)
if (!feature) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type webpack5 from 'webpack5'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { getModuleBuildError } from './webpackModuleError'

export class WellKnownErrorsPlugin {
apply(compiler: webpack5.Compiler) {
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap('WellKnownErrorsPlugin', (compilation) => {
compilation.hooks.afterSeal.tapPromise(
'WellKnownErrorsPlugin',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Chalk from 'chalk'
import { SimpleWebpackError } from './simpleWebpackError'
import { createOriginalStackFrame } from '@next/react-dev-overlay/lib/middleware'
import type webpack5 from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'

const chalk = new Chalk.constructor({ enabled: true })

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type webpack5 from 'webpack5'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'

// This class creates a simplified webpack error that formats nicely based on
// webpack's build in serializer.
// https://github.com/webpack/webpack/blob/c9d4ff7b054fc581c96ce0e53432d44f9dd8ca72/lib/Stats.js#L294-L356
export class SimpleWebpackError extends (Error as unknown as typeof webpack5.WebpackError) {
export class SimpleWebpackError extends (Error as unknown as typeof webpack.WebpackError) {
file: string

constructor(file: string, message: string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { readFileSync } from 'fs'
import * as path from 'path'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { getBabelError } from './parseBabel'
import { getCssError } from './parseCss'
import { getScssError } from './parseScss'
import { getNotFoundError } from './parseNotFoundError'
import { SimpleWebpackError } from './simpleWebpackError'
import isError from '../../../../lib/is-error'
import type webpack5 from 'webpack5'

function getFileData(
compilation: webpack5.Compilation,
compilation: webpack.Compilation,
m: any
): [string, string | null] {
let resolved: string
Expand Down Expand Up @@ -41,7 +41,7 @@ function getFileData(
}

export async function getModuleBuildError(
compilation: webpack5.Compilation,
compilation: webpack.Compilation,
input: any
): Promise<SimpleWebpackError | false> {
if (
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/config-shared.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os from 'os'
import type webpack5 from 'webpack5'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
import {
ImageConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/dev/hot-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import type ws from 'ws'

export class WebpackHotMiddleware {
Expand Down
19 changes: 10 additions & 9 deletions packages/next/server/dev/hot-reloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute } from 'path'
import { UrlObject } from 'url'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
createEntrypoints,
createPagesMapping,
Expand Down Expand Up @@ -103,14 +104,14 @@ function findEntryModule(issuer: any): any {
return issuer
}

function erroredPages(compilation: webpack.compilation.Compilation) {
function erroredPages(compilation: webpack5.Compilation) {
const failedPages: { [page: string]: any[] } = {}
for (const error of compilation.errors) {
if (!error.origin) {
if (!error.module) {
continue
}

const entryModule = findEntryModule(error.origin)
const entryModule = findEntryModule(error.module)
const { name } = entryModule
if (!name) {
continue
Expand Down Expand Up @@ -140,8 +141,8 @@ export default class HotReloader {
private pagesDir: string
private webpackHotMiddleware?: WebpackHotMiddleware
private config: NextConfigComplete
public clientStats: webpack.Stats | null
public serverStats: webpack.Stats | null
public clientStats: webpack5.Stats | null
public serverStats: webpack5.Stats | null
private clientError: Error | null = null
private serverError: Error | null = null
private serverPrevDocumentHash: string | null
Expand Down Expand Up @@ -472,7 +473,7 @@ export default class HotReloader {
// @ts-ignore webpack 5
configs.parallelism = 1

const multiCompiler = webpack(configs)
const multiCompiler = webpack(configs) as unknown as webpack5.MultiCompiler

watchCompilers(multiCompiler.compilers[0], multiCompiler.compilers[1])

Expand All @@ -485,7 +486,7 @@ export default class HotReloader {

const trackPageChanges =
(pageHashMap: Map<string, string>, changedItems: Set<string>) =>
(stats: webpack.compilation.Compilation) => {
(stats: webpack5.Compilation) => {
stats.entrypoints.forEach((entry, key) => {
if (key.startsWith('pages/')) {
// TODO this doesn't handle on demand loaded chunks
Expand Down Expand Up @@ -539,7 +540,7 @@ export default class HotReloader {

// Initial value
if (this.serverPrevDocumentHash === null) {
this.serverPrevDocumentHash = documentChunk.hash
this.serverPrevDocumentHash = documentChunk.hash || null
return
}

Expand All @@ -550,7 +551,7 @@ export default class HotReloader {

// Notify reload to reload the page, as _document.js was changed (different hash)
this.send('reloadPage')
this.serverPrevDocumentHash = documentChunk.hash
this.serverPrevDocumentHash = documentChunk.hash || null
}
)
multiCompiler.hooks.done.tap('NextjsHotReloaderForServer', () => {
Expand Down
Loading