webpack-config.ts 24.4 KB
Newer Older
1
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
2 3
import {
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
4 5 6
  CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
  REACT_LOADABLE_MANIFEST,
  SERVER_DIRECTORY,
7
  SERVERLESS_DIRECTORY,
8
} from 'next-server/constants'
9 10
import resolve from 'next/dist/compiled/resolve/index.js'
import path from 'path'
11
import crypto from 'crypto'
12
import webpack from 'webpack'
13

14
import {
15
  DOT_NEXT_ALIAS,
16 17 18 19
  NEXT_PROJECT_ROOT,
  NEXT_PROJECT_ROOT_DIST_CLIENT,
  PAGES_DIR_ALIAS,
} from '../lib/constants'
20
import { fileExists } from '../lib/file-exists'
21
import { WebpackEntrypoints } from './entries'
22
import { AllModulesIdentifiedPlugin } from './webpack/plugins/all-modules-identified-plugin'
23
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
24
import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin'
25
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
26
import { importAutoDllPlugin } from './webpack/plugins/dll-import'
27
import { HashedChunkIdsPlugin } from './webpack/plugins/hashed-chunk-ids-plugin'
28
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
29
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
30 31 32 33 34 35 36
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'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
37 38
// @ts-ignore: JS file
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
39

40
type ExcludesFalse = <T>(x: T | false) => x is T
41

42 43 44 45 46 47
const escapePathVariables = (value: any) => {
  return typeof value === 'string'
    ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, '[\\$1\\]')
    : value
}

48 49 50 51 52 53 54 55 56 57
export default async function getBaseWebpackConfig(
  dir: string,
  {
    dev = false,
    isServer = false,
    buildId,
    config,
    target = 'server',
    entrypoints,
    selectivePageBuilding = false,
58
    tracer,
59
  }: {
60
    tracer?: any
61 62 63 64 65 66 67 68 69
    dev?: boolean
    isServer?: boolean
    buildId: string
    config: any
    target?: string
    entrypoints: WebpackEntrypoints
    selectivePageBuilding?: boolean
  }
): Promise<webpack.Configuration> {
70
  const distDir = path.join(dir, config.distDir)
T
Tim Neutkens 已提交
71 72
  const defaultLoaders = {
    babel: {
73
      loader: 'next-babel-loader',
74 75
      options: {
        isServer,
76
        hasModern: !!config.experimental.modern,
77 78
        distDir,
        cwd: dir,
79
        cache: !selectivePageBuilding,
80
      },
81
    },
82
    // Backwards compat
83
    hotSelfAccept: {
84 85
      loader: 'noop-loader',
    },
T
Tim Neutkens 已提交
86 87
  }

T
Tim Neutkens 已提交
88 89 90
  // Support for NODE_PATH
  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
91
    .filter(p => !!p)
T
Tim Neutkens 已提交
92

93 94 95 96 97 98
  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 已提交
99
  const outputPath = path.join(distDir, isServer ? outputDir : '')
100
  const totalPages = Object.keys(entrypoints).length
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  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'
            )
          ),
      }
    : undefined
N
nkzawa 已提交
116

117 118 119 120
  let typeScriptPath
  try {
    typeScriptPath = resolve.sync('typescript', { basedir: dir })
  } catch (_) {}
121
  const tsConfigPath = path.join(dir, 'tsconfig.json')
122 123 124
  const useTypeScript = Boolean(
    typeScriptPath && (await fileExists(tsConfigPath))
  )
125

T
Tim Neutkens 已提交
126
  const resolveConfig = {
127
    // Disable .mjs for node_modules bundling
128
    extensions: isServer
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
      ? [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.js',
          '.mjs',
          '.jsx',
          '.json',
          '.wasm',
        ]
      : [
          ...(useTypeScript ? ['.tsx', '.ts'] : []),
          '.mjs',
          '.js',
          '.jsx',
          '.json',
          '.wasm',
        ],
T
Tim Neutkens 已提交
145 146
    modules: [
      'node_modules',
147
      ...nodePathList, // Support for NODE_PATH environment variable
T
Tim Neutkens 已提交
148 149
    ],
    alias: {
150 151 152 153 154 155
      // 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
      'next/head': 'next-server/dist/lib/head.js',
      'next/router': 'next/dist/client/router.js',
      'next/config': 'next-server/dist/lib/runtime-config.js',
      'next/dynamic': 'next-server/dist/lib/dynamic.js',
T
Tim Neutkens 已提交
156
      next: NEXT_PROJECT_ROOT,
157
      [PAGES_DIR_ALIAS]: path.join(dir, 'pages'),
158
      [DOT_NEXT_ALIAS]: distDir,
159
    },
160
    mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
T
Tim Neutkens 已提交
161 162
  }

