webpack-config.ts 42.3 KB
Newer Older
1
import chalk from 'chalk'
2
import crypto from 'crypto'
3
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
J
Joe Haddad 已提交
4
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
5
import path from 'path'
6 7
// @ts-ignore: Currently missing types
import PnpWebpackPlugin from 'pnp-webpack-plugin'
8
import webpack from 'webpack'
9

10
import {
11
  DOT_NEXT_ALIAS,
12 13 14 15
  NEXT_PROJECT_ROOT,
  NEXT_PROJECT_ROOT_DIST_CLIENT,
  PAGES_DIR_ALIAS,
} from '../lib/constants'
16
import { fileExists } from '../lib/file-exists'
J
Joe Haddad 已提交
17
import { findConfig } from '../lib/find-config'
18 19 20
import { resolveRequest } from '../lib/resolve-request'
import {
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
21
  CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
22 23 24 25 26
  CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
  REACT_LOADABLE_MANIFEST,
  SERVER_DIRECTORY,
  SERVERLESS_DIRECTORY,
} from '../next-server/lib/constants'
J
Joe Haddad 已提交
27
import { findPageFile } from '../server/lib/find-page-file'
28
import { WebpackEntrypoints } from './entries'
J
Joe Haddad 已提交
29 30 31 32 33 34 35
import {
  collectPlugins,
  PluginMetaData,
  VALID_MIDDLEWARE,
} from './plugins/collect-plugins'
// @ts-ignore: JS file
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
36 37
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
J
Joe Haddad 已提交
38
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin'
39
import { importAutoDllPlugin } from './webpack/plugins/dll-import'
40
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
41
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
42 43 44
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'
45
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
46 47 48 49
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'

50
type ExcludesFalse = <T>(x: T | false) => x is T
51

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

58 59 60 61 62
function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
  if (isServer) {
    return {}
  }

63
  const stubWindowFetch = path.join(__dirname, 'polyfills', 'fetch', 'index.js')
64 65 66
  const stubObjectAssign = path.join(__dirname, 'polyfills', 'object-assign.js')

  const shimAssign = path.join(__dirname, 'polyfills', 'object.assign')
67
  return {
68
    // Polyfill: Window#fetch
69 70 71
    __next_polyfill__fetch: require.resolve('whatwg-fetch'),
    unfetch$: stubWindowFetch,
    'isomorphic-unfetch$': stubWindowFetch,
72 73 74 75 76 77
    'whatwg-fetch$': path.join(
      __dirname,
      'polyfills',
      'fetch',
      'whatwg-fetch.js'
    ),
78 79 80 81 82 83 84 85 86 87 88 89

    // Polyfill: Object.assign
    __next_polyfill__object_assign: require.resolve('object-assign'),
    'object-assign$': stubObjectAssign,
    '@babel/runtime-corejs2/core-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'),
90 91 92

    // Replace: full URL polyfill with platform-based polyfill
    url: require.resolve('native-url'),
93 94 95
  }
}

