Skip to content

Commit

Permalink
Remove webpack4 types (#39631)
Browse files Browse the repository at this point in the history
These types are no longer needed as we are only leveraging webpack 5 so this finishes migrating our types away from webpack 4's types.
  • Loading branch information
ijjk committed Aug 16, 2022
1 parent 11bd44f commit 6fd2a7f
Show file tree
Hide file tree
Showing 54 changed files with 325 additions and 3,203 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -200,7 +200,7 @@
"turbo": "1.3.2-canary.1",
"typescript": "4.6.3",
"wait-port": "0.2.2",
"webpack": "link:packages/next/node_modules/webpack5",
"webpack": "5.74.0",
"webpack-bundle-analyzer": "4.3.0"
},
"resolutions": {
Expand Down
5 changes: 3 additions & 2 deletions packages/next/build/babel/loader/types.d.ts
@@ -1,8 +1,9 @@
import { loader } from 'next/dist/compiled/webpack/webpack'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../../../trace'

export interface NextJsLoaderContext extends loader.LoaderContext {
export interface NextJsLoaderContext extends webpack.LoaderContext<{}> {
currentTraceSpan: Span
target: string
}

export interface NextBabelLoaderOptions {
Expand Down
13 changes: 6 additions & 7 deletions packages/next/build/compiler.ts
@@ -1,16 +1,15 @@
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../trace'

export type CompilerResult = {
errors: webpack5.StatsError[]
warnings: webpack5.StatsError[]
stats: webpack5.Stats | undefined
errors: webpack.StatsError[]
warnings: webpack.StatsError[]
stats: webpack.Stats | undefined
}

function generateStats(
result: CompilerResult,
stat: webpack5.Stats
stat: webpack.Stats
): CompilerResult {
const { errors, warnings } = stat.toJson({
preset: 'errors-warnings',
Expand All @@ -29,7 +28,7 @@ function generateStats(

// Webpack 5 requires the compiler to be closed (to save caches)
// Webpack 4 does not have this close method so in order to be backwards compatible we check if it exists
function closeCompiler(compiler: webpack5.Compiler | webpack5.MultiCompiler) {
function closeCompiler(compiler: webpack.Compiler | webpack.MultiCompiler) {
return new Promise<void>((resolve, reject) => {
// @ts-ignore Close only exists on the compiler in webpack 5
return compiler.close((err: any) => (err ? reject(err) : resolve()))
Expand All @@ -41,7 +40,7 @@ export function runCompiler(
{ runWebpackSpan }: { runWebpackSpan: Span }
): Promise<CompilerResult> {
return new Promise((resolve, reject) => {
const compiler = webpack(config) as unknown as webpack5.Compiler
const compiler = webpack(config) as unknown as webpack.Compiler
compiler.run((err, stats) => {
const webpackCloseSpan = runWebpackSpan.traceChild('webpack-close', {
name: config.name,
Expand Down
14 changes: 7 additions & 7 deletions packages/next/build/entries.ts
Expand Up @@ -3,7 +3,7 @@ import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-
import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader'
import type { NextConfigComplete } from '../server/config-shared'
import type { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type { LoadedEnvFiles } from '@next/env'
import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path'
Expand Down Expand Up @@ -231,7 +231,7 @@ export function getServerlessEntry(opts: {
page: string
previewMode: __ApiPreviewProps
pages: { [page: string]: string }
}): ObjectValue<webpack5.EntryObject> {
}): ObjectValue<webpack.EntryObject> {
const loaderParams: ServerlessLoaderQuery = {
absolute404Path: opts.pages['/404'] || '',
absoluteAppPath: opts.pages['/_app'],
Expand Down Expand Up @@ -339,9 +339,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
appPaths,
pageExtensions,
} = params
const edgeServer: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {}
const client: webpack5.EntryObject = {}
const edgeServer: webpack.EntryObject = {}
const server: webpack.EntryObject = {}
const client: webpack.EntryObject = {}
const nestedMiddleware: string[] = []
let middlewareRegex: string | undefined = undefined

Expand Down Expand Up @@ -490,10 +490,10 @@ export function finalizeEntrypoint({
}: {
compilerType?: CompilerNameValues
name: string
value: ObjectValue<webpack5.EntryObject>
value: ObjectValue<webpack.EntryObject>
isServerComponent?: boolean
appDir?: boolean
}): ObjectValue<webpack5.EntryObject> {
}): ObjectValue<webpack.EntryObject> {
const entry =
typeof value !== 'object' || Array.isArray(value)
? { import: value }
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/index.ts
@@ -1,4 +1,4 @@
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { loadEnvConfig } from '@next/env'
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
Expand Down
18 changes: 9 additions & 9 deletions packages/next/build/output/index.ts
Expand Up @@ -4,16 +4,16 @@ 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'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { CompilerNameValues, COMPILER_NAMES } from '../../shared/lib/constants'

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

let previousClient: webpack5.Compiler | null = null
let previousServer: webpack5.Compiler | null = null
let previousEdgeServer: webpack5.Compiler | null = null
let previousClient: webpack.Compiler | null = null
let previousServer: webpack.Compiler | null = null
let previousEdgeServer: webpack.Compiler | null = null

type CompilerDiagnostics = {
modules: number
Expand Down Expand Up @@ -219,9 +219,9 @@ export function ampValidation(
}

export function watchCompilers(
client: webpack5.Compiler,
server: webpack5.Compiler,
edgeServer: webpack5.Compiler
client: webpack.Compiler,
server: webpack.Compiler,
edgeServer: webpack.Compiler
) {
if (
previousClient === client &&
Expand All @@ -240,14 +240,14 @@ export function watchCompilers(

function tapCompiler(
key: CompilerNameValues,
compiler: webpack5.Compiler,
compiler: webpack.Compiler,
onEvent: (status: WebpackStatus) => void
) {
compiler.hooks.invalid.tap(`NextJsInvalid-${key}`, () => {
onEvent({ loading: true })
})

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

const { errors, warnings } = formatWebpackMessages(
Expand Down
91 changes: 53 additions & 38 deletions packages/next/build/webpack-config.ts
Expand Up @@ -2,7 +2,6 @@ import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-ut
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import path, { dirname, join as pathJoin, relative as relativePath } from 'path'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import {
Expand Down Expand Up @@ -332,27 +331,29 @@ export function attachReactRefresh(
const reactRefreshLoaderName =
'next/dist/compiled/@next/react-refresh-utils/dist/loader'
const reactRefreshLoader = require.resolve(reactRefreshLoaderName)
webpackConfig.module?.rules.forEach((rule) => {
const curr = rule.use
// When the user has configured `defaultLoaders.babel` for a input file:
if (curr === targetLoader) {
++injections
rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem]
} else if (
Array.isArray(curr) &&
curr.some((r) => r === targetLoader) &&
// Check if loader already exists:
!curr.some(
(r) => r === reactRefreshLoader || r === reactRefreshLoaderName
)
) {
++injections
const idx = curr.findIndex((r) => r === targetLoader)
// Clone to not mutate user input
rule.use = [...curr]
webpackConfig.module?.rules?.forEach((rule) => {
if (rule && typeof rule === 'object' && 'use' in rule) {
const curr = rule.use
// When the user has configured `defaultLoaders.babel` for a input file:
if (curr === targetLoader) {
++injections
rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem]
} else if (
Array.isArray(curr) &&
curr.some((r) => r === targetLoader) &&
// Check if loader already exists:
!curr.some(
(r) => r === reactRefreshLoader || r === reactRefreshLoaderName
)
) {
++injections
const idx = curr.findIndex((r) => r === targetLoader)
// Clone to not mutate user input
rule.use = [...curr]

// inject / input: [other, babel] output: [other, refresh, babel]:
rule.use.splice(idx, 0, reactRefreshLoader)
// inject / input: [other, babel] output: [other, refresh, babel]:
rule.use.splice(idx, 0, reactRefreshLoader)
}
}
})

Expand Down Expand Up @@ -515,7 +516,7 @@ export default async function getBaseWebpackConfig(
config: NextConfigComplete
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack5.EntryObject
entrypoints: webpack.EntryObject
hasReactRoot: boolean
isDevFallback?: boolean
pagesDir: string
Expand Down Expand Up @@ -1245,7 +1246,9 @@ export default async function getBaseWebpackConfig(
moduleIds: isClient ? 'deterministic' : 'named',
}
: {}),
splitChunks: ((): webpack.Options.SplitChunksOptions | false => {
splitChunks: (():
| Required<webpack.Configuration>['optimization']['splitChunks']
| false => {
// For the edge runtime, we have to bundle all dependencies inside without dynamic `require`s.
// To make some dependencies like `react` to be shared between entrypoints, we use a special
// cache group here even under dev mode.
Expand Down Expand Up @@ -1293,12 +1296,13 @@ export default async function getBaseWebpackConfig(
// as we don't need a separate vendor chunk from that
// and all other chunk depend on them so there is no
// duplication that need to be pulled out.
chunks: (chunk) => !/^(polyfills|main|pages\/_app)$/.test(chunk.name),
chunks: (chunk: any) =>
!/^(polyfills|main|pages\/_app)$/.test(chunk.name),
cacheGroups: {
framework: {
chunks: 'all',
name: 'framework',
test(module) {
test(module: any) {
const resource = module.nameForCondition?.()
return resource
? topLevelFrameworkPaths.some((pkgPath) =>
Expand Down Expand Up @@ -1833,7 +1837,7 @@ export default async function getBaseWebpackConfig(
)
}

const webpack5Config = webpackConfig as webpack5.Configuration
const webpack5Config = webpackConfig as webpack.Configuration

if (isEdgeServer) {
webpack5Config.module?.rules?.unshift({
Expand Down Expand Up @@ -2010,7 +2014,7 @@ export default async function getBaseWebpackConfig(
}

if (logDefault || profile) {
webpack5Config.plugins!.push((compiler: webpack5.Compiler) => {
webpack5Config.plugins!.push((compiler: webpack.Compiler) => {
compiler.hooks.done.tap('next-webpack-logging', (stats) => {
console.log(
stats.toString({
Expand All @@ -2021,7 +2025,7 @@ export default async function getBaseWebpackConfig(
})
})
} else if (summary) {
webpack5Config.plugins!.push((compiler: webpack5.Compiler) => {
webpack5Config.plugins!.push((compiler: webpack.Compiler) => {
compiler.hooks.done.tap('next-webpack-logging', (stats) => {
console.log(
stats.toString({
Expand All @@ -2036,7 +2040,7 @@ export default async function getBaseWebpackConfig(

if (profile) {
const ProgressPlugin =
webpack.ProgressPlugin as unknown as typeof webpack5.ProgressPlugin
webpack.ProgressPlugin as unknown as typeof webpack.ProgressPlugin
webpack5Config.plugins!.push(
new ProgressPlugin({
profile: true,
Expand Down Expand Up @@ -2098,7 +2102,7 @@ export default async function getBaseWebpackConfig(
}

// eslint-disable-next-line no-shadow
const webpack5Config = webpackConfig as webpack5.Configuration
const webpack5Config = webpackConfig as webpack.Configuration

// disable lazy compilation of entries as next.js has it's own method here
if (webpack5Config.experiments?.lazyCompilation === true) {
Expand All @@ -2123,15 +2127,23 @@ export default async function getBaseWebpackConfig(
const rules = webpackConfig.module?.rules || []
const hasCustomSvg = rules.some(
(rule) =>
rule &&
typeof rule === 'object' &&
rule.loader !== 'next-image-loader' &&
'test' in rule &&
rule.test instanceof RegExp &&
rule.test.test('.svg')
)
const nextImageRule = rules.find(
(rule) => rule.loader === 'next-image-loader'
(rule) =>
rule && typeof rule === 'object' && rule.loader === 'next-image-loader'
)
if (hasCustomSvg && nextImageRule) {
if (
hasCustomSvg &&
nextImageRule &&
nextImageRule &&
typeof nextImageRule === 'object'
) {
// Exclude svg if the user already defined it in custom
// webpack config such as `@svgr/webpack` plugin or
// the `babel-plugin-inline-react-svg` plugin.
Expand All @@ -2158,6 +2170,7 @@ export default async function getBaseWebpackConfig(
const innerRules = []

for (const rule of webpackConfig.module.rules) {
if (!rule || typeof rule !== 'object') continue
if (rule.resolve) {
topRules.push(rule)
} else {
Expand Down Expand Up @@ -2230,8 +2243,8 @@ export default async function getBaseWebpackConfig(
}

const hasUserCssConfig =
webpackConfig.module?.rules.some(
(rule) => canMatchCss(rule.test) || canMatchCss(rule.include)
webpackConfig.module?.rules?.some(
(rule: any) => canMatchCss(rule.test) || canMatchCss(rule.include)
) ?? false

if (hasUserCssConfig) {
Expand All @@ -2246,9 +2259,10 @@ export default async function getBaseWebpackConfig(
)
}

if (webpackConfig.module?.rules.length) {
if (webpackConfig.module?.rules?.length) {
// Remove default CSS Loaders
webpackConfig.module.rules.forEach((r) => {
if (!r || typeof r !== 'object') return
if (Array.isArray(r.oneOf)) {
r.oneOf = r.oneOf.filter(
(o) => (o as any)[Symbol.for('__next_css_remove')] !== true
Expand Down Expand Up @@ -2286,6 +2300,7 @@ export default async function getBaseWebpackConfig(

webpackConfig.module.rules = webpackConfig.module.rules.filter(
(rule): boolean => {
if (!rule || typeof rule !== 'object') return true
if (!(rule.test instanceof RegExp)) return true
if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
// remove if it matches @zeit/next-typescript
Expand Down Expand Up @@ -2402,7 +2417,7 @@ export default async function getBaseWebpackConfig(
const originalEntry: any = webpackConfig.entry
if (typeof originalEntry !== 'undefined') {
const updatedEntry = async () => {
const entry: webpack5.EntryObject =
const entry: webpack.EntryObject =
typeof originalEntry === 'function'
? await originalEntry()
: originalEntry
Expand Down Expand Up @@ -2437,9 +2452,9 @@ export default async function getBaseWebpackConfig(
webpackConfig.entry = updatedEntry
}

if (!dev) {
if (!dev && typeof webpackConfig.entry === 'function') {
// entry is always a function
webpackConfig.entry = await (webpackConfig.entry as webpack.EntryFunc)()
webpackConfig.entry = await webpackConfig.entry()
}

return webpackConfig
Expand Down
Expand Up @@ -5,7 +5,7 @@ import { webpack } from 'next/dist/compiled/webpack/webpack'
const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/

export function getCssModuleLocalIdent(
context: webpack.loader.LoaderContext,
context: webpack.LoaderContext<{}>,
_: any,
exportName: string,
options: object
Expand Down

0 comments on commit 6fd2a7f

Please sign in to comment.