T
Tim Neutkens 已提交
163 164
  const webpackMode = dev ? 'development' : 'production'

165 166 167
  const terserPluginConfig = {
    parallel: true,
    sourceMap: false,
168
    cache: !selectivePageBuilding,
169
    cpus: config.experimental.cpus,
170
    distDir: distDir,
171
  }
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  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 已提交
193
  const devtool = dev ? 'cheap-module-source-map' : false
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  // 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,
      },
    },
    selective: {
      cacheGroups: {
        default: false,
        vendors: false,
        react: {
          name: 'commons',
          chunks: 'all',
212
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        },
      },
    },
    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',
229
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
230 231 232
        },
      },
    },
233
    prodGranular: {
234
      chunks: 'initial',
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
      cacheGroups: {
        default: false,
        vendors: false,
        framework: {
          name: 'framework',
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types)[\\/]/,
          priority: 40,
        },
        lib: {
          test(module: { size: Function; identifier: Function }): boolean {
            return (
              module.size() > 160000 &&
              /node_modules[/\\]/.test(module.identifier())
            )
          },
          name(module: { identifier: Function; rawRequest: string }): string {
            const rawRequest =
              module.rawRequest &&
              module.rawRequest.replace(/^@(\w+)[/\\]/, '$1-')
            if (rawRequest) return rawRequest

            const identifier = module.identifier()
            const trimmedIdentifier = /(?:^|[/\\])node_modules[/\\](.*)/.exec(
              identifier
            )
            const processedIdentifier =
              trimmedIdentifier &&
              trimmedIdentifier[1].replace(/^@(\w+)[/\\]/, '$1-')

            return processedIdentifier || identifier
          },
          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
                  },
                  ''
                )
              )
              .digest('base64')
              .replace(/\//g, '')
          },
          priority: 10,
          minChunks: 2,
          reuseExistingChunk: true,
        },
      },
      maxInitialRequests: 20,
    },
297 298 299 300 301 302 303 304 305
  }

  // Select appropriate SplitChunksPlugin config for this build
  let splitChunksConfig: webpack.Options.SplitChunksOptions
  if (dev) {
    splitChunksConfig = splitChunksConfigs.dev
  } else if (selectivePageBuilding) {
    splitChunksConfig = splitChunksConfigs.selective
  } else {
306 307 308
    splitChunksConfig = config.experimental.granularChunks
      ? splitChunksConfigs.prodGranular
      : splitChunksConfigs.prod
309 310
  }

311 312 313 314 315
  const crossOrigin =
    !config.crossOrigin && config.experimental.modern
      ? 'anonymous'
      : config.crossOrigin

316
  let webpackConfig: webpack.Configuration = {
J
JJ Kasper 已提交
317
    devtool,
T
Tim Neutkens 已提交
318
    mode: webpackMode,
T
Tim Neutkens 已提交
319 320
    name: isServer ? 'server' : 'client',
    target: isServer ? 'node' : 'web',
321 322
    externals: !isServer
      ? undefined
323
      : !isServerless
324 325 326 327 328 329 330 331 332 333
      ? [
          (context, request, callback) => {
            const notExternalModules = [
              'next/app',
              'next/document',
              'next/link',
              'next/error',
              'string-hash',
              'next/constants',
            ]
334

335 336 337
            if (notExternalModules.indexOf(request) !== -1) {
              return callback()
            }
K
k-kawakami 已提交
338

339 340 341 342 343 344 345
            resolve(
              request,
              { basedir: dir, preserveSymlinks: true },
              (err, res) => {
                if (err) {
                  return callback()
                }
K
k-kawakami 已提交
346

347 348 349
                if (!res) {
                  return callback()
                }
K
k-kawakami 已提交
350

351 352 353 354 355 356 357 358
                // Default pages have to be transpiled
                if (
                  res.match(/next[/\\]dist[/\\]/) ||
                  res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) ||
                  res.match(/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/)
                ) {
                  return callback()
                }
K
k-kawakami 已提交
359

360 361 362 363 364 365 366
                // 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 已提交
367

368 369 370
                if (res.match(/node_modules[/\\].*\.js$/)) {
                  return callback(undefined, `commonjs ${request}`)
                }
K
k-kawakami 已提交
371

372 373 374 375 376 377
                callback()
              }
            )
          },
        ]
      : [
378 379
          // 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
380
          '@ampproject/toolbox-optimizer', // except this one
381 382 383 384 385 386 387
          (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
388 389 390
              if (
                context.replace(/\\/g, '/').includes('next-server/dist/server')
              ) {
391 392 393 394 395
                return callback(undefined, `commonjs ${request}`)
              }
            }
            return callback()
          },