J
Joe Haddad 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 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 138 139 140 141 142 143 144 145 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 188 189 190 191 192 193 194
async function getPostCssPlugins(dir: string): Promise<unknown[]> {
  function load(plugins: { [key: string]: object | false }): unknown[] {
    return Object.keys(plugins)
      .map(pkg => {
        const options = plugins[pkg]
        if (options === false) {
          return false
        }

        const pluginPath = resolveRequest(pkg, `${dir}/`)

        if (options == null || Object.keys(options).length === 0) {
          return require(pluginPath)
        }
        return require(pluginPath)(options)
      })
      .filter(Boolean)
  }

  const config = await findConfig<{ plugins: { [key: string]: object } }>(
    dir,
    'postcss'
  )

  let target: unknown[]

  if (!config) {
    target = load({
      [require.resolve('postcss-flexbugs-fixes')]: {},
      [require.resolve('postcss-preset-env')]: {
        autoprefixer: {
          // Disable legacy flexbox support
          flexbox: 'no-2009',
        },
        // Enable CSS features that have shipped to the
        // web platform, i.e. in 2+ browsers unflagged.
        stage: 3,
      },
    })
  } else {
    const plugins = config.plugins
    if (plugins == null || typeof plugins !== 'object') {
      throw new Error(
        `Your custom PostCSS configuration must export a \`plugins\` key.`
      )
    }

    const invalidKey = Object.keys(config).find(key => key !== 'plugins')
    if (invalidKey) {
      console.warn(
        `${chalk.yellow.bold(
          'Warning'
        )}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` +
          `Please remove this configuration value.`
      )
    }

    // These plugins cannot be enabled by the user because they'll conflict with
    // `css-loader`'s behavior to make us compatible with webpack.
    ;[
      'postcss-modules-values',
      'postcss-modules-scope',
      'postcss-modules-extract-imports',
      'postcss-modules-local-by-default',
    ].forEach(plugin => {
      if (!plugins.hasOwnProperty(plugin)) {
        return
      }

      console.warn(
        `${chalk.yellow.bold('Warning')}: Please remove the ${chalk.underline(
          plugin
        )} plugin from your PostCSS configuration. ` +
          `This plugin is automatically configured by Next.js.`
      )
      delete plugins[plugin]
    })

    // Next.js doesn't support CSS Modules yet. When we do, we should respect the
    // options passed to this plugin (even though we need to remove the plugin
    // itself).
    if (plugins['postcss-modules']) {
      delete plugins['postcss-modules']

      console.warn(
        `${chalk.yellow.bold(
          'Warning'
        )}: Next.js does not support CSS Modules (yet). The ${chalk.underline(
          'postcss-modules'
        )} plugin will have no effect.`
      )
    }

    target = load(plugins as { [key: string]: object })
  }

  return target
}

195 196 197 198 199
export default async function getBaseWebpackConfig(
  dir: string,
  {
    buildId,
    config,
J
JJ Kasper 已提交
200 201 202 203
    dev = false,
    isServer = false,
    pagesDir,
    tracer,
204 205 206 207 208
    target = 'server',
    entrypoints,
  }: {
    buildId: string
    config: any
J
JJ Kasper 已提交
209 210 211
    dev?: boolean
    isServer?: boolean
    pagesDir: string
212
    target?: string
J
JJ Kasper 已提交
213
    tracer?: any
214 215 216
    entrypoints: WebpackEntrypoints
  }
): Promise<webpack.Configuration> {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  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,
        })
      }
    }
  }
233
  const distDir = path.join(dir, config.distDir)
T
Tim Neutkens 已提交
234 235
  const defaultLoaders = {
    babel: {
236
      loader: 'next-babel-loader',
237 238 239
      options: {
        isServer,
        distDir,
J
JJ Kasper 已提交
240
        pagesDir,
241
        cwd: dir,
242
        cache: true,
243 244
        babelPresetPlugins,
        hasModern: !!config.experimental.modern,
245
      },
246
    },
247
    // Backwards compat
248
    hotSelfAccept: {
249 250
      loader: 'noop-loader',
    },
T
Tim Neutkens 已提交
251 252
  }

253 254 255 256 257 258
  const babelIncludeRegexes: RegExp[] = [
    /next[\\/]dist[\\/]next-server[\\/]lib/,
    /next[\\/]dist[\\/]client/,
    /next[\\/]dist[\\/]pages/,
    /[\\/](strip-ansi|ansi-regex)[\\/]/,
    ...(config.experimental.plugins
J
JJ Kasper 已提交
259
      ? VALID_MIDDLEWARE.map(name => new RegExp(`src(\\\\|/)${name}`))
260 261 262
      : []),
  ]

T
Tim Neutkens 已提交
263 264 265
  // Support for NODE_PATH
  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
266
    .filter(p => !!p)
T
Tim Neutkens 已提交
267

268 269 270 271 272 273
  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 已提交
274
  const outputPath = path.join(distDir, isServer ? outputDir : '')
