webpack-config.ts 48.6 KB
Newer Older
1
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
2
import ReactRefreshWebpackPlugin from '@next/react-refresh-utils/ReactRefreshWebpackPlugin'
3
import crypto from 'crypto'
4
import { readFileSync, realpathSync } from 'fs'
5
import chalk from 'chalk'
6
import semver from 'next/dist/compiled/semver'
7 8
// @ts-ignore No typings yet
import TerserPlugin from './webpack/plugins/terser-webpack-plugin/src/index.js'
9
import path from 'path'
10
import webpack from 'webpack'
11
import { Configuration } from 'webpack'
12
import {
13
  DOT_NEXT_ALIAS,
14 15 16 17
  NEXT_PROJECT_ROOT,
  NEXT_PROJECT_ROOT_DIST_CLIENT,
  PAGES_DIR_ALIAS,
} from '../lib/constants'
18
import { fileExists } from '../lib/file-exists'
19 20
import { getPackageVersion } from '../lib/get-package-version'
import { Rewrite } from '../lib/load-custom-routes'
21
import { resolveRequest } from '../lib/resolve-request'
22
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
23 24
import {
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
25
  CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
26 27 28
  CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
  REACT_LOADABLE_MANIFEST,
  SERVERLESS_DIRECTORY,
29
  SERVER_DIRECTORY,
30
} from '../next-server/lib/constants'
31
import { execOnce } from '../next-server/lib/utils'
J
Joe Haddad 已提交
32
import { findPageFile } from '../server/lib/find-page-file'
33
import { WebpackEntrypoints } from './entries'
34
import * as Log from './output/log'
J
Joe Haddad 已提交
35 36 37 38 39
import {
  collectPlugins,
  PluginMetaData,
  VALID_MIDDLEWARE,
} from './plugins/collect-plugins'
40
import { build as buildConfiguration } from './webpack/config'
41
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
J
Joe Haddad 已提交
42
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
43 44
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
J
Joe Haddad 已提交
45
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin'
46
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
47
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
48 49 50
import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
51
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
52 53
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
54
import WebpackConformancePlugin, {
55
  DuplicatePolyfillsConformanceCheck,
56
  GranularChunksConformanceCheck,
57
  MinificationConformanceCheck,
58
  ReactSyncScriptsConformanceCheck,
59
} from './webpack/plugins/webpack-conformance-plugin'
J
Joe Haddad 已提交
60
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
61
import { NextConfig } from '../next-server/server/config'
62

63
type ExcludesFalse = <T>(x: T | false) => x is T
64

65 66
const isWebpack5 = parseInt(webpack.version!) === 5

67
if (isWebpack5 && semver.lt(webpack.version!, '5.11.1')) {
68
  Log.error(
69 70
    `webpack 5 version must be greater than v5.11.1 to work properly with Next.js, please upgrade to continue!\nSee more info here: https://err.sh/next.js/invalid-webpack-5-version`
  )
71
  process.exit(1)
72 73
}

74 75 76 77 78 79 80 81 82
const devtoolRevertWarning = execOnce((devtool: Configuration['devtool']) => {
  console.warn(
    chalk.yellow.bold('Warning: ') +
      chalk.bold(`Reverting webpack devtool to '${devtool}'.\n`) +
      'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
      'Read more: https://err.sh/next.js/improper-devtool'
  )
})