396 397 398 399 400
        ],
    optimization: Object.assign(
      {
        checkWasmTypes: false,
        nodeEnv: false,
401
      },
402 403 404 405
      isServer
        ? {
            splitChunks: false,
            minimize: false,
J
Joe Haddad 已提交
406
          }
407 408 409 410 411 412
        : {
            runtimeChunk: selectivePageBuilding
              ? false
              : {
                  name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
                },
413
            splitChunks: splitChunksConfig,
J
Joe Haddad 已提交
414 415
            minimize: !dev,
            minimizer: !dev
416 417 418 419
              ? [
                  new TerserPlugin({
                    ...terserPluginConfig,
                    terserOptions: {
420 421
                      ...terserOptions,
                      // Disable compress when using terser loader
422 423
                      ...(selectivePageBuilding ||
                      config.experimental.terserLoader
424
                        ? { compress: false }
425 426 427 428 429
                        : undefined),
                    },
                  }),
                ]
              : undefined,
430
          },
431 432 433 434 435
      selectivePageBuilding
        ? {
            providedExports: false,
            usedExports: false,
            concatenateModules: false,
436
          }
437 438 439 440 441
        : undefined
    ),
    recordsPath: selectivePageBuilding
      ? undefined
      : path.join(outputPath, 'records.json'),
N
nkzawa 已提交
442
    context: dir,
443
    // Kept as function to be backwards compatible
T
Tim Neutkens 已提交
444 445
    entry: async () => {
      return {
446 447
        ...(clientEntries ? clientEntries : {}),
        ...entrypoints,
T
Tim Neutkens 已提交
448 449
      }
    },
N
nkzawa 已提交
450
    output: {
451
      path: outputPath,
452
      filename: ({ chunk }: { chunk: { name: string } }) => {
453
        // Use `[name]-[contenthash].js` in production
454 455 456 457 458
        if (
          !dev &&
          (chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN ||
            chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK)
        ) {
459
          return chunk.name.replace(/\.js$/, '-[contenthash].js')
460 461 462
        }
        return '[name]'
      },
T
Tim Neutkens 已提交
463
      libraryTarget: isServer ? 'commonjs2' : 'var',
464 465 466
      hotUpdateChunkFilename: 'static/webpack/[id].[hash].hot-update.js',
      hotUpdateMainFilename: 'static/webpack/[hash].hot-update.json',
      // This saves chunks with the name given via `import()`
467 468 469
      chunkFilename: isServer
        ? `${dev ? '[name]' : '[name].[contenthash]'}.js`
        : `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
A
Andy 已提交
470
      strictModuleExceptionHandling: true,
471
      crossOriginLoading: crossOrigin,
472
      futureEmitAssets: !dev,
473
      webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
N
nkzawa 已提交
474
    },
475
    performance: false,
T
Tim Neutkens 已提交
476
    resolve: resolveConfig,
N
nkzawa 已提交
477
    resolveLoader: {
N
Naoyuki Kanezawa 已提交
478
      modules: [
479
        path.join(__dirname, 'webpack', 'loaders'), // The loaders Next.js provides
480
        'node_modules',
481 482
        ...nodePathList, // Support for NODE_PATH environment variable
      ],
N
nkzawa 已提交
483
    },
T
Tim Neutkens 已提交
484
    // @ts-ignore this is filtered
N
nkzawa 已提交
485
    module: {
486
      strictExportPresence: true,
487
      rules: [
488
        (selectivePageBuilding || config.experimental.terserLoader) &&
J
Joe Haddad 已提交
489
          !isServer && {
490 491 492 493 494 495
            test: /\.(js|mjs|jsx)$/,
            exclude: /\.min\.(js|mjs|jsx)$/,
            use: {
              loader: 'next-minify-loader',
              options: {
                terserOptions: {
496
                  ...terserOptions,
497 498 499 500 501 502 503 504 505 506 507
                  mangle: false,
                },
              },
            },
          },
        config.experimental.ampBindInitData &&
          !isServer && {
            test: /\.(tsx|ts|js|mjs|jsx)$/,
            include: [path.join(dir, 'data')],
            use: 'next-data-loader',
          },
T
Tim Neutkens 已提交
508
        {
509
          test: /\.(tsx|ts|js|mjs|jsx)$/,
510 511 512 513 514
          include: [
            dir,
            /next-server[\\/]dist[\\/]lib/,
            /next[\\/]dist[\\/]client/,
            /next[\\/]dist[\\/]pages/,
515
            /[\\/](strip-ansi|ansi-regex)[\\/]/,
516
          ],
517
          exclude: (path: string) => {
518 519 520
            if (
              /next-server[\\/]dist[\\/]lib/.test(path) ||
              /next[\\/]dist[\\/]client/.test(path) ||
521
              /next[\\/]dist[\\/]pages/.test(path) ||
522
              /[\\/](strip-ansi|ansi-regex)[\\/]/.test(path)
523
            ) {
524 525
              return false
            }
526

527
            return /node_modules/.test(path)
528
          },
529
          use: defaultLoaders.babel,
530
        },
531
      ].filter(Boolean),
N
nkzawa 已提交
532
    },
T
Tim Neutkens 已提交
533
    plugins: [
534 535
      // This plugin makes sure `output.filename` is used for entry chunks
      new ChunkNamesPlugin(),
536
      new webpack.DefinePlugin({
537
        ...Object.keys(config.env).reduce((acc, key) => {
538
          if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
539 540 541
            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`
            )
