webpack-config.ts 41.7 KB
Newer Older
G
Guy Bedford 已提交
1
import chalk from 'next/dist/compiled/chalk'
2
import crypto from 'crypto'
3
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
4
import path from 'path'
5
import PnpWebpackPlugin from 'pnp-webpack-plugin'
6
import webpack from 'webpack'
7
import {
8
  DOT_NEXT_ALIAS,
9 10 11 12
  NEXT_PROJECT_ROOT,
  NEXT_PROJECT_ROOT_DIST_CLIENT,
  PAGES_DIR_ALIAS,
} from '../lib/constants'
13
import { fileExists } from '../lib/file-exists'
14
import { readFileSync } from 'fs'
15 16 17
import { resolveRequest } from '../lib/resolve-request'
import {
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
18
  CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
19 20 21
  CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
  REACT_LOADABLE_MANIFEST,
  SERVERLESS_DIRECTORY,
22
  SERVER_DIRECTORY,
23
} from '../next-server/lib/constants'
J
Joe Haddad 已提交
24
import { findPageFile } from '../server/lib/find-page-file'
25
import { WebpackEntrypoints } from './entries'
J
Joe Haddad 已提交
26 27 28 29 30
import {
  collectPlugins,
  PluginMetaData,
  VALID_MIDDLEWARE,
} from './plugins/collect-plugins'
31
import { build as buildConfiguration } from './webpack/config'
32
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
J
Joe Haddad 已提交
33
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
34 35
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
J
Joe Haddad 已提交
36
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin'
37
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
38
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
39 40 41
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'
42
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
43 44 45
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
46
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
47 48
import WebpackConformancePlugin, {
  MinificationConformanceCheck,
49 50
  ReactSyncScriptsConformanceCheck,
  DuplicatePolyfillsConformanceCheck,
51
} from './webpack/plugins/webpack-conformance-plugin'
52

53
type ExcludesFalse = <T>(x: T | false) => x is T
54

55 56 57 58 59 60
const escapePathVariables = (value: any) => {
  return typeof value === 'string'
    ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, '[\\$1\\]')
    : value
}

61
function parseJsonFile(path: string) {
G
json5  
Guy Bedford 已提交
62
  const JSON5 = require('next/dist/compiled/json5')
63 64 65 66
  const contents = readFileSync(path)
  return JSON5.parse(contents)
}

67
function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
68 69 70 71
  if (isServer) {
    return {}
  }

72
  const stubWindowFetch = path.join(__dirname, 'polyfills', 'fetch', 'index.js')
73 74 75
  const stubObjectAssign = path.join(__dirname, 'polyfills', 'object-assign.js')

  const shimAssign = path.join(__dirname, 'polyfills', 'object.assign')
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  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'),

101 102
      // Replace: full URL polyfill with platform-based polyfill
      url: require.resolve('native-url'),
103 104
    }
  )
105 106
}

107 108 109 110 111 112
type ClientEntries = {
  'main.js': string[]
} & {
  [key: string]: string
}

113 114 115 116 117
export default async function getBaseWebpackConfig(
  dir: string,
  {
    buildId,
    config,
J
JJ Kasper 已提交
118 119 120 121
    dev = false,
    isServer = false,
    pagesDir,
    tracer,
122 123 124 125 126
    target = 'server',
    entrypoints,
  }: {
    buildId: string
    config: any
J
JJ Kasper 已提交
127 128 129
    dev?: boolean
    isServer?: boolean
    pagesDir: string
130
    target?: string
J
JJ Kasper 已提交
131
    tracer?: any
132 133 134
    entrypoints: WebpackEntrypoints
  }
): Promise<webpack.Configuration> {
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  let plugins: PluginMetaData[] = []
  let babelPresetPlugins: { dir: string; config: any }[] = []

  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,
        })
      }
    }
  }
151
  const distDir = path.join(dir, config.distDir)
T
Tim Neutkens 已提交
152 153
  const defaultLoaders = {
    babel: {
154
      loader: 'next-babel-loader',
155 156 157
      options: {
        isServer,
        distDir,
J
JJ Kasper 已提交
158
        pagesDir,
159
        cwd: dir,
160
        cache: true,
161 162
        babelPresetPlugins,
        hasModern: !!config.experimental.modern,
163
        development: dev,
164
      },
165
    },
166
    // Backwards compat
167
    hotSelfAccept: {
168 169
      loader: 'noop-loader',
    },
T
Tim Neutkens 已提交
170 171
  }