83
function parseJsonFile(filePath: string) {
G
json5  
Guy Bedford 已提交
84
  const JSON5 = require('next/dist/compiled/json5')
85
  const contents = readFileSync(filePath, 'utf8')
86 87 88 89 90 91

  // Special case an empty file
  if (contents.trim() === '') {
    return {}
  }

92 93 94 95 96 97 98 99
  try {
    return JSON5.parse(contents)
  } catch (err) {
    const codeFrame = codeFrameColumns(
      String(contents),
      { start: { line: err.lineNumber, column: err.columnNumber } },
      { message: err.message, highlightCode: true }
    )
100
    throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`)
101
  }
102 103
}

104
function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
105 106 107 108
  if (isServer) {
    return {}
  }

109
  const stubWindowFetch = path.join(__dirname, 'polyfills', 'fetch', 'index.js')
110 111 112
  const stubObjectAssign = path.join(__dirname, 'polyfills', 'object-assign.js')

  const shimAssign = path.join(__dirname, 'polyfills', 'object.assign')
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
  return Object.assign(
    {},
    {
      unfetch$: stubWindowFetch,
      'isomorphic-unfetch$': stubWindowFetch,
      'whatwg-fetch$': path.join(
        __dirname,
        'polyfills',
        'fetch',
        'whatwg-fetch.js'
      ),
    },
    {
      'object-assign$': stubObjectAssign,

      // Stub Package: object.assign
      'object.assign/auto': path.join(shimAssign, 'auto.js'),
      'object.assign/implementation': path.join(
        shimAssign,
        'implementation.js'
      ),
      'object.assign$': path.join(shimAssign, 'index.js'),
      'object.assign/polyfill': path.join(shimAssign, 'polyfill.js'),
      'object.assign/shim': path.join(shimAssign, 'shim.js'),

138 139
      // Replace: full URL polyfill with platform-based polyfill
      url: require.resolve('native-url'),
140 141
    }
  )
142 143
}

144
type ClientEntries = {
145
  [key: string]: string | string[]
146 147
}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
export function attachReactRefresh(
  webpackConfig: webpack.Configuration,
  targetLoader: webpack.RuleSetUseItem
) {
  let injections = 0
  const reactRefreshLoaderName = '@next/react-refresh-utils/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]

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

  if (injections) {
    Log.info(
      `automatically enabled Fast Refresh for ${injections} custom loader${
        injections > 1 ? 's' : ''
      }`
    )
  }
}

188 189 190 191 192
export default async function getBaseWebpackConfig(
  dir: string,
  {
    buildId,
    config,
J
JJ Kasper 已提交
193 194 195 196
    dev = false,
    isServer = false,
    pagesDir,
    tracer,
197
    target = 'server',
198
    reactProductionProfiling = false,
199
    entrypoints,
200
    rewrites,
201 202
  }: {
    buildId: string
203
    config: NextConfig
J
JJ Kasper 已提交
204 205 206
    dev?: boolean
    isServer?: boolean
    pagesDir: string
207
    target?: string
J
JJ Kasper 已提交
208
    tracer?: any
209
    reactProductionProfiling?: boolean
210
    entrypoints: WebpackEntrypoints
211
    rewrites: Rewrite[]
212 213
  }
): Promise<webpack.Configuration> {
214 215 216
  let plugins: PluginMetaData[] = []
  let babelPresetPlugins: { dir: string; config: any }[] = []

217 218
  const hasRewrites = rewrites.length > 0 || dev

219 220 221 222 223 224 225 226 227 228 229 230 231
  if (config.experimental.plugins) {
    plugins = await collectPlugins(dir, config.env, config.plugins)
    pluginLoaderOptions.plugins = plugins

    for (const plugin of plugins) {
      if (plugin.middleware.includes('babel-preset-build')) {
        babelPresetPlugins.push({
          dir: plugin.directory,
          config: plugin.config,
        })
      }
    }
  }
232

233 234 235 236 237 238 239
  const reactVersion = await getPackageVersion({ cwd: dir, name: 'react' })
  const hasReactRefresh: boolean = dev && !isServer
  const hasJsxRuntime: boolean =
    Boolean(reactVersion) &&
    // 17.0.0-rc.0 had a breaking change not compatible with Next.js, but was
    // fixed in rc.1.
    semver.gte(reactVersion!, '17.0.0-rc.1')
240

241
  const distDir = path.join(dir, config.distDir)
T
Tim Neutkens 已提交
242 243
  const defaultLoaders = {
    babel: {
244
      loader: 'next-babel-loader',
245 246 247
      options: {
        isServer,
        distDir,
J
JJ Kasper 已提交
248
        pagesDir,
249
        cwd: dir,
250
        // Webpack 5 has a built-in loader cache
251
        cache: !isWebpack5,
252
        babelPresetPlugins,
253
        development: dev,
254
        hasReactRefresh,
255
        hasJsxRuntime,
256
      },
257
    },
258
    // Backwards compat
259
    hotSelfAccept: {
260 261
      loader: 'noop-loader',
    },
T
Tim Neutkens 已提交
262 263
  }

264 265 266 267 268 269
  const babelIncludeRegexes: RegExp[] = [
    /next[\\/]dist[\\/]next-server[\\/]lib/,
    /next[\\/]dist[\\/]client/,
    /next[\\/]dist[\\/]pages/,
    /[\\/](strip-ansi|ansi-regex)[\\/]/,
    ...(config.experimental.plugins
J
Joe Haddad 已提交
270
      ? VALID_MIDDLEWARE.map((name) => new RegExp(`src(\\\\|/)${name}`))
271 272 273
      : []),
  ]

T
Tim Neutkens 已提交
274 275 276
  // Support for NODE_PATH
  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
J
Joe Haddad 已提交
277
    .filter((p) => !!p)
T
Tim Neutkens 已提交
278

279 280 281 282 283 284
  const isServerless = target === 'serverless'
  const isServerlessTrace = target === 'experimental-serverless-trace'
  // Intentionally not using isTargetLikeServerless helper
  const isLikeServerless = isServerless || isServerlessTrace

  const outputDir = isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
T
Tim Neutkens 已提交
285
  const outputPath = path.join(distDir, isServer ? outputDir : '')
286
  const totalPages = Object.keys(entrypoints).length
287
  const clientEntries = !isServer
288
    ? ({
289 290 291
        // Backwards compatibility
        'main.js': [],
        [CLIENT_STATIC_FILES_RUNTIME_MAIN]:
292 293 294 295 296 297 298 299
          `./` +
          path
            .relative(
              dir,
              path.join(
                NEXT_PROJECT_ROOT_DIST_CLIENT,
                dev ? `next-dev.js` : 'next.js'
              )
300
            )
301
            .replace(/\\/g, '/'),
302 303
        [CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join(
          NEXT_PROJECT_ROOT_DIST_CLIENT,
304
          'polyfills.js'
305
        ),
306
      } as ClientEntries)
307
    : undefined
N
nkzawa 已提交
308

309
  let typeScriptPath: string | undefined
310
  try {
311
    typeScriptPath = resolveRequest('typescript', `${dir}/`)
312
  } catch (_) {}
313
  const tsConfigPath = path.join(dir, 'tsconfig.json')
314 315 316
  const useTypeScript = Boolean(
    typeScriptPath && (await fileExists(tsConfigPath))
  )
317

318 319 320
  let jsConfig
  // jsconfig is a subset of tsconfig
  if (useTypeScript) {
321
    const ts = (await import(typeScriptPath!)) as typeof import('typescript')
322 323
    const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath)
    jsConfig = { compilerOptions: tsConfig.options }
324 325 326 327
  }

  const jsConfigPath = path.join(dir, 'jsconfig.json')
  if (!useTypeScript && (await fileExists(jsConfigPath))) {
328
    jsConfig = parseJsonFile(jsConfigPath)
329 330 331 332 333 334 335
  }

  let resolvedBaseUrl
  if (jsConfig?.compilerOptions?.baseUrl) {
    resolvedBaseUrl = path.resolve(dir, jsConfig.compilerOptions.baseUrl)
  }

336
  function getReactProfilingInProduction() {
337
    if (reactProductionProfiling) {
338 339 340 341 342 343 344
      return {
        'react-dom$': 'react-dom/profiling',
        'scheduler/tracing': 'scheduler/tracing-profiling',
      }
    }
  }

345 346 347 348
  const clientResolveRewrites = require.resolve(
    'next/dist/next-server/lib/router/utils/resolve-rewrites'
  )

T
Tim Neutkens 已提交
349
  const resolveConfig = {
350
    // Disable .mjs for node_modules bundling
351
    extensions: isServer
352 353 354
      ? [
          '.js',
          '.mjs',
355
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
356 357 358 359 360 361 362
          '.jsx',
          '.json',
          '.wasm',
        ]
      : [
          '.mjs',
          '.js',
363
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
364 365 366 367
          '.jsx',
          '.json',
          '.wasm',
        ],
T
Tim Neutkens 已提交
368 369
    modules: [
      'node_modules',
370
      ...nodePathList, // Support for NODE_PATH environment variable
T
Tim Neutkens 已提交
371 372
    ],
    alias: {
373 374 375
      next: NEXT_PROJECT_ROOT,
      ...(isWebpack5 && !isServer
        ? {
T
Tim Neutkens 已提交
376 377 378 379 380
            stream: require.resolve('stream-browserify'),
            path: require.resolve('path-browserify'),
            crypto: require.resolve('crypto-browserify'),
            buffer: require.resolve('buffer'),
            vm: require.resolve('vm-browserify'),
381 382
          }
        : undefined),
J
JJ Kasper 已提交
383
      [PAGES_DIR_ALIAS]: pagesDir,
384
      [DOT_NEXT_ALIAS]: distDir,
385
      ...getOptimizedAliases(isServer),
386
      ...getReactProfilingInProduction(),
387 388 389
      [clientResolveRewrites]: hasRewrites
        ? clientResolveRewrites
        : require.resolve('next/dist/client/dev/noop.js'),
390
    },
391
    mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
392 393 394
    plugins: isWebpack5
      ? // webpack 5+ has the PnP resolver built-in by default:
        []
395
      : [require('pnp-webpack-plugin')],
T
Tim Neutkens 已提交
396 397
  }

T
Tim Neutkens 已提交
398 399
  const webpackMode = dev ? 'development' : 'production'

400
  const terserOptions: any = {
401 402 403 404 405 406 407 408
    parse: {
      ecma: 8,
    },
    compress: {
      ecma: 5,
      warnings: false,
      // The following two options are known to break valid JavaScript code
      comparisons: false,
409
      inline: 2, // https://github.com/vercel/next.js/issues/7178#issuecomment-493048965
410 411 412 413 414 415 416 417 418 419 420
    },
    mangle: { safari10: true },
    output: {
      ecma: 5,
      safari10: true,
      comments: false,
      // Fixes usage of Emoji and certain Regex
      ascii_only: true,
    },
  }

421 422 423 424 425 426 427 428 429 430 431
  const isModuleCSS = (module: { type: string }): boolean => {
    return (
      // mini-css-extract-plugin
      module.type === `css/mini-extract` ||
      // extract-css-chunks-webpack-plugin (old)
      module.type === `css/extract-chunks` ||
      // extract-css-chunks-webpack-plugin (new)
      module.type === `css/extract-css-chunks`
    )
  }

432 433 434 435 436 437 438 439
  // Contains various versions of the Webpack SplitChunksPlugin used in different build types
  const splitChunksConfigs: {
    [propName: string]: webpack.Options.SplitChunksOptions
  } = {
    dev: {
      cacheGroups: {
        default: false,
        vendors: false,
440 441
        // In webpack 5 vendors was renamed to defaultVendors
        defaultVendors: false,
442 443
      },
    },
444
    prodGranular: {
445
      chunks: 'all',
446 447 448
      cacheGroups: {
        default: false,
        vendors: false,
449 450
        // In webpack 5 vendors was renamed to defaultVendors
        defaultVendors: false,
451
        framework: {
452
          chunks: 'all',
453
          name: 'framework',
A
Alex Castle 已提交
454
          // This regex ignores nested copies of framework libraries so they're
455
          // bundled with their issuer.
456
          // https://github.com/vercel/next.js/pull/9012
457
          test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/,
458
          priority: 40,
J
Joe Haddad 已提交
459 460 461
          // Don't let webpack eliminate this chunk (prevents this chunk from
          // becoming a part of the commons chunk)
          enforce: true,
462 463 464 465 466 467 468 469
        },
        lib: {
          test(module: { size: Function; identifier: Function }): boolean {
            return (
              module.size() > 160000 &&
              /node_modules[/\\]/.test(module.identifier())
            )
          },
J
Joe Haddad 已提交
470 471 472 473 474 475
          name(module: {
            type: string
            libIdent?: Function
            updateHash: (hash: crypto.Hash) => void
          }): string {
            const hash = crypto.createHash('sha1')
476
            if (isModuleCSS(module)) {
J
Joe Haddad 已提交
477 478 479 480 481 482 483 484 485 486 487
              module.updateHash(hash)
            } else {
              if (!module.libIdent) {
                throw new Error(
                  `Encountered unknown module type: ${module.type}. Please open an issue.`
                )
              }

              hash.update(module.libIdent({ context: dir }))
            }

488
            return hash.digest('hex').substring(0, 8)
489 490 491 492 493 494
          },
          priority: 30,
          minChunks: 1,
          reuseExistingChunk: true,
        },
        commons: {
495
          name: 'commons',
496 497 498 499 500
          minChunks: totalPages,
          priority: 20,
        },
        shared: {
          name(module, chunks) {
501
            return (
502
              crypto
503 504 505 506 507 508 509 510
                .createHash('sha1')
                .update(
                  chunks.reduce(
                    (acc: string, chunk: webpack.compilation.Chunk) => {
                      return acc + chunk.name
                    },
                    ''
                  )
511
                )
512
                .digest('hex') + (isModuleCSS(module) ? '_CSS' : '')
513
            )
514 515 516 517 518 519
          },
          priority: 10,
          minChunks: 2,
          reuseExistingChunk: true,
        },
      },
520 521
      maxInitialRequests: 25,
      minSize: 20000,
522
    },
523 524 525 526 527 528 529
  }

  // Select appropriate SplitChunksPlugin config for this build
  let splitChunksConfig: webpack.Options.SplitChunksOptions
  if (dev) {
    splitChunksConfig = splitChunksConfigs.dev
  } else {
530
    splitChunksConfig = splitChunksConfigs.prodGranular
531 532
  }

533
  const crossOrigin = config.crossOrigin
534

535 536 537 538 539
  let customAppFile: string | null = await findPageFile(
    pagesDir,
    '/_app',
    config.pageExtensions
  )
J
Joe Haddad 已提交
540
  if (customAppFile) {
541
    customAppFile = path.resolve(path.join(pagesDir, customAppFile))
J
Joe Haddad 已提交
542 543
  }

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
  const conformanceConfig = Object.assign(
    {
      ReactSyncScriptsConformanceCheck: {
        enabled: true,
      },
      MinificationConformanceCheck: {
        enabled: true,
      },
      DuplicatePolyfillsConformanceCheck: {
        enabled: true,
        BlockedAPIToBePolyfilled: Object.assign(
          [],
          ['fetch'],
          config.conformance?.DuplicatePolyfillsConformanceCheck
            ?.BlockedAPIToBePolyfilled || []
        ),
      },
561 562 563
      GranularChunksConformanceCheck: {
        enabled: true,
      },
564 565 566
    },
    config.conformance
  )
567

568 569 570 571
  function handleExternals(context: any, request: any, callback: any) {
    if (request === 'next') {
      return callback(undefined, `commonjs ${request}`)
    }
K
k-kawakami 已提交
572

573 574 575 576
    const notExternalModules = [
      'next/app',
      'next/document',
      'next/link',
A
Alex Castle 已提交
577
      'next/image',
578 579 580 581 582 583 584 585
      'next/error',
      'string-hash',
      'next/constants',
    ]

    if (notExternalModules.indexOf(request) !== -1) {
      return callback()
    }
586

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    // We need to externalize internal requests for files intended to
    // not be bundled.

    const isLocal: boolean =
      request.startsWith('.') ||
      // Always check for unix-style path, as webpack sometimes
      // normalizes as posix.
      path.posix.isAbsolute(request) ||
      // When on Windows, we also want to check for Windows-specific
      // absolute paths.
      (process.platform === 'win32' && path.win32.isAbsolute(request))
    const isLikelyNextExternal =
      isLocal && /[/\\]next-server[/\\]/.test(request)

    // Relative requires don't need custom resolution, because they
    // are relative to requests we've already resolved here.
    // Absolute requires (require('/foo')) are extremely uncommon, but
    // also have no need for customization as they're already resolved.
    if (isLocal && !isLikelyNextExternal) {
      return callback()
    }
K
k-kawakami 已提交
608

609 610 611 612 613 614 615 616 617 618 619 620
    // Resolve the import with the webpack provided context, this
    // ensures we're resolving the correct version when multiple
    // exist.
    let res: string
    try {
      res = resolveRequest(request, `${context}/`)
    } catch (err) {
      // If the request cannot be resolved, we need to tell webpack to
      // "bundle" it so that webpack shows an error (that it cannot be
      // resolved).
      return callback()
    }
K
k-kawakami 已提交
621

622 623 624 625 626
    // Same as above, if the request cannot be resolved we need to have
    // webpack "bundle" it so it surfaces the not found error.
    if (!res) {
      return callback()
    }
627

628 629 630 631 632 633 634
    let isNextExternal: boolean = false
    if (isLocal) {
      // we need to process next-server/lib/router/router so that
      // the DefinePlugin can inject process.env values
      isNextExternal = /next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/.test(
        res
      )
635

636 637 638 639
      if (!isNextExternal) {
        return callback()
      }
    }
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    // `isNextExternal` special cases Next.js' internal requires that
    // should not be bundled. We need to skip the base resolve routine
    // to prevent it from being bundled (assumes Next.js version cannot
    // mismatch).
    if (!isNextExternal) {
      // Bundled Node.js code is relocated without its node_modules tree.
      // This means we need to make sure its request resolves to the same
      // package that'll be available at runtime. If it's not identical,
      // we need to bundle the code (even if it _should_ be external).
      let baseRes: string | null
      try {
        baseRes = resolveRequest(request, `${dir}/`)
      } catch (err) {
        baseRes = null
      }
656

657 658 659
      // Same as above: if the package, when required from the root,
      // would be different from what the real resolution would use, we
      // cannot externalize it.
660 661 662 663 664 665
      if (
        !baseRes ||
        (baseRes !== res &&
          // if res and baseRes are symlinks they could point to the the same file
          realpathSync(baseRes) !== realpathSync(res))
      ) {
666 667 668
        return callback()
      }
    }
K
k-kawakami 已提交
669

670 671 672 673 674 675 676 677 678
    // Default pages have to be transpiled
    if (
      !res.match(/next[/\\]dist[/\\]next-server[/\\]/) &&
      (res.match(/[/\\]next[/\\]dist[/\\]/) ||
        // This is the @babel/plugin-transform-runtime "helpers: true" option
        res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/))
    ) {
      return callback()
    }
K
k-kawakami 已提交
679

680 681 682 683 684 685 686
    // Webpack itself has to be compiled because it doesn't always use module relative paths
    if (
      res.match(/node_modules[/\\]webpack/) ||
      res.match(/node_modules[/\\]css-loader/)
    ) {
      return callback()
    }
687

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    // Anything else that is standard JavaScript within `node_modules`
    // can be externalized.
    if (isNextExternal || res.match(/node_modules[/\\].*\.js$/)) {
      const externalRequest = isNextExternal
        ? // Generate Next.js external import
          path.posix.join(
            'next',
            'dist',
            path
              .relative(
                // Root of Next.js package:
                path.join(__dirname, '..'),
                res
              )
              // Windows path normalization
              .replace(/\\/g, '/')
          )
        : request
K
k-kawakami 已提交
706

707 708 709 710 711 712 713
      return callback(undefined, `commonjs ${externalRequest}`)
    }

    // Default behavior: bundle the code!
    callback()
  }

L
Luke Fender 已提交
714 715
  const emacsLockfilePattern = '**/.#*'

716 717 718 719 720 721 722 723 724 725 726 727 728
  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),
729 730
        ]
      : [
731 732
          // When the 'serverless' target is used all node_modules will be compiled into the output bundles
          // So that the 'serverless' bundles have 0 runtime dependencies
733
          '@ampproject/toolbox-optimizer', // except this one
J
Janicklas Ralph 已提交
734 735 736 737

          // Mark this as external if not enabled so it doesn't cause a
          // webpack error from being missing
          ...(config.experimental.optimizeCss ? [] : ['critters']),
738
        ],
739
    optimization: {
740 741
      // Webpack 5 uses a new property for the same functionality
      ...(isWebpack5 ? { emitOnErrors: !dev } : { noEmitOnErrors: dev }),
742 743 744 745
      checkWasmTypes: false,
      nodeEnv: false,
      splitChunks: isServer ? false : splitChunksConfig,
      runtimeChunk: isServer
746 747 748
        ? isWebpack5 && !isLikeServerless
          ? { name: 'webpack-runtime' }
          : undefined
749 750 751
        : { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK },
      minimize: !(dev || isServer),
      minimizer: [
J
Joe Haddad 已提交
752
        // Minify JavaScript
753
        new TerserPlugin({
754 755
          cacheDir: path.join(distDir, 'cache', 'next-minifier'),
          parallel: config.experimental.cpus,
756 757
          terserOptions,
        }),
J
Joe Haddad 已提交
758
        // Minify CSS
759 760 761 762 763 764 765 766 767
        new CssMinimizerPlugin({
          postcssOptions: {
            map: {
              // `inline: false` generates the source map in a separate file.
              // Otherwise, the CSS file is needlessly large.
              inline: false,
              // `annotation: false` skips appending the `sourceMappingURL`
              // to the end of the CSS file. Webpack already handles this.
              annotation: false,
J
Joe Haddad 已提交
768
            },
769 770 771
          },
        }),
      ],
772
    },
N
nkzawa 已提交
773
    context: dir,
774 775 776
    node: {
      setImmediate: false,
    },
777
    // Kept as function to be backwards compatible
T
Tim Neutkens 已提交
778 779
    entry: async () => {
      return {
780 781
        ...(clientEntries ? clientEntries : {}),
        ...entrypoints,
782 783 784 785 786 787 788
        ...(isServer
          ? {
              'init-server.js': 'next-plugin-loader?middleware=on-init-server!',
              'on-error-server.js':
                'next-plugin-loader?middleware=on-error-server!',
            }
          : {}),
T
Tim Neutkens 已提交
789 790
      }
    },
791
    watchOptions: {
L
Luke Fender 已提交
792 793 794 795 796 797 798
      ignored: [
        '**/.git/**',
        '**/node_modules/**',
        '**/.next/**',
        // can be removed after https://github.com/paulmillr/chokidar/issues/955 is released
        emacsLockfilePattern,
      ],
799
    },
N
nkzawa 已提交
800
    output: {
801 802 803 804 805 806 807 808 809 810 811 812 813
      ...(isWebpack5
        ? {
            environment: {
              arrowFunction: false,
              bigIntLiteral: false,
              const: false,
              destructuring: false,
              dynamicImport: false,
              forOf: false,
              module: false,
            },
          }
        : {}),
814
      path: outputPath,
815
      // On the server we don't use the chunkhash
816 817 818
      filename: isServer
        ? '[name].js'
        : `static/chunks/[name]${dev ? '' : '-[chunkhash]'}.js`,
819 820
      library: isServer ? undefined : '_N_E',
      libraryTarget: isServer ? 'commonjs2' : 'assign',
821 822 823 824 825 826
      hotUpdateChunkFilename: isWebpack5
        ? 'static/webpack/[id].[fullhash].hot-update.js'
        : 'static/webpack/[id].[hash].hot-update.js',
      hotUpdateMainFilename: isWebpack5
        ? 'static/webpack/[fullhash].hot-update.json'
        : 'static/webpack/[hash].hot-update.json',
827
      // This saves chunks with the name given via `import()`
828 829 830
      chunkFilename: isServer
        ? `${dev ? '[name]' : '[name].[contenthash]'}.js`
        : `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
A
Andy 已提交
831
      strictModuleExceptionHandling: true,
832
      crossOriginLoading: crossOrigin,
833
      futureEmitAssets: !dev,
834
      webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
N
nkzawa 已提交
835
    },
836
    performance: false,
T
Tim Neutkens 已提交
837
    resolve: resolveConfig,
N
nkzawa 已提交
838
    resolveLoader: {
839 840 841
      // The loaders Next.js provides
      alias: [
        'emit-file-loader',
842
        'error-loader',
843 844 845 846 847
        'next-babel-loader',
        'next-client-pages-loader',
        'next-data-loader',
        'next-serverless-loader',
        'noop-loader',
848
        'next-plugin-loader',
849 850 851
      ].reduce((alias, loader) => {
        // using multiple aliases to replace `resolveLoader.modules`
        alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
852

853 854
        return alias
      }, {} as Record<string, string>),
N
Naoyuki Kanezawa 已提交
855
      modules: [
856
        'node_modules',
857 858
        ...nodePathList, // Support for NODE_PATH environment variable
      ],
859
      plugins: isWebpack5 ? [] : [require('pnp-webpack-plugin')],
N
nkzawa 已提交
860 861
    },
    module: {
862
      rules: [
J
JJ Kasper 已提交
863 864 865 866 867 868 869 870 871 872 873 874
        ...(isWebpack5
          ? [
              // TODO: FIXME: do NOT webpack 5 support with this
              // x-ref: https://github.com/webpack/webpack/issues/11467
              {
                test: /\.m?js/,
                resolve: {
                  fullySpecified: false,
                },
              } as any,
            ]
          : []),
T
Tim Neutkens 已提交
875
        {
876
          test: /\.(tsx|ts|js|mjs|jsx)$/,
877
          include: [dir, ...babelIncludeRegexes],
878 879
          exclude: (excludePath: string) => {
            if (babelIncludeRegexes.some((r) => r.test(excludePath))) {
880 881
              return false
            }
882
            return /node_modules/.test(excludePath)
883
          },
884 885 886 887 888
          use: config.experimental.babelMultiThread
            ? [
                // Move Babel transpilation into a thread pool (2 workers, unlimited batch size).
                // Applying a cache to the off-thread work avoids paying transfer costs for unchanged modules.
                {
G
Guy Bedford 已提交
889
                  loader: 'next/dist/compiled/cache-loader',
890 891 892
                  options: {
                    cacheContext: dir,
                    cacheDirectory: path.join(dir, '.next', 'cache', 'webpack'),
893
                    cacheIdentifier: `webpack${isServer ? '-server' : ''}`,
894 895 896
                  },
                },
                {
G
Guy Bedford 已提交
897
                  loader: require.resolve('next/dist/compiled/thread-loader'),
898 899 900 901 902
                  options: {
                    workers: 2,
                    workerParallelJobs: Infinity,
                  },
                },
903 904 905
                hasReactRefresh
                  ? require.resolve('@next/react-refresh-utils/loader')
                  : '',
906
                defaultLoaders.babel,
907 908 909 910
              ].filter(Boolean)
            : hasReactRefresh
            ? [
                require.resolve('@next/react-refresh-utils/loader'),
911
                defaultLoaders.babel,
912 913
              ]
            : defaultLoaders.babel,
914
        },
915
      ].filter(Boolean),
N
nkzawa 已提交
916
    },
T
Tim Neutkens 已提交
917
    plugins: [
918
      hasReactRefresh && new ReactRefreshWebpackPlugin(),
919 920 921 922 923 924 925 926
      // Makes sure `Buffer` is polyfilled in client-side bundles (same behavior as webpack 4)
      isWebpack5 &&
        !isServer &&
        new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }),
      // Makes sure `process` is polyfilled in client-side bundles (same behavior as webpack 4)
      isWebpack5 &&
        !isServer &&
        new webpack.ProvidePlugin({ process: ['process'] }),