542 543 544
          }

          return {
545
            ...acc,
546
            [`process.env.${key}`]: JSON.stringify(config.env[key]),
547
          }
548
        }, {}),
549
        'process.env.NODE_ENV': JSON.stringify(webpackMode),
550
        'process.crossOrigin': JSON.stringify(crossOrigin),
551
        'process.browser': JSON.stringify(!isServer),
552 553 554
        'process.env.__NEXT_EXPERIMENTAL_SELECTIVEPAGEBUILDING': JSON.stringify(
          selectivePageBuilding
        ),
555
        // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
556 557 558 559 560 561
        ...(dev && !isServer
          ? {
              'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
            }
          : {}),
        'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
562
          config.exportTrailingSlash
563
        ),
564
        'process.env.__NEXT_MODERN_BUILD': config.experimental.modern && !dev,
565 566
        'process.env.__NEXT_GRANULAR_CHUNKS':
          config.experimental.granularChunks && !selectivePageBuilding && !dev,
567
        ...(isServer
568 569 570 571 572 573
          ? {
              // 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),
            }
574
          : undefined),
575
      }),
576 577 578 579
      !isServer &&
        new ReactLoadablePlugin({
          filename: REACT_LOADABLE_MANIFEST,
        }),
580
      !isServer && new DropClientPage(),
J
JJ Kasper 已提交
581 582 583 584 585
      new ChunkGraphPlugin(buildId, {
        dir,
        distDir,
        isServer,
      }),
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
      ...(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(),
            ]
601

602
            if (!isServer) {
603
              const AutoDllPlugin = importAutoDllPlugin({ distDir })
604 605 606 607 608 609 610 611 612
              devPlugins.push(
                new AutoDllPlugin({
                  filename: '[name]_[hash].js',
                  path: './static/development/dll',
                  context: dir,
                  entry: {
                    dll: ['react', 'react-dom'],
                  },
                  config: {
J
JJ Kasper 已提交
613
                    devtool,
614 615 616 617 618 619 620
                    mode: webpackMode,
                    resolve: resolveConfig,
                  },
                })
              )
              devPlugins.push(new webpack.HotModuleReplacementPlugin())
            }
621

622 623 624
            return devPlugins
          })()
        : []),
625
      !dev && new webpack.HashedModuleIdsPlugin(),
626 627
      // This must come after HashedModuleIdsPlugin (it sets any modules that
      // were missed by HashedModuleIdsPlugin)
628
      !dev && selectivePageBuilding && new AllModulesIdentifiedPlugin(dir),