275
  const totalPages = Object.keys(entrypoints).length
276 277 278 279 280 281 282 283 284 285 286 287 288
  const clientEntries = !isServer
    ? {
        // 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'
            )
          ),
289 290 291 292
        [CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join(
          NEXT_PROJECT_ROOT_DIST_CLIENT,
          'polyfills.js'
        ),
293 294
      }
    : undefined
N
nkzawa 已提交
295

296 297
  let typeScriptPath
  try {
298
    typeScriptPath = resolveRequest('typescript', `${dir}/`)
299
  } catch (_) {}
300
  const tsConfigPath = path.join(dir, 'tsconfig.json')
301 302 303
  const useTypeScript = Boolean(
    typeScriptPath && (await fileExists(tsConfigPath))
  )
304 305 306
  const ignoreTypeScriptErrors = dev
    ? config.typescript && config.typescript.ignoreDevErrors
    : config.typescript && config.typescript.ignoreBuildErrors
307

T
Tim Neutkens 已提交
308
  const resolveConfig = {
309
    // Disable .mjs for node_modules bundling
310
    extensions: isServer
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
      ? [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.js',
          '.mjs',
          '.jsx',
          '.json',
          '.wasm',
        ]
      : [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.mjs',
          '.js',
          '.jsx',
          '.json',
          '.wasm',
        ],
T
Tim Neutkens 已提交
327 328
    modules: [
      'node_modules',
329
      ...nodePathList, // Support for NODE_PATH environment variable
T
Tim Neutkens 已提交
330 331
    ],
    alias: {
332 333
      // 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
334
      'next/head': 'next/dist/next-server/lib/head.js',
335
      'next/router': 'next/dist/client/router.js',
336 337
      'next/config': 'next/dist/next-server/lib/runtime-config.js',
      'next/dynamic': 'next/dist/next-server/lib/dynamic.js',
T
Tim Neutkens 已提交
338
      next: NEXT_PROJECT_ROOT,
J
JJ Kasper 已提交
339
      [PAGES_DIR_ALIAS]: pagesDir,
340
      [DOT_NEXT_ALIAS]: distDir,
341
      ...getOptimizedAliases(isServer),
342
    },
343
    mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
344
    plugins: [PnpWebpackPlugin],
T
Tim Neutkens 已提交
345 346
  }

T
Tim Neutkens 已提交
347 348
  const webpackMode = dev ? 'development' : 'production'

349
  const terserPluginConfig = {
350
    cache: true,
351
    cpus: config.experimental.cpus,
352
    distDir: distDir,
353 354 355
    parallel: true,
    sourceMap: false,
    workerThreads: config.experimental.workerThreads,
356
  }
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  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 已提交
378
  const devtool = dev ? 'cheap-module-source-map' : false
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  // 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',
403
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler|use-subscription)[\\/]/,
404 405 406
        },
      },
    },
407
    prodGranular: {
408
      chunks: 'all',
409 410 411 412
      cacheGroups: {
        default: false,
        vendors: false,
        framework: {
413
          chunks: 'all',
414
          name: 'framework',
A
Alex Castle 已提交
415
          // This regex ignores nested copies of framework libraries so they're
416 417
          // bundled with their issuer.
          // https://github.com/zeit/next.js/pull/9012
418
          test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/,
419
          priority: 40,
J
Joe Haddad 已提交
420 421 422
          // Don't let webpack eliminate this chunk (prevents this chunk from
          // becoming a part of the commons chunk)
          enforce: true,
423 424 425 426 427 428 429 430
        },
        lib: {
          test(module: { size: Function; identifier: Function }): boolean {
            return (
              module.size() > 160000 &&
              /node_modules[/\\]/.test(module.identifier())
            )
          },
J
Joe Haddad 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
          name(module: {
            type: string
            libIdent?: Function
            updateHash: (hash: crypto.Hash) => void
          }): string {
            const hash = crypto.createHash('sha1')
            if (module.type === `css/mini-extract`) {
              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)
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
          },
          priority: 30,
          minChunks: 1,
          reuseExistingChunk: true,
        },
        commons: {
          name: 'commons',
          minChunks: totalPages,
          priority: 20,
        },
        shared: {
          name(module, chunks) {
            return crypto
              .createHash('sha1')
              .update(
                chunks.reduce(
                  (acc: string, chunk: webpack.compilation.Chunk) => {
                    return acc + chunk.name
                  },
                  ''
                )
              )
472
              .digest('hex')
473 474 475 476 477 478
          },
          priority: 10,
          minChunks: 2,
          reuseExistingChunk: true,
        },
      },
479 480
      maxInitialRequests: 25,
      minSize: 20000,
481
    },