172 173 174 175 176 177
  const babelIncludeRegexes: RegExp[] = [
    /next[\\/]dist[\\/]next-server[\\/]lib/,
    /next[\\/]dist[\\/]client/,
    /next[\\/]dist[\\/]pages/,
    /[\\/](strip-ansi|ansi-regex)[\\/]/,
    ...(config.experimental.plugins
J
JJ Kasper 已提交
178
      ? VALID_MIDDLEWARE.map(name => new RegExp(`src(\\\\|/)${name}`))
179 180 181
      : []),
  ]

T
Tim Neutkens 已提交
182 183 184
  // Support for NODE_PATH
  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
185
    .filter(p => !!p)
T
Tim Neutkens 已提交
186

187 188 189 190 191 192
  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 已提交
193
  const outputPath = path.join(distDir, isServer ? outputDir : '')
194
  const totalPages = Object.keys(entrypoints).length
195
  const clientEntries = !isServer
196
    ? ({
197 198 199 200 201 202 203 204 205 206 207
        // Backwards compatibility
        'main.js': [],
        [CLIENT_STATIC_FILES_RUNTIME_MAIN]:
          `.${path.sep}` +
          path.relative(
            dir,
            path.join(
              NEXT_PROJECT_ROOT_DIST_CLIENT,
              dev ? `next-dev.js` : 'next.js'
            )
          ),
208 209
        [CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join(
          NEXT_PROJECT_ROOT_DIST_CLIENT,
210
          'polyfills.js'
211
        ),
212
      } as ClientEntries)
213
    : undefined
N
nkzawa 已提交
214

215 216
  let typeScriptPath
  try {
217
    typeScriptPath = resolveRequest('typescript', `${dir}/`)
218
  } catch (_) {}
219
  const tsConfigPath = path.join(dir, 'tsconfig.json')
220 221 222
  const useTypeScript = Boolean(
    typeScriptPath && (await fileExists(tsConfigPath))
  )
223
  const ignoreTypeScriptErrors = dev
224 225
    ? config.typescript?.ignoreDevErrors
    : config.typescript?.ignoreBuildErrors
226

227 228 229
  let jsConfig
  // jsconfig is a subset of tsconfig
  if (useTypeScript) {
230
    jsConfig = parseJsonFile(tsConfigPath)
231 232 233 234
  }

  const jsConfigPath = path.join(dir, 'jsconfig.json')
  if (!useTypeScript && (await fileExists(jsConfigPath))) {
235
    jsConfig = parseJsonFile(jsConfigPath)
236 237 238 239 240 241 242
  }

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

T
Tim Neutkens 已提交
243
  const resolveConfig = {
244
    // Disable .mjs for node_modules bundling
245
    extensions: isServer
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
      ? [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.js',
          '.mjs',
          '.jsx',
          '.json',
          '.wasm',
        ]
      : [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.mjs',
          '.js',
          '.jsx',
          '.json',
          '.wasm',
        ],
T
Tim Neutkens 已提交
262 263
    modules: [
      'node_modules',
264
      ...nodePathList, // Support for NODE_PATH environment variable
T
Tim Neutkens 已提交
265 266
    ],
    alias: {
267 268
      // These aliases make sure the wrapper module is not included in the bundles
      // Which makes bundles slightly smaller, but also skips parsing a module that we know will result in this alias
269
      'next/head': 'next/dist/next-server/lib/head.js',
270
      'next/router': 'next/dist/client/router.js',
271 272
      'next/config': 'next/dist/next-server/lib/runtime-config.js',
      'next/dynamic': 'next/dist/next-server/lib/dynamic.js',
T
Tim Neutkens 已提交
273
      next: NEXT_PROJECT_ROOT,
J
JJ Kasper 已提交
274
      [PAGES_DIR_ALIAS]: pagesDir,
275
      [DOT_NEXT_ALIAS]: distDir,
276
      ...getOptimizedAliases(isServer),
277
    },
278
    mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
279
    plugins: [PnpWebpackPlugin],
T
Tim Neutkens 已提交
280 281
  }

T
Tim Neutkens 已提交
282 283
  const webpackMode = dev ? 'development' : 'production'

284
  const terserPluginConfig = {
285
    cache: true,
286
    cpus: config.experimental.cpus,
287
    distDir: distDir,
288 289 290
    parallel: true,
    sourceMap: false,
    workerThreads: config.experimental.workerThreads,
291
  }
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  const terserOptions = {
    parse: {
      ecma: 8,
    },
    compress: {
      ecma: 5,
      warnings: false,
      // The following two options are known to break valid JavaScript code
      comparisons: false,
      inline: 2, // https://github.com/zeit/next.js/issues/7178#issuecomment-493048965
    },
    mangle: { safari10: true },
    output: {
      ecma: 5,
      safari10: true,
      comments: false,
      // Fixes usage of Emoji and certain Regex
      ascii_only: true,
    },
  }

J
Joe Haddad 已提交
313
  const devtool = dev ? 'cheap-module-source-map' : false
314

315 316 317 318 319 320 321 322 323 324 325
  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`
    )
  }

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  // 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,
      },
    },
    prod: {
      chunks: 'all',
      cacheGroups: {
        default: false,
        vendors: false,
        commons: {
          name: 'commons',
          chunks: 'all',
          minChunks: totalPages > 2 ? totalPages * 0.5 : 2,
        },
        react: {
          name: 'commons',
          chunks: 'all',
349
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler|use-subscription)[\\/]/,
350 351 352
        },
      },
    },
353
    prodGranular: {
354
      chunks: 'all',
355 356 357 358
      cacheGroups: {
        default: false,
        vendors: false,
        framework: {
359
          chunks: 'all',
360
          name: 'framework',
A
Alex Castle 已提交
361
          // This regex ignores nested copies of framework libraries so they're
362 363
          // bundled with their issuer.
          // https://github.com/zeit/next.js/pull/9012
364
          test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/,
365
          priority: 40,
J
Joe Haddad 已提交
366 367 368
          // Don't let webpack eliminate this chunk (prevents this chunk from
          // becoming a part of the commons chunk)
          enforce: true,
369 370 371 372 373 374 375 376
        },
        lib: {
          test(module: { size: Function; identifier: Function }): boolean {
            return (
              module.size() > 160000 &&
              /node_modules[/\\]/.test(module.identifier())
            )
          },
J
Joe Haddad 已提交
377 378 379 380 381 382
          name(module: {
            type: string
            libIdent?: Function
            updateHash: (hash: crypto.Hash) => void
          }): string {
            const hash = crypto.createHash('sha1')
383
            if (isModuleCSS(module)) {
J
Joe Haddad 已提交
384 385 386 387 388 389 390 391 392 393 394 395
              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 }))
            }

            return hash.digest('hex').substring(0, 8)
396 397 398 399 400 401 402 403 404 405 406 407
          },
          priority: 30,
          minChunks: 1,
          reuseExistingChunk: true,
        },
        commons: {
          name: 'commons',
          minChunks: totalPages,
          priority: 20,
        },
        shared: {
          name(module, chunks) {
408 409 410 411 412 413 414 415 416 417
            return (
              crypto
                .createHash('sha1')
                .update(
                  chunks.reduce(
                    (acc: string, chunk: webpack.compilation.Chunk) => {
                      return acc + chunk.name
                    },
                    ''
                  )
418
                )
419 420
                .digest('hex') + (isModuleCSS(module) ? '_CSS' : '')
            )
421 422 423 424 425 426
          },
          priority: 10,
          minChunks: 2,
          reuseExistingChunk: true,
        },
      },
427 428
      maxInitialRequests: 25,
      minSize: 20000,
429
    },
430 431 432 433 434 435 436
  }

  // Select appropriate SplitChunksPlugin config for this build
  let splitChunksConfig: webpack.Options.SplitChunksOptions
  if (dev) {
    splitChunksConfig = splitChunksConfigs.dev
  } else {
437 438 439
    splitChunksConfig = config.experimental.granularChunks
      ? splitChunksConfigs.prodGranular
      : splitChunksConfigs.prod
440 441
  }

442 443 444 445 446
  const crossOrigin =
    !config.crossOrigin && config.experimental.modern
      ? 'anonymous'
      : config.crossOrigin

J
Joe Haddad 已提交
447
  let customAppFile: string | null = config.experimental.css
448
    ? await findPageFile(pagesDir, '/_app', config.pageExtensions)
J
Joe Haddad 已提交
449 450
    : null
  if (customAppFile) {
451
    customAppFile = path.resolve(path.join(pagesDir, customAppFile))
J
Joe Haddad 已提交
452 453
  }

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  const conformanceConfig = Object.assign(
    {
      ReactSyncScriptsConformanceCheck: {
        enabled: true,
      },
      MinificationConformanceCheck: {
        enabled: true,
      },
      DuplicatePolyfillsConformanceCheck: {
        enabled: true,
        BlockedAPIToBePolyfilled: Object.assign(
          [],
          ['fetch'],
          config.conformance?.DuplicatePolyfillsConformanceCheck
            ?.BlockedAPIToBePolyfilled || []
        ),
      },
    },
    config.conformance
  )
474
  let webpackConfig: webpack.Configuration = {
475
    externals: !isServer
476 477 478 479
      ? // 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']
480
      : !isServerless
481 482
      ? [
          (context, request, callback) => {
483 484 485 486
            if (request === 'next') {
              return callback(undefined, `commonjs ${request}`)
            }

487 488 489 490 491 492 493 494
            const notExternalModules = [
              'next/app',
              'next/document',
              'next/link',
              'next/error',
              'string-hash',
              'next/constants',
            ]
495

496 497 498
            if (notExternalModules.indexOf(request) !== -1) {
              return callback()
            }
K
k-kawakami 已提交
499

500 501 502 503 504 505 506 507 508 509 510 511 512
            // 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)
513

514 515 516 517
            // 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.
518
            if (isLocal && !isLikelyNextExternal) {
J
Joe Haddad 已提交
519
              return callback()
520 521
            }

522 523 524
            // Resolve the import with the webpack provided context, this
            // ensures we're resolving the correct version when multiple
            // exist.
525
            let res: string
526
            try {
527
              res = resolveRequest(request, `${context}/`)
528
            } catch (err) {
529 530 531
              // 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).
532 533
              return callback()
            }
K
k-kawakami 已提交
534

535 536
            // Same as above, if the request cannot be resolved we need to have
            // webpack "bundle" it so it surfaces the not found error.
537 538 539
            if (!res) {
              return callback()
            }
K
k-kawakami 已提交
540

541 542
            let isNextExternal: boolean = false
            if (isLocal) {
543 544 545 546 547 548
              // 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
              )

549 550 551 552
              if (!isNextExternal) {
                return callback()
              }
            }
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
            // `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
              }

              // 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.
              if (baseRes !== res) {
                return callback()
              }