927
      // This plugin makes sure `output.filename` is used for entry chunks
T
Tim Neutkens 已提交
928
      !isWebpack5 && new ChunkNamesPlugin(),
929
      new webpack.DefinePlugin({
930 931 932 933 934 935 936 937 938
        ...Object.keys(process.env).reduce(
          (prev: { [key: string]: string }, key: string) => {
            if (key.startsWith('NEXT_PUBLIC_')) {
              prev[`process.env.${key}`] = JSON.stringify(process.env[key]!)
            }
            return prev
          },
          {}
        ),
939
        ...Object.keys(config.env).reduce((acc, key) => {
940
          if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
941
            throw new Error(
942
              `The key "${key}" under "env" in next.config.js is not allowed. https://err.sh/vercel/next.js/env-key-not-allowed`
943
            )
944 945 946
          }

          return {
947
            ...acc,
948
            [`process.env.${key}`]: JSON.stringify(config.env[key]),
949
          }
950
        }, {}),
951
        'process.env.NODE_ENV': JSON.stringify(webpackMode),
952
        'process.env.__NEXT_CROSS_ORIGIN': JSON.stringify(crossOrigin),
953
        'process.browser': JSON.stringify(!isServer),
J
JJ Kasper 已提交
954 955 956
        'process.env.__NEXT_TEST_MODE': JSON.stringify(
          process.env.__NEXT_TEST_MODE
        ),
957
        // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
958 959 960 961 962
        ...(dev && !isServer
          ? {
              'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
            }
          : {}),
J
Jan Potoms 已提交
963
        'process.env.__NEXT_TRAILING_SLASH': JSON.stringify(
964
          config.trailingSlash
J
Jan Potoms 已提交
965
        ),
966 967 968
        'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify(
          config.devIndicators.buildActivity
        ),