482 483 484 485 486 487 488
  }

  // Select appropriate SplitChunksPlugin config for this build
  let splitChunksConfig: webpack.Options.SplitChunksOptions
  if (dev) {
    splitChunksConfig = splitChunksConfigs.dev
  } else {
489 490 491
    splitChunksConfig = config.experimental.granularChunks
      ? splitChunksConfigs.prodGranular
      : splitChunksConfigs.prod
492 493
  }

494 495 496 497 498
  const crossOrigin =
    !config.crossOrigin && config.experimental.modern
      ? 'anonymous'
      : config.crossOrigin

J
Joe Haddad 已提交
499
  let customAppFile: string | null = config.experimental.css
500
    ? await findPageFile(pagesDir, '/_app', config.pageExtensions)
J
Joe Haddad 已提交
501 502
    : null
  if (customAppFile) {
503
    customAppFile = path.resolve(path.join(pagesDir, customAppFile))
J
Joe Haddad 已提交
504 505
  }

J
Joe Haddad 已提交
506 507 508 509
  const postCssPlugins: unknown[] = config.experimental.css
    ? await getPostCssPlugins(dir)
    : []

510
  let webpackConfig: webpack.Configuration = {
J
JJ Kasper 已提交
511
    devtool,
T
Tim Neutkens 已提交
512
    mode: webpackMode,
T
Tim Neutkens 已提交
513 514
    name: isServer ? 'server' : 'client',
    target: isServer ? 'node' : 'web',
515 516
    externals: !isServer
      ? undefined
517
      : !isServerless
518 519 520 521 522 523 524 525 526 527
      ? [
          (context, request, callback) => {
            const notExternalModules = [
              'next/app',
              'next/document',
              'next/link',
              'next/error',
              'string-hash',
              'next/constants',
            ]
528

529 530 531
            if (notExternalModules.indexOf(request) !== -1) {
              return callback()
            }
K
k-kawakami 已提交
532

533 534 535 536 537 538
            // make sure we don't externalize anything that is
            // supposed to be transpiled
            if (babelIncludeRegexes.some(r => r.test(request))) {
              return callback()
            }

539 540 541 542
            // 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.
J
Joe Haddad 已提交
543
            const start = request.charAt(0)
544
            if (start === '.' || start === '/') {
J
Joe Haddad 已提交
545
              return callback()
546 547
            }

548 549 550
            // Resolve the import with the webpack provided context, this
            // ensures we're resolving the correct version when multiple
            // exist.
551 552
            let res
            try {
553
              res = resolveRequest(request, `${context}/`)
554
            } catch (err) {
555 556 557 558
              // This is a special case for the Next.js data experiment. This
              // will be removed in the future.
              // We're telling webpack to externalize a package that doesn't
              // exist because we know it won't ever be used at runtime.
559 560 561 562 563 564 565 566 567 568 569
              if (
                request === 'react-ssr-prepass' &&
                !config.experimental.ampBindInitData
              ) {
                if (
                  context.replace(/\\/g, '/').includes('next-server/server')
                ) {
                  return callback(undefined, `commonjs ${request}`)
                }
              }

570 571 572
              // 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).
573 574
              return callback()
            }
K
k-kawakami 已提交
575

576 577
            // Same as above, if the request cannot be resolved we need to have
            // webpack "bundle" it so it surfaces the not found error.
578 579 580
            if (!res) {
              return callback()
            }
K
k-kawakami 已提交
581

582 583 584 585
            // 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).
586 587
            let baseRes
            try {
588
              baseRes = resolveRequest(request, `${dir}/`)
589 590
            } catch (err) {}

591 592 593
            // 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.
594 595 596 597
            if (baseRes !== res) {
              return callback()
            }

598 599 600 601 602 603 604 605 606
            // Default pages have to be transpiled
            if (
              !res.match(/next[/\\]dist[/\\]next-server[/\\]/) &&
              (res.match(/next[/\\]dist[/\\]/) ||
                res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) ||
                res.match(/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/))
            ) {
              return callback()
            }
K
k-kawakami 已提交
607

608 609 610 611 612 613 614
            // 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 已提交
615

616 617
            // Anything else that is standard JavaScript within `node_modules`
            // can be externalized.
618 619 620
            if (res.match(/node_modules[/\\].*\.js$/)) {
              return callback(undefined, `commonjs ${request}`)
            }
K
k-kawakami 已提交
621

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

733 734
        return alias
      }, {} as Record<string, string>),