576 577
            }

578 579 580
            // Default pages have to be transpiled
            if (
              !res.match(/next[/\\]dist[/\\]next-server[/\\]/) &&
581
              (res.match(/[/\\]next[/\\]dist[/\\]/) ||
582
                // This is the @babel/plugin-transform-runtime "helpers: true" option
583
                res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/))
584 585 586
            ) {
              return callback()
            }
K
k-kawakami 已提交
587

588 589 590 591 592 593 594
            // 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()
            }
K
k-kawakami 已提交
595

596 597
            // Anything else that is standard JavaScript within `node_modules`
            // can be externalized.
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
            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

              return callback(undefined, `commonjs ${externalRequest}`)
616
            }
K
k-kawakami 已提交
617

618
            // Default behavior: bundle the code!
619
            callback()
620 621 622
          },
        ]
      : [
623 624
          // 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
625
          '@ampproject/toolbox-optimizer', // except this one
626
        ],
627 628 629 630 631 632 633 634 635
    optimization: {
      checkWasmTypes: false,
      nodeEnv: false,
      splitChunks: isServer ? false : splitChunksConfig,
      runtimeChunk: isServer
        ? undefined
        : { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK },
      minimize: !(dev || isServer),
      minimizer: [
J
Joe Haddad 已提交
636
        // Minify JavaScript
637 638 639 640
        new TerserPlugin({
          ...terserPluginConfig,
          terserOptions,
        }),
J
Joe Haddad 已提交
641 642
        // Minify CSS
        config.experimental.css &&
J
Joe Haddad 已提交
643 644
          new CssMinimizerPlugin({
            postcssOptions: {
J
Joe Haddad 已提交
645 646 647 648
              map: {
                // `inline: false` generates the source map in a separate file.
                // Otherwise, the CSS file is needlessly large.
                inline: false,
J
Joe Haddad 已提交
649 650 651
                // `annotation: false` skips appending the `sourceMappingURL`
                // to the end of the CSS file. Webpack already handles this.
                annotation: false,
J
Joe Haddad 已提交
652 653 654 655
              },
            },
          }),
      ].filter(Boolean),
656
    },