969 970 971
        'process.env.__NEXT_PLUGINS': JSON.stringify(
          config.experimental.plugins
        ),
G
Gerald Monaco 已提交
972 973 974
        'process.env.__NEXT_STRICT_MODE': JSON.stringify(
          config.reactStrictMode
        ),
975 976 977
        'process.env.__NEXT_REACT_MODE': JSON.stringify(
          config.experimental.reactMode
        ),
978 979 980
        'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
          config.experimental.optimizeFonts && !dev
        ),
981 982 983
        'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify(
          config.experimental.optimizeImages
        ),
J
Janicklas Ralph 已提交
984 985 986
        'process.env.__NEXT_OPTIMIZE_CSS': JSON.stringify(
          !!config.experimental.optimizeCss && !dev
        ),
987 988 989
        'process.env.__NEXT_SCROLL_RESTORATION': JSON.stringify(
          config.experimental.scrollRestoration
        ),
990
        'process.env.__NEXT_IMAGE_OPTS': JSON.stringify({
991
          deviceSizes: config.images.deviceSizes,
992
          imageSizes: config.images.imageSizes,
993 994
          path: config.images.path,
          loader: config.images.loader,
995 996 997 998 999 1000
          ...(dev
            ? {
                // pass domains in development to allow validating on the client
                domains: config.images.domains,
              }
            : {}),
1001
        }),