N
Naoyuki Kanezawa 已提交
735
      modules: [
736
        'node_modules',
737 738
        ...nodePathList, // Support for NODE_PATH environment variable
      ],
739
      plugins: [PnpWebpackPlugin],
N
nkzawa 已提交
740
    },
T
Tim Neutkens 已提交
741
    // @ts-ignore this is filtered
N
nkzawa 已提交
742
    module: {
743
      strictExportPresence: true,
744
      rules: [
745 746 747 748 749 750
        config.experimental.ampBindInitData &&
          !isServer && {
            test: /\.(tsx|ts|js|mjs|jsx)$/,
            include: [path.join(dir, 'data')],
            use: 'next-data-loader',
          },
T
Tim Neutkens 已提交
751
        {
752
          test: /\.(tsx|ts|js|mjs|jsx)$/,
753
          include: [dir, ...babelIncludeRegexes],
754
          exclude: (path: string) => {
755
            if (babelIncludeRegexes.some(r => r.test(path))) {
756 757
              return false
            }
758
            return /node_modules/.test(path)
759
          },
760
          use: defaultLoaders.babel,
761
        },
J
Joe Haddad 已提交
762 763 764
        config.experimental.css &&
          // Support CSS imports
          ({
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
            oneOf: [
              {
                test: /\.css$/,
                issuer: { include: [customAppFile].filter(Boolean) },
                use: isServer
                  ? // Global CSS is ignored on the server because it's only needed
                    // on the client-side.
                    require.resolve('ignore-loader')
                  : [
                      // During development we load CSS via JavaScript so we can
                      // hot reload it without refreshing the page.
                      dev && {
                        loader: require.resolve('style-loader'),
                        options: {
                          // By default, style-loader injects CSS into the bottom
                          // of <head>. This causes ordering problems between dev
                          // and prod. To fix this, we render a <noscript> tag as
                          // an anchor for the styles to be placed before. These
                          // styles will be applied _before_ <style jsx global>.
                          insert: function(element: Node) {
                            // These elements should always exist. If they do not,
                            // this code should fail.
                            var anchorElement = document.querySelector(
                              '#__next_css__DO_NOT_USE__'
                            )!
                            var parentNode = anchorElement.parentNode! // Normally <head>

                            // Each style tag should be placed right before our
                            // anchor. By inserting before and not after, we do not
                            // need to track the last inserted element.
                            parentNode.insertBefore(element, anchorElement)

                            // Remember: this is development only code.
                            //
                            // After styles are injected, we need to remove the
                            // <style> tags that set `body { display: none; }`.
                            //
                            // We use `requestAnimationFrame` as a way to defer
                            // this operation since there may be multiple style
                            // tags.
                            ;(self.requestAnimationFrame || setTimeout)(
                              function() {
                                for (
                                  var x = document.querySelectorAll(
                                      '[data-next-hide-fouc]'
                                    ),
                                    i = x.length;
                                  i--;

                                ) {
                                  x[i].parentNode!.removeChild(x[i])
                                }
                              }
                            )
                          },
                        },
                      },
                      // When building for production we extract CSS into
                      // separate files.
                      !dev && {
                        loader: MiniCssExtractPlugin.loader,
                        options: {},
827
                      },
J
Joe Haddad 已提交
828

829 830 831 832 833
                      // Resolve CSS `@import`s and `url()`s
                      {
                        loader: require.resolve('css-loader'),
                        options: { importLoaders: 1, sourceMap: true },
                      },
J
Joe Haddad 已提交
834

835 836 837 838 839
                      // Compile CSS
                      {
                        loader: require.resolve('postcss-loader'),
                        options: {
                          ident: 'postcss',
J
Joe Haddad 已提交
840
                          plugins: postCssPlugins,
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
                          sourceMap: true,
                        },
                      },
                    ].filter(Boolean),
                // A global CSS import always has side effects. Webpack will tree
                // shake the CSS without this option if the issuer claims to have
                // no side-effects.
                // See https://github.com/webpack/webpack/issues/6571
                sideEffects: true,
              },
              {
                test: /\.css$/,
                use: isServer
                  ? require.resolve('ignore-loader')
                  : {
                      loader: 'error-loader',
                      options: {
                        reason:
                          `Global CSS ${chalk.bold(
                            'cannot'
                          )} be imported from files other than your ${chalk.bold(
                            'Custom <App>'
                          )}. Please move all global CSS imports to ${chalk.cyan(
                            customAppFile
J
JJ Kasper 已提交
865
                              ? path.relative(dir, customAppFile)
866 867 868 869
                              : 'pages/_app.js'
                          )}.\n` +
                          `Read more: https://err.sh/next.js/global-css`,
                      },
J
Joe Haddad 已提交
870
                    },
871 872
              },
            ],
J
Joe Haddad 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
          } as webpack.RuleSetRule),
        config.experimental.css &&
          ({
            loader: require.resolve('file-loader'),
            issuer: {
              // file-loader is only used for CSS files, e.g. url() for a SVG
              // or font files
              test: /\.css$/,
            },
            // Exclude extensions that webpack handles by default
            exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash].[ext]',
            },
          } as webpack.RuleSetRule),