N
nkzawa 已提交
657
    context: dir,
658 659 660
    node: {
      setImmediate: false,
    },
661
    // Kept as function to be backwards compatible
T
Tim Neutkens 已提交
662 663
    entry: async () => {
      return {
664 665
        ...(clientEntries ? clientEntries : {}),
        ...entrypoints,
666 667 668 669 670 671 672
        ...(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 已提交
673 674
      }
    },
N
nkzawa 已提交
675
    output: {
676
      path: outputPath,
677
      filename: ({ chunk }: { chunk: { name: string } }) => {
678
        // Use `[name]-[contenthash].js` in production
679 680 681
        if (
          !dev &&
          (chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN ||
682 683
            chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK ||
            chunk.name === CLIENT_STATIC_FILES_RUNTIME_POLYFILLS)
684
        ) {
685
          return chunk.name.replace(/\.js$/, '-[contenthash].js')
686 687 688
        }
        return '[name]'
      },
T
Tim Neutkens 已提交
689
      libraryTarget: isServer ? 'commonjs2' : 'var',
690 691 692
      hotUpdateChunkFilename: 'static/webpack/[id].[hash].hot-update.js',
      hotUpdateMainFilename: 'static/webpack/[hash].hot-update.json',
      // This saves chunks with the name given via `import()`
693 694 695
      chunkFilename: isServer
        ? `${dev ? '[name]' : '[name].[contenthash]'}.js`
        : `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
A
Andy 已提交
696
      strictModuleExceptionHandling: true,
697
      crossOriginLoading: crossOrigin,
698
      futureEmitAssets: !dev,
699
      webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
N
nkzawa 已提交
700
    },
701
    performance: false,
T
Tim Neutkens 已提交
702
    resolve: resolveConfig,
N
nkzawa 已提交
703
    resolveLoader: {
704 705 706
      // The loaders Next.js provides
      alias: [
        'emit-file-loader',
707
        'error-loader',
708 709 710 711 712
        'next-babel-loader',
        'next-client-pages-loader',
        'next-data-loader',
        'next-serverless-loader',
        'noop-loader',
713
        'next-plugin-loader',
714 715 716
      ].reduce((alias, loader) => {
        // using multiple aliases to replace `resolveLoader.modules`
        alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
717

718 719
        return alias
      }, {} as Record<string, string>),
N
Naoyuki Kanezawa 已提交
720
      modules: [
721
        'node_modules',
722 723
        ...nodePathList, // Support for NODE_PATH environment variable
      ],
724
      plugins: [PnpWebpackPlugin],
N
nkzawa 已提交
725 726
    },
    module: {
727
      rules: [
T
Tim Neutkens 已提交
728
        {
729
          test: /\.(tsx|ts|js|mjs|jsx)$/,
730
          include: [dir, ...babelIncludeRegexes],
731
          exclude: (path: string) => {
732
            if (babelIncludeRegexes.some(r => r.test(path))) {
733 734
              return false
            }
735
            return /node_modules/.test(path)
736
          },
737 738 739 740 741
          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 已提交
742
                  loader: 'next/dist/compiled/cache-loader',
743 744 745 746 747 748 749 750 751
                  options: {
                    cacheContext: dir,
                    cacheDirectory: path.join(dir, '.next', 'cache', 'webpack'),
                    cacheIdentifier: `webpack${isServer ? '-server' : ''}${
                      config.experimental.modern ? '-hasmodern' : ''
                    }`,
                  },
                },
                {
G
Guy Bedford 已提交
752
                  loader: require.resolve('next/dist/compiled/thread-loader'),
753 754 755 756 757 758 759 760
                  options: {
                    workers: 2,
                    workerParallelJobs: Infinity,
                  },
                },
                defaultLoaders.babel,
              ]
            : defaultLoaders.babel,
761
        },
762
      ].filter(Boolean),
N
nkzawa 已提交
763
    },
T
Tim Neutkens 已提交
764
    plugins: [
765 766
      // This plugin makes sure `output.filename` is used for entry chunks
      new ChunkNamesPlugin(),
767
      new webpack.DefinePlugin({
768 769 770
        ...(config.experimental.pageEnv
          ? Object.keys(process.env).reduce(
              (prev: { [key: string]: string }, key: string) => {
771
                if (key.startsWith('NEXT_PUBLIC_')) {
772
                  prev[`process.env.${key}`] = JSON.stringify(process.env[key]!)
773 774 775 776 777 778
                }
                return prev
              },
              {}
            )
          : {}),
779
        ...Object.keys(config.env).reduce((acc, key) => {
780
          if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
781 782 783
            throw new Error(
              `The key "${key}" under "env" in next.config.js is not allowed. https://err.sh/zeit/next.js/env-key-not-allowed`
            )
784 785 786
          }

          return {
787
            ...acc,
788
            [`process.env.${key}`]: JSON.stringify(config.env[key]),
789
          }