1002
        'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
1003
        'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
J
Joe Haddad 已提交
1004
        'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
1005
        'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
1006
        'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
1007
        ...(isServer
1008 1009 1010 1011 1012 1013
          ? {
              // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
              // This is typically found in unmaintained modules from the
              // pre-webpack era (common in server-side code)
              'global.GENTLY': JSON.stringify(false),
            }
1014
          : undefined),
1015
        // stub process.env with proxy to warn a missing value is
1016 1017
        // being accessed in development mode
        ...(config.experimental.pageEnv && process.env.NODE_ENV !== 'production'
1018
          ? {
1019
              'process.env': `
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            new Proxy(${isServer ? 'process.env' : '{}'}, {
              get(target, prop) {
                if (typeof target[prop] === 'undefined') {
                  console.warn(\`An environment variable (\${prop}) that was not provided in the environment was accessed.\nSee more info here: https://err.sh/next.js/missing-env-value\`)
                }
                return target[prop]
              }
            })
          `,
            }
          : {}),
1031
      }),
1032 1033 1034 1035
      !isServer &&
        new ReactLoadablePlugin({
          filename: REACT_LOADABLE_MANIFEST,
        }),
1036
      !isServer && new DropClientPage(),
1037 1038 1039 1040 1041
      // Moment.js is an extremely popular library that bundles large locale files
      // by default due to how Webpack interprets its code. This is a practical
      // solution that requires the user to opt into importing specific locales.
      // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
      config.future.excludeDefaultMomentLocales &&