888
      ].filter(Boolean),
N
nkzawa 已提交
889
    },
T
Tim Neutkens 已提交
890
    plugins: [
891 892
      // This plugin makes sure `output.filename` is used for entry chunks
      new ChunkNamesPlugin(),
893
      new webpack.DefinePlugin({
894
        ...Object.keys(config.env).reduce((acc, key) => {
895
          if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
896 897 898
            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`
            )
899 900 901
          }

          return {
902
            ...acc,
903
            [`process.env.${key}`]: JSON.stringify(config.env[key]),
904
          }
905
        }, {}),
906
        'process.env.NODE_ENV': JSON.stringify(webpackMode),
907
        'process.crossOrigin': JSON.stringify(crossOrigin),
908
        'process.browser': JSON.stringify(!isServer),
J
JJ Kasper 已提交
909 910 911
        'process.env.__NEXT_TEST_MODE': JSON.stringify(
          process.env.__NEXT_TEST_MODE
        ),
912
        // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
913 914 915 916 917 918
        ...(dev && !isServer
          ? {
              'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
            }
          : {}),
        'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
919
          config.exportTrailingSlash
920
        ),
921 922 923
        'process.env.__NEXT_DEFER_SCRIPTS': JSON.stringify(
          config.experimental.deferScripts
        ),
924 925 926 927 928 929 930 931 932 933 934 935
        '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
        ),
936 937 938
        'process.env.__NEXT_PLUGINS': JSON.stringify(
          config.experimental.plugins
        ),
G
Gerald Monaco 已提交
939 940 941
        'process.env.__NEXT_STRICT_MODE': JSON.stringify(
          config.reactStrictMode
        ),
942 943 944
        'process.env.__NEXT_REACT_MODE': JSON.stringify(
          config.experimental.reactMode
        ),
945
        ...(isServer
946 947 948 949 950 951
          ? {
              // 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),
            }
952
          : undefined),
953
      }),
954 955 956 957
      !isServer &&
        new ReactLoadablePlugin({
          filename: REACT_LOADABLE_MANIFEST,
        }),
958
      !isServer && new DropClientPage(),
959 960 961 962 963 964
      // 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$/),
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
      ...(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(),
            ]
980

981
            if (!isServer) {
982
              const AutoDllPlugin = importAutoDllPlugin({ distDir })
983 984 985 986 987 988 989 990 991
              devPlugins.push(
                new AutoDllPlugin({
                  filename: '[name]_[hash].js',
                  path: './static/development/dll',
                  context: dir,
                  entry: {
                    dll: ['react', 'react-dom'],
                  },
                  config: {
J
JJ Kasper 已提交
992
                    devtool,
993 994 995 996 997 998 999
                    mode: webpackMode,
                    resolve: resolveConfig,
                  },
                })
              )
              devPlugins.push(new webpack.HotModuleReplacementPlugin())
            }
1000

1001 1002 1003
            return devPlugins
          })()
        : []),
1004
      !dev && new webpack.HashedModuleIdsPlugin(),
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
      !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 已提交
1017
      isServerless && isServer && new ServerlessPlugin(),
1018 1019
      isServer && new PagesManifestPlugin(isLikeServerless),
      target === 'server' &&
1020 1021
        isServer &&
        new NextJsSSRModuleCachePlugin({ outputPath }),
1022
      isServer && new NextJsSsrImportPlugin(),
1023 1024 1025 1026 1027 1028
      !isServer &&
        new BuildManifestPlugin({
          buildId,
          clientManifest: config.experimental.granularChunks,
          modern: config.experimental.modern,
        }),
J
Joe Haddad 已提交
1029 1030 1031 1032 1033 1034 1035 1036
      // Extract CSS as CSS file(s) in the client-side production bundle.
      config.experimental.css &&
        !isServer &&
        !dev &&
        new MiniCssExtractPlugin({
          filename: 'static/css/[contenthash].css',
          chunkFilename: 'static/css/[contenthash].chunk.css',
        }),
1037 1038 1039
      tracer &&
        new ProfilingPlugin({
          tracer,
1040
        }),
1041 1042
      !isServer &&
        useTypeScript &&
1043
        !ignoreTypeScriptErrors &&
M
Maël Nison 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        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',
          })
        ),
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      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')
1069 1070 1071
              : escapePathVariables(
                  args[0].chunk.name.replace(/\.js$/, '.module.js')
                )
1072 1073 1074 1075
          },
          chunkFilename: (inputChunkName: string) =>
            inputChunkName.replace(/\.js$/, '.module.js'),
        }),
1076
    ].filter((Boolean as any) as ExcludesFalse),
1077
  }
1078

T
Tim Neutkens 已提交
1079
  if (typeof config.webpack === 'function') {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    webpackConfig = config.webpack(webpackConfig, {
      dir,
      dev,
      isServer,
      buildId,
      config,
      defaultLoaders,
      totalPages,
      webpack,
    })
1090 1091 1092

    // @ts-ignore: Property 'then' does not exist on type 'Configuration'
    if (typeof webpackConfig.then === 'function') {
1093
      console.warn(
1094
        '> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config'
1095
      )
1096
    }
1097
  }
T
Tim Neutkens 已提交
1098

1099
  // check if using @zeit/next-typescript and show warning
1100 1101 1102
  if (
    isServer &&
    webpackConfig.module &&
1103 1104 1105 1106
    Array.isArray(webpackConfig.module.rules)
  ) {
    let foundTsRule = false

1107 1108
    webpackConfig.module.rules = webpackConfig.module.rules.filter(
      (rule): boolean => {
1109
        if (!(rule.test instanceof RegExp)) return true
1110
        if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
1111 1112 1113 1114 1115
          // remove if it matches @zeit/next-typescript
          foundTsRule = rule.use === defaultLoaders.babel
          return !foundTsRule
        }
        return true
1116 1117
      }
    )
1118 1119

    if (foundTsRule) {
1120
      console.warn(
1121
        '\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'
1122
      )
1123 1124 1125
    }
  }

1126
  // Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
1127
  if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
1128 1129 1130 1131 1132 1133 1134
    ;[].forEach.call(webpackConfig.module.rules, function(
      rule: webpack.RuleSetRule
    ) {
      if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
        return
      }

1135 1136 1137 1138
      const isSass =
        rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
      const isLess = rule.test.source === '\\.less$'
      const isCss = rule.test.source === '\\.css$'
1139
      const isStylus = rule.test.source === '\\.styl$'
1140 1141

      // Check if the rule we're iterating over applies to Sass, Less, or CSS
1142
      if (!(isSass || isLess || isCss || isStylus)) {
1143 1144 1145 1146 1147 1148 1149 1150 1151
        return
      }

      ;[].forEach.call(rule.use, function(use: webpack.RuleSetUseItem) {
        if (
          !(
            use &&
            typeof use === 'object' &&
            // Identify use statements only pertaining to `css-loader`
1152 1153
            (use.loader === 'css-loader' ||
              use.loader === 'css-loader/locals') &&
1154 1155 1156 1157
            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
1158 1159
            // old `css-loader` versions. Custom setups (that aren't next-sass,
            // next-less or next-stylus) likely have the newer version.
1160
            // We still handle this gracefully below.
1161 1162 1163 1164 1165
            (Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
              Object.prototype.hasOwnProperty.call(
                use.options,
                'exportOnlyLocals'
              ))
1166 1167 1168 1169 1170 1171 1172
          )
        ) {
          return
        }

        // Try to monkey patch within a try-catch. We shouldn't fail the build
        // if we cannot pull this off.
1173 1174
        // The user may not even be using the `next-sass` or `next-less` or
        // `next-stylus` plugins.
1175 1176
        // If it does work, great!
        try {
1177 1178
          // Resolve the version of `@zeit/next-css` as depended on by the Sass,
          // Less or Stylus plugin.
1179 1180
          const correctNextCss = resolveRequest(
            '@zeit/next-css',
1181 1182 1183 1184 1185 1186 1187 1188 1189
            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'
1190 1191
                    : isStylus
                    ? '@zeit/next-stylus'
1192 1193
                    : 'next'
                )
1194 1195 1196 1197 1198 1199 1200
          )

          // 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.
1201
            const correctCssLoader = resolveRequest(use.loader, correctNextCss)
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
            if (correctCssLoader) {
              // We saved the user from a failed build!
              use.loader = correctCssLoader
            }
          }
        } catch (_) {
          // The error is not required to be handled.
        }
      })
    })
  }

1214
  // Backwards compat for `main.js` entry key
1215
  const originalEntry: any = webpackConfig.entry
1216 1217
  if (typeof originalEntry !== 'undefined') {
    webpackConfig.entry = async () => {
1218 1219 1220 1221
      const entry: WebpackEntrypoints =
        typeof originalEntry === 'function'
          ? await originalEntry()
          : originalEntry
1222 1223 1224
      // 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]
1225
        // @ts-ignore TODO: investigate type error
1226 1227
        entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
          ...entry['main.js'],
1228
          originalFile,
1229
        ]
1230
      }
1231
      delete entry['main.js']
1232

1233
      return entry
1234 1235 1236
    }
  }

1237
  if (!dev) {
1238 1239 1240 1241
    // @ts-ignore entry is always a function
    webpackConfig.entry = await webpackConfig.entry()
  }

T
Tim Neutkens 已提交
1242
  return webpackConfig
N
nkzawa 已提交
1243
}