790
        }, {}),
791
        'process.env.NODE_ENV': JSON.stringify(webpackMode),
792
        'process.crossOrigin': JSON.stringify(crossOrigin),
793
        'process.browser': JSON.stringify(!isServer),
J
JJ Kasper 已提交
794 795 796
        'process.env.__NEXT_TEST_MODE': JSON.stringify(
          process.env.__NEXT_TEST_MODE
        ),
797
        // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
798 799 800 801 802 803
        ...(dev && !isServer
          ? {
              'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
            }
          : {}),
        'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
804
          config.exportTrailingSlash
805
        ),
806 807 808 809 810 811 812 813 814 815 816 817
        'process.env.__NEXT_MODERN_BUILD': JSON.stringify(
          config.experimental.modern && !dev
        ),
        'process.env.__NEXT_GRANULAR_CHUNKS': JSON.stringify(
          config.experimental.granularChunks && !dev
        ),
        'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify(
          config.devIndicators.buildActivity
        ),
        'process.env.__NEXT_PRERENDER_INDICATOR': JSON.stringify(
          config.devIndicators.autoPrerender
        ),
818 819 820
        'process.env.__NEXT_PLUGINS': JSON.stringify(
          config.experimental.plugins
        ),
G
Gerald Monaco 已提交
821 822 823
        'process.env.__NEXT_STRICT_MODE': JSON.stringify(
          config.reactStrictMode
        ),