1042 1043 1044 1045
        new webpack.IgnorePlugin({
          resourceRegExp: /^\.\/locale$/,
          contextRegExp: /moment$/,
        }),
1046 1047 1048 1049 1050 1051 1052
      ...(dev
        ? (() => {
            // Even though require.cache is server only we have to clear assets from both compilations
            // This is because the client compilation generates the build manifest that's used on the server side
            const {
              NextJsRequireCacheHotReloader,
            } = require('./webpack/plugins/nextjs-require-cache-hot-reloader')
1053
            const devPlugins = [new NextJsRequireCacheHotReloader()]
1054

1055
            if (!isServer) {
1056 1057
              devPlugins.push(new webpack.HotModuleReplacementPlugin())
            }
1058

1059 1060 1061
            return devPlugins
          })()
        : []),
1062 1063
      // Webpack 5 no longer requires this plugin in production:
      !isWebpack5 && !dev && new webpack.HashedModuleIdsPlugin(),
1064 1065
      !dev &&
        new webpack.IgnorePlugin({
1066 1067
          resourceRegExp: /react-is/,
          contextRegExp: /(next-server|next)[\\/]dist[\\/]/,
1068
        }),
J
Joe Haddad 已提交
1069
      isServerless && isServer && new ServerlessPlugin(),
1070
      isServer && new PagesManifestPlugin(isLikeServerless),
1071 1072
      !isWebpack5 &&
        target === 'server' &&
1073 1074
        isServer &&
        new NextJsSSRModuleCachePlugin({ outputPath }),
1075
      isServer && new NextJsSsrImportPlugin(),
1076 1077 1078
      !isServer &&
        new BuildManifestPlugin({
          buildId,
1079
          rewrites,
1080
        }),
1081 1082 1083
      tracer &&
        new ProfilingPlugin({
          tracer,
1084
        }),
1085 1086
      config.experimental.optimizeFonts &&
        !dev &&
P
Prateek Bhatnagar 已提交
1087
        isServer &&
J
Joe Haddad 已提交
1088 1089 1090 1091 1092 1093
        (function () {
          const {
            FontStylesheetGatheringPlugin,
          } = require('./webpack/plugins/font-stylesheet-gathering-plugin')
          return new FontStylesheetGatheringPlugin()
        })(),
1094
      config.experimental.conformance &&
1095
        !isWebpack5 &&
1096 1097
        !dev &&
        new WebpackConformancePlugin({
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
          tests: [
            !isServer &&
              conformanceConfig.MinificationConformanceCheck.enabled &&
              new MinificationConformanceCheck(),
            conformanceConfig.ReactSyncScriptsConformanceCheck.enabled &&
              new ReactSyncScriptsConformanceCheck({
                AllowedSources:
                  conformanceConfig.ReactSyncScriptsConformanceCheck
                    .allowedSources || [],
              }),
            !isServer &&
              conformanceConfig.DuplicatePolyfillsConformanceCheck.enabled &&
              new DuplicatePolyfillsConformanceCheck({
                BlockedAPIToBePolyfilled:
                  conformanceConfig.DuplicatePolyfillsConformanceCheck
                    .BlockedAPIToBePolyfilled,
              }),
1115 1116 1117 1118 1119
            !isServer &&
              conformanceConfig.GranularChunksConformanceCheck.enabled &&
              new GranularChunksConformanceCheck(
                splitChunksConfigs.prodGranular
              ),
1120
          ].filter(Boolean),
1121
        }),
J
Joe Haddad 已提交
1122
      new WellKnownErrorsPlugin(),
1123
    ].filter((Boolean as any) as ExcludesFalse),
1124
  }
1125