629 630
      // This sets chunk ids to be hashed versions of their names to reduce
      // bundle churn
631
      !dev && selectivePageBuilding && new HashedChunkIdsPlugin(buildId),
J
Joe Haddad 已提交
632
      // On the client we want to share the same runtime cache
633
      !isServer && selectivePageBuilding && new SharedRuntimePlugin(),
634 635 636 637 638 639 640 641 642 643 644 645
      !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)
            )
          },
        }),
646 647 648 649 650 651 652 653
      isLikeServerless &&
        new ServerlessPlugin(buildId, {
          isServer,
          isFlyingShuttle: selectivePageBuilding,
          isTrace: isServerlessTrace,
        }),
      isServer && new PagesManifestPlugin(isLikeServerless),
      target === 'server' &&
654 655
        isServer &&
        new NextJsSSRModuleCachePlugin({ outputPath }),
656
      isServer && new NextJsSsrImportPlugin(),
657 658 659 660 661 662
      !isServer &&
        new BuildManifestPlugin({
          buildId,
          clientManifest: config.experimental.granularChunks,
          modern: config.experimental.modern,
        }),
663 664 665
      tracer &&
        new ProfilingPlugin({
          tracer,
666
        }),
667 668
      !isServer &&
        useTypeScript &&
669
        new ForkTsCheckerWebpackPlugin({
670
          typescript: typeScriptPath,
671
          async: dev,
672 673 674 675 676 677 678 679
          useTypescriptIncrementalApi: true,
          checkSyntacticErrors: true,
          tsconfig: tsConfigPath,
          reportFiles: ['**', '!**/__tests__/**', '!**/?(*.)(spec|test).*'],
          compilerOptions: { isolatedModules: true, noEmit: true },
          silent: true,
          formatter: 'codeframe',
        }),
680 681 682 683 684 685 686 687 688 689 690 691
      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')
692 693 694
              : escapePathVariables(
                  args[0].chunk.name.replace(/\.js$/, '.module.js')
                )
695 696 697 698
          },
          chunkFilename: (inputChunkName: string) =>
            inputChunkName.replace(/\.js$/, '.module.js'),
        }),
699
    ].filter((Boolean as any) as ExcludesFalse),
700
  }
701

T
Tim Neutkens 已提交
702
  if (typeof config.webpack === 'function') {
703 704 705 706 707 708 709 710 711 712
    webpackConfig = config.webpack(webpackConfig, {
      dir,
      dev,
      isServer,
      buildId,
      config,
      defaultLoaders,
      totalPages,
      webpack,
    })
713 714 715

    // @ts-ignore: Property 'then' does not exist on type 'Configuration'
    if (typeof webpackConfig.then === 'function') {
716 717 718
      console.warn(
        '> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config.md'
      )
719
    }
720
  }
T
Tim Neutkens 已提交
721

722
  // check if using @zeit/next-typescript and show warning
723 724 725
  if (
    isServer &&
    webpackConfig.module &&
726 727 728 729
    Array.isArray(webpackConfig.module.rules)
  ) {
    let foundTsRule = false

730 731
    webpackConfig.module.rules = webpackConfig.module.rules.filter(
      (rule): boolean => {
732
        if (!(rule.test instanceof RegExp)) return true
733
        if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
734 735 736 737 738
          // remove if it matches @zeit/next-typescript
          foundTsRule = rule.use === defaultLoaders.babel
          return !foundTsRule
        }
        return true
739 740
      }
    )
741 742

    if (foundTsRule) {
743
      console.warn(
744
        '\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'
745
      )
746 747 748
    }
  }

749
  // Backwards compat for `main.js` entry key
750
  const originalEntry: any = webpackConfig.entry
751 752
  if (typeof originalEntry !== 'undefined') {
    webpackConfig.entry = async () => {
753 754 755 756
      const entry: WebpackEntrypoints =
        typeof originalEntry === 'function'
          ? await originalEntry()
          : originalEntry
757 758 759 760 761
      // 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'],
762
          originalFile,
763
        ]
764
      }
765
      delete entry['main.js']
766

767
      return entry
768 769 770
    }
  }

771
  if (!dev) {
772 773 774 775
    // @ts-ignore entry is always a function
    webpackConfig.entry = await webpackConfig.entry()
  }

T
Tim Neutkens 已提交
776
  return webpackConfig
N
nkzawa 已提交
777
}