824 825 826
        'process.env.__NEXT_REACT_MODE': JSON.stringify(
          config.experimental.reactMode
        ),
T
Tim Neutkens 已提交
827 828 829
        'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(
          config.experimental.basePath
        ),
830 831 832
        'process.env.__NEXT_FID_POLYFILL': JSON.stringify(
          config.experimental.measureFid
        ),
833
        ...(isServer
834 835 836 837 838 839
          ? {
              // 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),
            }
840
          : undefined),
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        // stub process.env with proxy to warn a missing value is
        // being accessed
        ...(config.experimental.pageEnv
          ? {
              'process.env':
                process.env.NODE_ENV === 'production'
                  ? isServer
                    ? 'process.env'
                    : '{}'
                  : `
            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]
              }
            })
          `,
            }
          : {}),
862
      }),
863 864 865 866
      !isServer &&
        new ReactLoadablePlugin({
          filename: REACT_LOADABLE_MANIFEST,
        }),
867
      !isServer && new DropClientPage(),
868 869 870 871 872 873
      // 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 &&
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
      ...(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')
            const {
              UnlinkRemovedPagesPlugin,
            } = require('./webpack/plugins/unlink-removed-pages-plugin')
            const devPlugins = [
              new UnlinkRemovedPagesPlugin(),
              new webpack.NoEmitOnErrorsPlugin(),
              new NextJsRequireCacheHotReloader(),
            ]
889

890
            if (!isServer) {
G
Guy Bedford 已提交
891 892 893
              const AutoDllPlugin = require('next/dist/compiled/autodll-webpack-plugin')(
                distDir
              )
894 895 896 897 898 899 900 901 902
              devPlugins.push(
                new AutoDllPlugin({
                  filename: '[name]_[hash].js',
                  path: './static/development/dll',
                  context: dir,
                  entry: {
                    dll: ['react', 'react-dom'],
                  },
                  config: {
J
JJ Kasper 已提交
903
                    devtool,
904 905 906 907 908 909 910
                    mode: webpackMode,
                    resolve: resolveConfig,
                  },
                })
              )
              devPlugins.push(new webpack.HotModuleReplacementPlugin())
            }
911

912 913 914
            return devPlugins
          })()
        : []),
915
      !dev && new webpack.HashedModuleIdsPlugin(),
916 917 918 919 920 921 922 923 924 925 926 927
      !dev &&
        new webpack.IgnorePlugin({
          checkResource: (resource: string) => {
            return /react-is/.test(resource)
          },
          checkContext: (context: string) => {
            return (
              /next-server[\\/]dist[\\/]/.test(context) ||
              /next[\\/]dist[\\/]/.test(context)
            )
          },
        }),
J
Joe Haddad 已提交
928
      isServerless && isServer && new ServerlessPlugin(),
929 930
      isServer && new PagesManifestPlugin(isLikeServerless),
      target === 'server' &&
931 932
        isServer &&
        new NextJsSSRModuleCachePlugin({ outputPath }),
933
      isServer && new NextJsSsrImportPlugin(),
934 935 936 937 938 939
      !isServer &&
        new BuildManifestPlugin({
          buildId,
          clientManifest: config.experimental.granularChunks,
          modern: config.experimental.modern,
        }),
940 941 942
      tracer &&
        new ProfilingPlugin({
          tracer,
943
        }),
944 945
      !isServer &&
        useTypeScript &&
946
        !ignoreTypeScriptErrors &&