1126 1127 1128 1129 1130
  // Support tsconfig and jsconfig baseUrl
  if (resolvedBaseUrl) {
    webpackConfig.resolve?.modules?.push(resolvedBaseUrl)
  }

1131
  if (jsConfig?.compilerOptions?.paths && resolvedBaseUrl) {
1132
    webpackConfig.resolve?.plugins?.unshift(
1133 1134 1135 1136
      new JsConfigPathsPlugin(jsConfig.compilerOptions.paths, resolvedBaseUrl)
    )
  }

1137
  if (isWebpack5) {
1138
    // futureEmitAssets is on by default in webpack 5
1139
    delete webpackConfig.output?.futureEmitAssets
1140
    // webpack 5 no longer polyfills Node.js modules:
1141
    if (webpackConfig.node) delete webpackConfig.node.setImmediate
1142 1143 1144 1145 1146

    if (dev) {
      if (!webpackConfig.optimization) {
        webpackConfig.optimization = {}
      }
1147
      webpackConfig.optimization.providedExports = false
1148 1149
      webpackConfig.optimization.usedExports = false
    }
1150

1151 1152
    const nextPublicVariables = Object.keys(process.env)
      .reduce((acc: string[], key: string) => {
1153
        if (key.startsWith('NEXT_PUBLIC_')) {
1154
          return [...acc, `${key}=${process.env[key]}`]
1155
        }
1156 1157 1158 1159
        return acc
      }, [])
      .join('|')

1160 1161 1162 1163 1164 1165
    const nextEnvVariables = Object.keys(config.env).reduce(
      (prev: string, key: string) => {
        return `${prev}|${key}=${config.env[key]}`
      },
      ''
    )
1166

1167 1168 1169 1170 1171 1172 1173 1174
    const configVars = JSON.stringify({
      crossOrigin: config.crossOrigin,
      pageExtensions: config.pageExtensions,
      trailingSlash: config.trailingSlash,
      buildActivity: config.devIndicators.buildActivity,
      plugins: config.experimental.plugins,
      reactStrictMode: config.reactStrictMode,
      reactMode: config.experimental.reactMode,
1175
      optimizeFonts: config.experimental.optimizeFonts,
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
      optimizeImages: config.experimental.optimizeImages,
      scrollRestoration: config.experimental.scrollRestoration,
      basePath: config.basePath,
      pageEnv: config.experimental.pageEnv,
      excludeDefaultMomentLocales: config.future.excludeDefaultMomentLocales,
      assetPrefix: config.assetPrefix,
      target,
      reactProductionProfiling,
    })

    const cache: any = {
      type: 'filesystem',
      // Includes:
      //  - Next.js version
      //  - NEXT_PUBLIC_ variable values (they affect caching) TODO: make this module usage only
      //  - next.config.js `env` key
      //  - next.config.js keys that affect compilation
      version: `${process.env.__NEXT_VERSION}|${nextPublicVariables}|${nextEnvVariables}|${configVars}`,
      cacheDirectory: path.join(dir, '.next', 'cache', 'webpack'),
    }
1196

1197 1198 1199 1200
    // Adds `next.config.js` as a buildDependency when custom webpack config is provided
    if (config.webpack && config.configFile) {
      cache.buildDependencies = {
        config: [config.configFile],
1201
      }
1202
    }
1203

1204
    webpackConfig.cache = cache
1205

1206 1207
    // @ts-ignore TODO: remove ignore when webpack 5 is stable
    webpackConfig.optimization.realContentHash = false
1208 1209
  }

1210 1211 1212 1213 1214
  webpackConfig = await buildConfiguration(webpackConfig, {
    rootDirectory: dir,
    customAppFile,
    isDevelopment: dev,
    isServer,
1215
    assetPrefix: config.assetPrefix || '',
1216
    sassOptions: config.sassOptions,
1217
    productionBrowserSourceMaps: config.productionBrowserSourceMaps,
1218 1219
  })

1220
  let originalDevtool = webpackConfig.devtool
T
Tim Neutkens 已提交
1221
  if (typeof config.webpack === 'function') {
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    webpackConfig = config.webpack(webpackConfig, {
      dir,
      dev,
      isServer,
      buildId,
      config,
      defaultLoaders,
      totalPages,
      webpack,
    })
1232

J
Jeff Escalante 已提交
1233 1234 1235 1236 1237 1238 1239
    if (!webpackConfig) {
      throw new Error(
        'Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js.\n' +
          'See more info here https://err.sh/next.js/undefined-webpack-config'
      )
    }

1240 1241 1242 1243 1244
    if (dev && originalDevtool !== webpackConfig.devtool) {
      webpackConfig.devtool = originalDevtool
      devtoolRevertWarning(originalDevtool)
    }

1245
    if (typeof (webpackConfig as any).then === 'function') {
1246
      console.warn(
1247
        '> Promise returned in next config. https://err.sh/vercel/next.js/promise-in-next-config'
1248
      )
1249
    }
1250
  }
T
Tim Neutkens 已提交
1251

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
  // Backwards compat with webpack-dev-middleware options object
  if (typeof config.webpackDevMiddleware === 'function') {
    const options = config.webpackDevMiddleware({
      watchOptions: webpackConfig.watchOptions,
    })
    if (options.watchOptions) {
      webpackConfig.watchOptions = options.watchOptions
    }
  }

1262 1263 1264 1265 1266
  function canMatchCss(rule: webpack.RuleSetCondition | undefined): boolean {
    if (!rule) {
      return false
    }

1267 1268 1269 1270 1271 1272 1273 1274
    const fileNames = [
      '/tmp/test.css',
      '/tmp/test.scss',
      '/tmp/test.sass',
      '/tmp/test.less',
      '/tmp/test.styl',
    ]

J
Joe Haddad 已提交
1275
    if (rule instanceof RegExp && fileNames.some((input) => rule.test(input))) {
1276 1277 1278 1279
      return true
    }

    if (typeof rule === 'function') {
1280
      if (
J
Joe Haddad 已提交
1281
        fileNames.some((input) => {
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
          try {
            if (rule(input)) {
              return true
            }
          } catch (_) {}
          return false
        })
      ) {
        return true
      }
1292 1293 1294 1295 1296 1297 1298 1299 1300
    }

    if (Array.isArray(rule) && rule.some(canMatchCss)) {
      return true
    }

    return false
  }

1301 1302
  const hasUserCssConfig =
    webpackConfig.module?.rules.some(
J
Joe Haddad 已提交
1303
      (rule) => canMatchCss(rule.test) || canMatchCss(rule.include)
1304
    ) ?? false
1305