M
Maël Nison 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959
        new ForkTsCheckerWebpackPlugin(
          PnpWebpackPlugin.forkTsCheckerOptions({
            typescript: typeScriptPath,
            async: dev,
            useTypescriptIncrementalApi: true,
            checkSyntacticErrors: true,
            tsconfig: tsConfigPath,
            reportFiles: ['**', '!**/__tests__/**', '!**/?(*.)(spec|test).*'],
            compilerOptions: { isolatedModules: true, noEmit: true },
            silent: true,
            formatter: 'codeframe',
          })
        ),
960 961 962 963 964 965 966 967 968 969 970 971
      config.experimental.modern &&
        !isServer &&
        !dev &&
        new NextEsmPlugin({
          filename: (getFileName: Function | string) => (...args: any[]) => {
            const name =
              typeof getFileName === 'function'
                ? getFileName(...args)
                : getFileName

            return name.includes('.js')
              ? name.replace(/\.js$/, '.module.js')
972 973 974
              : escapePathVariables(
                  args[0].chunk.name.replace(/\.js$/, '.module.js')
                )
975 976 977 978
          },
          chunkFilename: (inputChunkName: string) =>
            inputChunkName.replace(/\.js$/, '.module.js'),
        }),
979 980 981
      config.experimental.conformance &&
        !dev &&
        new WebpackConformancePlugin({
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
          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,
              }),
          ].filter(Boolean),
1000
        }),
1001
    ].filter((Boolean as any) as ExcludesFalse),
1002
  }
1003

1004 1005 1006 1007 1008
  // Support tsconfig and jsconfig baseUrl
  if (resolvedBaseUrl) {
    webpackConfig.resolve?.modules?.push(resolvedBaseUrl)
  }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
  if (
    config.experimental.jsconfigPaths &&
    jsConfig?.compilerOptions?.paths &&
    resolvedBaseUrl
  ) {
    webpackConfig.resolve?.plugins?.push(
      new JsConfigPathsPlugin(jsConfig.compilerOptions.paths, resolvedBaseUrl)
    )
  }

1019 1020 1021 1022 1023 1024
  webpackConfig = await buildConfiguration(webpackConfig, {
    rootDirectory: dir,
    customAppFile,
    isDevelopment: dev,
    isServer,
    hasSupportCss: !!config.experimental.css,
1025
    hasSupportScss: !!config.experimental.scss,
1026
    assetPrefix: config.assetPrefix || '',
1027
    sassOptions: config.experimental.sassOptions,
1028 1029
  })

T
Tim Neutkens 已提交
1030
  if (typeof config.webpack === 'function') {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    webpackConfig = config.webpack(webpackConfig, {
      dir,
      dev,
      isServer,
      buildId,
      config,
      defaultLoaders,
      totalPages,
      webpack,
    })
1041

1042
    if (typeof (webpackConfig as any).then === 'function') {
1043
      console.warn(
1044
        '> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config'
1045
      )
1046
    }
1047
  }
T
Tim Neutkens 已提交
1048

1049 1050 1051 1052 1053
  function canMatchCss(rule: webpack.RuleSetCondition | undefined): boolean {
    if (!rule) {
      return false
    }

1054 1055 1056 1057 1058 1059 1060 1061 1062
    const fileNames = [
      '/tmp/test.css',
      '/tmp/test.scss',
      '/tmp/test.sass',
      '/tmp/test.less',
      '/tmp/test.styl',
    ]

    if (rule instanceof RegExp && fileNames.some(input => rule.test(input))) {
1063 1064 1065 1066
      return true
    }

    if (typeof rule === 'function') {
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
      if (
        fileNames.some(input => {
          try {
            if (rule(input)) {
              return true
            }
          } catch (_) {}
          return false
        })
      ) {
        return true
      }
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    }

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

    return false
  }

  if (config.experimental.css) {
    const hasUserCssConfig =
1090
      webpackConfig.module?.rules.some(
1091
        rule => canMatchCss(rule.test) || canMatchCss(rule.include)
1092
      ) ?? false
1093 1094

    if (hasUserCssConfig) {
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
      // 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'
        )
      }

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
      if (webpackConfig.module?.rules.length) {
        // Remove default CSS Loader
        webpackConfig.module.rules = webpackConfig.module.rules.filter(
          r =>
            !(
              typeof r.oneOf?.[0]?.options === 'object' &&
              r.oneOf[0].options.__next_css_remove === true
            )
        )
      }
      if (webpackConfig.plugins?.length) {
        // Disable CSS Extraction Plugin
        webpackConfig.plugins = webpackConfig.plugins.filter(
          p => (p as any).__next_css_remove !== true
        )
      }
      if (webpackConfig.optimization?.minimizer?.length) {
        // Disable CSS Minifier
        webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter(
          e => (e as any).__next_css_remove !== true
        )
      }