1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  if (hasUserCssConfig) {
    // only show warning for one build
    if (isServer) {
      console.warn(
        chalk.yellow.bold('Warning: ') +
          chalk.bold(
            'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n'
          ) +
          'See here for more info: https://err.sh/next.js/built-in-css-disabled\n'
      )
    }

    if (webpackConfig.module?.rules.length) {
      // Remove default CSS Loader
      webpackConfig.module.rules = webpackConfig.module.rules.filter(
J
Joe Haddad 已提交
1321
        (r) =>
1322 1323 1324 1325 1326
          !(
            typeof r.oneOf?.[0]?.options === 'object' &&
            r.oneOf[0].options.__next_css_remove === true
          )
      )
1327
    }
1328 1329 1330
    if (webpackConfig.plugins?.length) {
      // Disable CSS Extraction Plugin
      webpackConfig.plugins = webpackConfig.plugins.filter(
J
Joe Haddad 已提交
1331
        (p) => (p as any).__next_css_remove !== true
1332 1333 1334 1335 1336
      )
    }
    if (webpackConfig.optimization?.minimizer?.length) {
      // Disable CSS Minifier
      webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter(
J
Joe Haddad 已提交
1337
        (e) => (e as any).__next_css_remove !== true
1338 1339 1340 1341
      )
    }
  } else {
    await __overrideCssConfiguration(dir, !dev, webpackConfig)
1342 1343
  }

1344 1345 1346 1347 1348
  // Inject missing React Refresh loaders so that development mode is fast:
  if (hasReactRefresh) {
    attachReactRefresh(webpackConfig, defaultLoaders.babel)
  }

1349
  // check if using @zeit/next-typescript and show warning
1350 1351 1352
  if (
    isServer &&
    webpackConfig.module &&
1353 1354 1355 1356
    Array.isArray(webpackConfig.module.rules)
  ) {
    let foundTsRule = false

1357 1358
    webpackConfig.module.rules = webpackConfig.module.rules.filter(
      (rule): boolean => {
1359
        if (!(rule.test instanceof RegExp)) return true
1360
        if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
1361 1362 1363 1364 1365
          // remove if it matches @zeit/next-typescript
          foundTsRule = rule.use === defaultLoaders.babel
          return !foundTsRule
        }
        return true
1366 1367
      }
    )
1368 1369

    if (foundTsRule) {
1370
      console.warn(
1371
        '\n@zeit/next-typescript is no longer needed since Next.js has built-in support for TypeScript now. Please remove it from your next.config.js and your .babelrc\n'
1372
      )
1373 1374 1375
    }
  }

1376
  // Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
1377
  if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
J
Joe Haddad 已提交
1378
    ;[].forEach.call(webpackConfig.module.rules, function (
1379 1380 1381 1382 1383 1384
      rule: webpack.RuleSetRule
    ) {
      if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
        return
      }

1385 1386 1387 1388
      const isSass =
        rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
      const isLess = rule.test.source === '\\.less$'
      const isCss = rule.test.source === '\\.css$'
1389
      const isStylus = rule.test.source === '\\.styl$'
1390 1391

      // Check if the rule we're iterating over applies to Sass, Less, or CSS
1392
      if (!(isSass || isLess || isCss || isStylus)) {
1393 1394 1395
        return
      }

J
Joe Haddad 已提交
1396
      ;[].forEach.call(rule.use, function (use: webpack.RuleSetUseItem) {
1397 1398 1399 1400 1401
        if (
          !(
            use &&
            typeof use === 'object' &&
            // Identify use statements only pertaining to `css-loader`
1402 1403
            (use.loader === 'css-loader' ||
              use.loader === 'css-loader/locals') &&
1404 1405 1406 1407
            use.options &&
            typeof use.options === 'object' &&
            // The `minimize` property is a good heuristic that we need to
            // perform this hack. The `minimize` property was only valid on
1408 1409
            // old `css-loader` versions. Custom setups (that aren't next-sass,
            // next-less or next-stylus) likely have the newer version.
1410
            // We still handle this gracefully below.
1411 1412 1413 1414 1415
            (Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
              Object.prototype.hasOwnProperty.call(
                use.options,
                'exportOnlyLocals'
              ))
1416 1417 1418 1419 1420 1421 1422
          )
        ) {
          return
        }

        // Try to monkey patch within a try-catch. We shouldn't fail the build
        // if we cannot pull this off.
1423 1424
        // The user may not even be using the `next-sass` or `next-less` or
        // `next-stylus` plugins.
1425 1426
        // If it does work, great!
        try {
1427 1428
          // Resolve the version of `@zeit/next-css` as depended on by the Sass,
          // Less or Stylus plugin.
1429 1430
          const correctNextCss = resolveRequest(
            '@zeit/next-css',
1431 1432 1433 1434 1435 1436 1437 1438 1439
            isCss
              ? // Resolve `@zeit/next-css` from the base directory
                `${dir}/`
              : // Else, resolve it from the specific plugins
                require.resolve(
                  isSass
                    ? '@zeit/next-sass'
                    : isLess
                    ? '@zeit/next-less'
1440 1441
                    : isStylus
                    ? '@zeit/next-stylus'
1442 1443
                    : 'next'
                )
1444 1445 1446 1447 1448 1449 1450
          )

          // If we found `@zeit/next-css` ...
          if (correctNextCss) {
            // ... resolve the version of `css-loader` shipped with that
            // package instead of whichever was hoisted highest in your
            // `node_modules` tree.
1451
            const correctCssLoader = resolveRequest(use.loader, correctNextCss)
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
            if (correctCssLoader) {
              // We saved the user from a failed build!
              use.loader = correctCssLoader
            }
          }
        } catch (_) {
          // The error is not required to be handled.
        }
      })
    })
  }

1464
  // Backwards compat for `main.js` entry key
1465
  const originalEntry: any = webpackConfig.entry
1466 1467
  if (typeof originalEntry !== 'undefined') {
    webpackConfig.entry = async () => {
1468 1469 1470 1471
      const entry: WebpackEntrypoints =
        typeof originalEntry === 'function'
          ? await originalEntry()
          : originalEntry
1472 1473
      // Server compilation doesn't have main.js
      if (clientEntries && entry['main.js'] && entry['main.js'].length > 0) {
1474 1475 1476
        const originalFile = clientEntries[
          CLIENT_STATIC_FILES_RUNTIME_MAIN
        ] as string
1477 1478 1479 1480
        entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
          ...entry['main.js'],
          originalFile,
        ]
1481
      }
1482
      delete entry['main.js']
1483

1484
      return entry
1485 1486 1487
    }
  }

1488
  if (!dev) {
1489 1490
    // entry is always a function
    webpackConfig.entry = await (webpackConfig.entry as webpack.EntryFunc)()
1491 1492
  }

T
Tim Neutkens 已提交
1493
  return webpackConfig
N
nkzawa 已提交
1494
}