1128
    } else {
1129
      await __overrideCssConfiguration(dir, !dev, webpackConfig)
1130 1131 1132
    }
  }

1133
  // check if using @zeit/next-typescript and show warning
1134 1135 1136
  if (
    isServer &&
    webpackConfig.module &&
1137 1138 1139 1140
    Array.isArray(webpackConfig.module.rules)
  ) {
    let foundTsRule = false

1141 1142
    webpackConfig.module.rules = webpackConfig.module.rules.filter(
      (rule): boolean => {
1143
        if (!(rule.test instanceof RegExp)) return true
1144
        if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
1145 1146 1147 1148 1149
          // remove if it matches @zeit/next-typescript
          foundTsRule = rule.use === defaultLoaders.babel
          return !foundTsRule
        }
        return true
1150 1151
      }
    )
1152 1153

    if (foundTsRule) {
1154
      console.warn(
1155
        '\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'
1156
      )
1157 1158 1159
    }
  }

1160
  // Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
1161
  if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
1162 1163 1164 1165 1166 1167 1168
    ;[].forEach.call(webpackConfig.module.rules, function(
      rule: webpack.RuleSetRule
    ) {
      if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
        return
      }

1169 1170 1171 1172
      const isSass =
        rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
      const isLess = rule.test.source === '\\.less$'
      const isCss = rule.test.source === '\\.css$'
1173
      const isStylus = rule.test.source === '\\.styl$'
1174 1175

      // Check if the rule we're iterating over applies to Sass, Less, or CSS
1176
      if (!(isSass || isLess || isCss || isStylus)) {
1177 1178 1179 1180 1181 1182 1183 1184 1185
        return
      }

      ;[].forEach.call(rule.use, function(use: webpack.RuleSetUseItem) {
        if (
          !(
            use &&
            typeof use === 'object' &&
            // Identify use statements only pertaining to `css-loader`
1186 1187
            (use.loader === 'css-loader' ||
              use.loader === 'css-loader/locals') &&
1188 1189 1190 1191
            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
1192 1193
            // old `css-loader` versions. Custom setups (that aren't next-sass,
            // next-less or next-stylus) likely have the newer version.
1194
            // We still handle this gracefully below.
1195 1196 1197 1198 1199
            (Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
              Object.prototype.hasOwnProperty.call(
                use.options,
                'exportOnlyLocals'
              ))
1200 1201 1202 1203 1204 1205 1206
          )
        ) {
          return
        }

        // Try to monkey patch within a try-catch. We shouldn't fail the build
        // if we cannot pull this off.
1207 1208
        // The user may not even be using the `next-sass` or `next-less` or
        // `next-stylus` plugins.
1209 1210
        // If it does work, great!
        try {
1211 1212
          // Resolve the version of `@zeit/next-css` as depended on by the Sass,
          // Less or Stylus plugin.
1213 1214
          const correctNextCss = resolveRequest(
            '@zeit/next-css',
1215 1216 1217 1218 1219 1220 1221 1222 1223
            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'
1224 1225
                    : isStylus
                    ? '@zeit/next-stylus'
1226 1227
                    : 'next'
                )
1228 1229 1230 1231 1232 1233 1234
          )

          // 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.
1235
            const correctCssLoader = resolveRequest(use.loader, correctNextCss)
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
            if (correctCssLoader) {
              // We saved the user from a failed build!
              use.loader = correctCssLoader
            }
          }
        } catch (_) {
          // The error is not required to be handled.
        }
      })
    })
  }

1248
  // Backwards compat for `main.js` entry key
1249
  const originalEntry: any = webpackConfig.entry
1250 1251
  if (typeof originalEntry !== 'undefined') {
    webpackConfig.entry = async () => {
1252 1253 1254 1255
      const entry: WebpackEntrypoints =
        typeof originalEntry === 'function'
          ? await originalEntry()
          : originalEntry
1256 1257 1258 1259 1260
      // Server compilation doesn't have main.js
      if (clientEntries && entry['main.js'] && entry['main.js'].length > 0) {
        const originalFile = clientEntries[CLIENT_STATIC_FILES_RUNTIME_MAIN]
        entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
          ...entry['main.js'],
1261
          originalFile,
1262
        ]
1263
      }
1264
      delete entry['main.js']
1265

1266
      return entry
1267 1268 1269
    }
  }

1270
  if (!dev) {
1271 1272
    // entry is always a function
    webpackConfig.entry = await (webpackConfig.entry as webpack.EntryFunc)()
1273 1274
  }

T
Tim Neutkens 已提交
1275
  return webpackConfig
N
nkzawa 已提交
1276
}