2019-05-08 03:11:56 +02:00
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
2019-04-26 17:23:32 +02:00
import {
CLIENT_STATIC_FILES_RUNTIME_MAIN ,
2019-04-26 18:12:40 +02:00
CLIENT_STATIC_FILES_RUNTIME_WEBPACK ,
REACT_LOADABLE_MANIFEST ,
SERVER_DIRECTORY ,
2019-08-06 00:26:20 +02:00
SERVERLESS_DIRECTORY ,
2019-04-26 17:23:32 +02:00
} from 'next-server/constants'
2019-04-26 18:12:40 +02:00
import resolve from 'next/dist/compiled/resolve/index.js'
import path from 'path'
2019-08-08 19:14:33 +02:00
import crypto from 'crypto'
2019-06-24 15:48:26 +02:00
import webpack from 'webpack'
2019-04-26 18:12:40 +02:00
2019-04-26 17:23:32 +02:00
import {
2019-04-26 18:12:40 +02:00
DOT_NEXT_ALIAS ,
2019-04-26 17:23:32 +02:00
NEXT_PROJECT_ROOT ,
NEXT_PROJECT_ROOT_DIST_CLIENT ,
PAGES_DIR_ALIAS ,
} from '../lib/constants'
2019-07-17 08:01:21 +02:00
import { fileExists } from '../lib/file-exists'
2019-04-26 18:12:40 +02:00
import { WebpackEntrypoints } from './entries'
2019-03-14 16:04:08 +01:00
import { AllModulesIdentifiedPlugin } from './webpack/plugins/all-modules-identified-plugin'
2019-04-26 18:12:40 +02:00
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
2019-04-02 21:48:05 +02:00
import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin'
2019-04-26 18:12:40 +02:00
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
2019-06-24 15:48:26 +02:00
import { importAutoDllPlugin } from './webpack/plugins/dll-import'
2019-04-26 18:12:40 +02:00
import { HashedChunkIdsPlugin } from './webpack/plugins/hashed-chunk-ids-plugin'
2019-05-08 03:11:56 +02:00
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
2019-08-06 00:26:20 +02:00
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
2019-04-26 18:12:40 +02:00
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'
2019-02-20 20:24:02 +01:00
type ExcludesFalse = < T > ( x : T | false ) = > x is T
2016-12-28 00:28:19 +01:00
2019-08-12 05:32:18 +02:00
const escapePathVariables = ( value : any ) = > {
return typeof value === 'string'
? value . replace ( /\[(\\*[\w:]+\\*)\]/gi , '[\\$1\\]' )
: value
}
2019-04-26 17:23:32 +02:00
export default async function getBaseWebpackConfig (
dir : string ,
{
dev = false ,
isServer = false ,
buildId ,
config ,
target = 'server' ,
entrypoints ,
selectivePageBuilding = false ,
} : {
dev? : boolean
isServer? : boolean
buildId : string
config : any
target? : string
entrypoints : WebpackEntrypoints
selectivePageBuilding? : boolean
}
) : Promise < webpack.Configuration > {
2019-04-22 18:16:42 +02:00
const distDir = path . join ( dir , config . distDir )
2018-01-30 16:40:52 +01:00
const defaultLoaders = {
babel : {
2018-05-23 20:26:57 +02:00
loader : 'next-babel-loader' ,
2019-04-26 17:23:32 +02:00
options : {
isServer ,
2019-08-12 06:10:12 +02:00
hasModern : ! ! config . experimental . modern ,
2019-04-26 17:23:32 +02:00
distDir ,
cwd : dir ,
2019-05-17 21:39:18 +02:00
cache : ! selectivePageBuilding ,
2019-04-26 17:23:32 +02:00
} ,
2018-06-14 19:30:14 +02:00
} ,
2019-01-08 23:10:32 +01:00
// Backwards compat
2018-06-14 19:30:14 +02:00
hotSelfAccept : {
2019-04-26 17:23:32 +02:00
loader : 'noop-loader' ,
} ,
2018-01-30 16:40:52 +01:00
}
2018-02-01 16:21:18 +01:00
// Support for NODE_PATH
const nodePathList = ( process . env . NODE_PATH || '' )
. split ( process . platform === 'win32' ? ';' : ':' )
2019-04-26 17:23:32 +02:00
. filter ( p = > ! ! p )
2018-02-01 16:21:18 +01:00
2019-08-06 00:26:20 +02:00
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
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
const outputPath = path . join ( distDir , isServer ? outputDir : '' )
2019-01-08 23:10:32 +01:00
const totalPages = Object . keys ( entrypoints ) . length
2019-04-26 17:23:32 +02:00
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
2016-10-19 14:41:45 +02:00
2019-05-09 04:51:23 +02:00
let typeScriptPath
try {
typeScriptPath = resolve . sync ( 'typescript' , { basedir : dir } )
} catch ( _ ) { }
2019-05-08 03:11:56 +02:00
const tsConfigPath = path . join ( dir , 'tsconfig.json' )
2019-05-09 04:51:23 +02:00
const useTypeScript = Boolean (
typeScriptPath && ( await fileExists ( tsConfigPath ) )
)
2019-04-26 18:12:40 +02:00
2018-08-14 00:09:05 +02:00
const resolveConfig = {
2018-11-20 12:13:31 +01:00
// Disable .mjs for node_modules bundling
2019-04-26 17:23:32 +02:00
extensions : isServer
2019-04-26 18:12:40 +02:00
? [
. . . ( useTypeScript ? [ '.tsx' , '.ts' ] : [ ] ) ,
'.js' ,
'.mjs' ,
'.jsx' ,
'.json' ,
'.wasm' ,
]
: [
. . . ( useTypeScript ? [ '.tsx' , '.ts' ] : [ ] ) ,
'.mjs' ,
'.js' ,
'.jsx' ,
'.json' ,
'.wasm' ,
] ,
2018-08-14 00:09:05 +02:00
modules : [
'node_modules' ,
2019-04-26 17:23:32 +02:00
. . . nodePathList , // Support for NODE_PATH environment variable
2018-08-14 00:09:05 +02:00
] ,
alias : {
2019-03-24 14:33:10 +01:00
// 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' ,
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
next : NEXT_PROJECT_ROOT ,
2019-01-08 23:10:32 +01:00
[ PAGES_DIR_ALIAS ] : path . join ( dir , 'pages' ) ,
2019-04-15 11:26:23 +02:00
[ DOT_NEXT_ALIAS ] : distDir ,
2018-12-04 10:59:12 +01:00
} ,
2019-04-26 17:23:32 +02:00
mainFields : isServer ? [ 'main' , 'module' ] : [ 'browser' , 'module' , 'main' ] ,
2018-08-14 00:09:05 +02:00
}
2018-08-30 12:27:22 +02:00
const webpackMode = dev ? 'development' : 'production'
2019-02-20 20:24:02 +01:00
const terserPluginConfig = {
parallel : true ,
sourceMap : false ,
2019-04-26 14:47:57 +02:00
cache : ! selectivePageBuilding ,
2019-03-11 17:33:30 +01:00
cpus : config.experimental.cpus ,
2019-04-26 17:23:32 +02:00
distDir : distDir ,
2019-02-20 20:24:02 +01:00
}
2019-06-11 19:34:45 +02:00
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 ,
} ,
}
2019-07-01 19:13:06 +02:00
const devtool = dev ? 'cheap-module-source-map' : false
2019-02-20 20:24:02 +01:00
2019-07-29 18:19:31 +02:00
// 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' ,
2019-07-29 19:42:57 +02:00
test : /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/ ,
2019-07-29 18:19:31 +02:00
} ,
} ,
} ,
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' ,
2019-07-29 19:42:57 +02:00
test : /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/ ,
2019-07-29 18:19:31 +02:00
} ,
} ,
} ,
2019-08-08 19:14:33 +02:00
prodGranular : {
2019-08-13 02:35:33 +02:00
chunks : 'initial' ,
2019-08-08 19:14:33 +02:00
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 ,
} ,
2019-07-29 18:19:31 +02:00
}
// Select appropriate SplitChunksPlugin config for this build
let splitChunksConfig : webpack.Options.SplitChunksOptions
if ( dev ) {
splitChunksConfig = splitChunksConfigs . dev
} else if ( selectivePageBuilding ) {
splitChunksConfig = splitChunksConfigs . selective
} else {
2019-08-08 19:14:33 +02:00
splitChunksConfig = config . experimental . granularChunks
? splitChunksConfigs . prodGranular
: splitChunksConfigs . prod
2019-07-29 18:19:31 +02:00
}
2019-07-25 04:16:32 +02:00
const crossOrigin =
! config . crossOrigin && config . experimental . modern
? 'anonymous'
: config . crossOrigin
2019-02-20 20:24:02 +01:00
let webpackConfig : webpack.Configuration = {
2019-05-05 13:03:13 +02:00
devtool ,
2018-08-30 12:27:22 +02:00
mode : webpackMode ,
2018-01-30 16:40:52 +01:00
name : isServer ? 'server' : 'client' ,
target : isServer ? 'node' : 'web' ,
2019-04-26 17:23:32 +02:00
externals : ! isServer
? undefined
2019-08-06 00:26:20 +02:00
: ! isServerless
2019-04-26 17:23:32 +02:00
? [
( context , request , callback ) = > {
const notExternalModules = [
'next/app' ,
'next/document' ,
'next/link' ,
'next/error' ,
'string-hash' ,
'next/constants' ,
]
2019-02-20 20:24:02 +01:00
2019-04-26 17:23:32 +02:00
if ( notExternalModules . indexOf ( request ) !== - 1 ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
resolve (
request ,
{ basedir : dir , preserveSymlinks : true } ,
( err , res ) = > {
if ( err ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
if ( ! res ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
// 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 ( )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
// 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 ( )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
if ( res . match ( /node_modules[/\\].*\.js$/ ) ) {
return callback ( undefined , ` commonjs ${ request } ` )
}
2019-03-07 17:40:08 +01:00
2019-04-26 17:23:32 +02:00
callback ( )
}
)
} ,
]
: [
2019-08-06 00:26:20 +02:00
// 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
2019-08-07 16:47:46 +02:00
'@ampproject/toolbox-optimizer' , // except this one
2019-07-15 16:41:53 +02:00
( 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
2019-07-17 20:21:24 +02:00
if (
context . replace ( /\\/g , '/' ) . includes ( 'next-server/dist/server' )
) {
2019-07-15 16:41:53 +02:00
return callback ( undefined , ` commonjs ${ request } ` )
}
}
return callback ( )
} ,
2019-04-26 17:23:32 +02:00
] ,
optimization : Object.assign (
{
checkWasmTypes : false ,
nodeEnv : false ,
2019-04-03 02:22:04 +02:00
} ,
2019-04-26 17:23:32 +02:00
isServer
? {
splitChunks : false ,
minimize : false ,
2019-03-27 16:51:05 +01:00
}
2019-04-26 17:23:32 +02:00
: {
runtimeChunk : selectivePageBuilding
? false
: {
name : CLIENT_STATIC_FILES_RUNTIME_WEBPACK ,
} ,
2019-07-29 18:19:31 +02:00
splitChunks : splitChunksConfig ,
2019-07-01 19:13:06 +02:00
minimize : ! dev ,
minimizer : ! dev
2019-04-26 17:23:32 +02:00
? [
new TerserPlugin ( {
. . . terserPluginConfig ,
terserOptions : {
2019-06-11 19:34:45 +02:00
. . . terserOptions ,
// Disable compress when using terser loader
2019-04-26 17:23:32 +02:00
. . . ( selectivePageBuilding ||
config . experimental . terserLoader
2019-06-11 19:34:45 +02:00
? { compress : false }
2019-04-26 17:23:32 +02:00
: undefined ) ,
} ,
} ) ,
]
: undefined ,
2019-02-20 20:24:02 +01:00
} ,
2019-04-26 17:23:32 +02:00
selectivePageBuilding
? {
providedExports : false ,
usedExports : false ,
concatenateModules : false ,
2019-02-20 20:24:02 +01:00
}
2019-04-26 17:23:32 +02:00
: undefined
) ,
recordsPath : selectivePageBuilding
? undefined
: path . join ( outputPath , 'records.json' ) ,
2016-10-14 17:05:08 +02:00
context : dir ,
2018-03-31 14:00:56 +02:00
// Kept as function to be backwards compatible
2018-01-30 16:40:52 +01:00
entry : async ( ) = > {
return {
2019-04-26 17:23:32 +02:00
. . . ( clientEntries ? clientEntries : { } ) ,
. . . entrypoints ,
2018-01-30 16:40:52 +01:00
}
} ,
2016-10-14 17:05:08 +02:00
output : {
2018-07-24 11:24:40 +02:00
path : outputPath ,
2019-04-26 17:23:32 +02:00
filename : ( { chunk } : { chunk : { name : string } } ) = > {
2018-08-04 19:00:13 +02:00
// Use `[name]-[contenthash].js` in production
2019-04-26 17:23:32 +02:00
if (
! dev &&
( chunk . name === CLIENT_STATIC_FILES_RUNTIME_MAIN ||
chunk . name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK )
) {
2018-08-04 20:18:20 +02:00
return chunk . name . replace ( /\.js$/ , '-[contenthash].js' )
2018-07-24 11:24:40 +02:00
}
return '[name]'
} ,
2019-04-08 11:14:51 +02:00
libraryTarget : isServer ? 'commonjs2' : 'var' ,
2018-07-24 11:24:40 +02:00
hotUpdateChunkFilename : 'static/webpack/[id].[hash].hot-update.js' ,
hotUpdateMainFilename : 'static/webpack/[hash].hot-update.json' ,
// This saves chunks with the name given via `import()`
2019-04-26 17:23:32 +02:00
chunkFilename : isServer
? ` ${ dev ? '[name]' : '[name].[contenthash]' } .js `
: ` static/chunks/ ${ dev ? '[name]' : '[name].[contenthash]' } .js ` ,
2018-10-02 13:10:07 +02:00
strictModuleExceptionHandling : true ,
2019-07-25 04:16:32 +02:00
crossOriginLoading : crossOrigin ,
2019-01-24 10:25:58 +01:00
futureEmitAssets : ! dev ,
2019-04-26 17:23:32 +02:00
webassemblyModuleFilename : 'static/wasm/[modulehash].wasm' ,
2016-10-14 17:05:08 +02:00
} ,
2019-04-09 19:43:24 +02:00
performance : false ,
2018-08-14 00:09:05 +02:00
resolve : resolveConfig ,
2016-10-14 17:05:08 +02:00
resolveLoader : {
2016-12-28 19:16:52 +01:00
modules : [
2018-06-16 19:23:02 +02:00
path . join ( __dirname , 'webpack' , 'loaders' ) , // The loaders Next.js provides
2019-04-08 14:57:21 +02:00
'node_modules' ,
2019-04-26 17:23:32 +02:00
. . . nodePathList , // Support for NODE_PATH environment variable
] ,
2016-10-14 17:05:08 +02:00
} ,
2019-04-02 16:09:34 +02:00
// @ts-ignore this is filtered
2016-10-14 17:05:08 +02:00
module : {
2019-05-28 21:43:07 +02:00
strictExportPresence : true ,
2018-01-03 13:43:48 +01:00
rules : [
2019-04-26 17:23:32 +02:00
( selectivePageBuilding || config . experimental . terserLoader ) &&
2019-07-01 19:13:06 +02:00
! isServer && {
2019-04-26 17:23:32 +02:00
test : /\.(js|mjs|jsx)$/ ,
exclude : /\.min\.(js|mjs|jsx)$/ ,
use : {
loader : 'next-minify-loader' ,
options : {
terserOptions : {
2019-06-11 19:34:45 +02:00
. . . terserOptions ,
2019-04-26 17:23:32 +02:00
mangle : false ,
} ,
} ,
} ,
} ,
config . experimental . ampBindInitData &&
! isServer && {
test : /\.(tsx|ts|js|mjs|jsx)$/ ,
include : [ path . join ( dir , 'data' ) ] ,
use : 'next-data-loader' ,
} ,
2018-01-30 16:40:52 +01:00
{
2019-04-23 11:54:08 +02:00
test : /\.(tsx|ts|js|mjs|jsx)$/ ,
2019-05-01 19:16:52 +02:00
include : [
dir ,
/next-server[\\/]dist[\\/]lib/ ,
/next[\\/]dist[\\/]client/ ,
/next[\\/]dist[\\/]pages/ ,
2019-06-24 17:45:36 +02:00
/[\\/](strip-ansi|ansi-regex)[\\/]/ ,
2019-05-01 19:16:52 +02:00
] ,
2019-02-20 20:24:02 +01:00
exclude : ( path : string ) = > {
2019-05-08 03:11:56 +02:00
if (
/next-server[\\/]dist[\\/]lib/ . test ( path ) ||
/next[\\/]dist[\\/]client/ . test ( path ) ||
2019-06-24 17:45:36 +02:00
/next[\\/]dist[\\/]pages/ . test ( path ) ||
2019-06-25 03:05:15 +02:00
/[\\/](strip-ansi|ansi-regex)[\\/]/ . test ( path )
2019-05-08 03:11:56 +02:00
) {
2019-05-01 19:16:52 +02:00
return false
}
2018-11-28 15:03:02 +01:00
2019-02-20 20:24:02 +01:00
return /node_modules/ . test ( path )
2018-11-28 15:03:02 +01:00
} ,
2019-04-26 17:23:32 +02:00
use : defaultLoaders.babel ,
2019-04-21 23:25:17 +02:00
} ,
2019-04-26 17:23:32 +02:00
] . filter ( Boolean ) ,
2016-10-16 06:01:17 +02:00
} ,
2018-01-30 16:40:52 +01:00
plugins : [
2018-07-24 11:24:40 +02:00
// This plugin makes sure `output.filename` is used for entry chunks
new ChunkNamesPlugin ( ) ,
2019-02-15 17:49:40 +01:00
new webpack . DefinePlugin ( {
2019-04-26 17:23:32 +02:00
. . . Object . keys ( config . env ) . reduce ( ( acc , key ) = > {
2019-07-29 09:17:10 +02:00
if ( /^(?:NODE_.+)|^(?:__.+)$/i . test ( key ) ) {
2019-04-26 17:23:32 +02:00
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 `
)
2019-02-15 17:49:40 +01:00
}
return {
2019-02-08 14:38:18 +01:00
. . . acc ,
2019-04-26 17:23:32 +02:00
[ ` process.env. ${ key } ` ] : JSON . stringify ( config . env [ key ] ) ,
2019-02-15 17:49:40 +01:00
}
2019-04-26 17:23:32 +02:00
} , { } ) ,
2019-04-09 15:16:27 +02:00
'process.env.NODE_ENV' : JSON . stringify ( webpackMode ) ,
2019-07-25 04:16:32 +02:00
'process.crossOrigin' : JSON . stringify ( crossOrigin ) ,
2019-03-10 05:27:33 +01:00
'process.browser' : JSON . stringify ( ! isServer ) ,
2019-08-12 00:03:11 +02:00
'process.env.__NEXT_EXPERIMENTAL_SELECTIVEPAGEBUILDING' : JSON . stringify (
selectivePageBuilding
) ,
2019-03-10 05:27:33 +01:00
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
2019-04-26 17:23:32 +02:00
. . . ( dev && ! isServer
? {
'process.env.__NEXT_DIST_DIR' : JSON . stringify ( distDir ) ,
}
: { } ) ,
'process.env.__NEXT_EXPORT_TRAILING_SLASH' : JSON . stringify (
2019-07-03 19:25:44 +02:00
config . exportTrailingSlash
2019-04-26 17:23:32 +02:00
) ,
2019-07-25 04:16:32 +02:00
'process.env.__NEXT_MODERN_BUILD' : config . experimental . modern && ! dev ,
2019-08-08 19:14:33 +02:00
'process.env.__NEXT_GRANULAR_CHUNKS' :
config . experimental . granularChunks && ! selectivePageBuilding && ! dev ,
2019-06-19 02:59:30 +02:00
. . . ( isServer
2019-07-11 19:02:43 +02:00
? {
// 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 ) ,
}
2019-08-14 04:02:53 +02:00
: undefined ) ,
2019-04-24 11:04:36 +02:00
} ) ,
2019-04-26 17:23:32 +02:00
! isServer &&
new ReactLoadablePlugin ( {
filename : REACT_LOADABLE_MANIFEST ,
} ) ,
2019-04-21 23:25:17 +02:00
! isServer && new DropClientPage ( ) ,
2019-05-01 22:31:08 +02:00
new ChunkGraphPlugin ( buildId , {
dir ,
distDir ,
isServer ,
} ) ,
2019-04-26 17:23:32 +02:00
. . . ( 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 ( ) ,
]
2019-03-10 05:27:33 +01:00
2019-04-26 17:23:32 +02:00
if ( ! isServer ) {
2019-06-24 15:48:26 +02:00
const AutoDllPlugin = importAutoDllPlugin ( { distDir } )
2019-04-26 17:23:32 +02:00
devPlugins . push (
new AutoDllPlugin ( {
filename : '[name]_[hash].js' ,
path : './static/development/dll' ,
context : dir ,
entry : {
dll : [ 'react' , 'react-dom' ] ,
} ,
config : {
2019-05-05 13:03:13 +02:00
devtool ,
2019-04-26 17:23:32 +02:00
mode : webpackMode ,
resolve : resolveConfig ,
} ,
} )
)
devPlugins . push ( new webpack . HotModuleReplacementPlugin ( ) )
}
2019-03-10 05:27:33 +01:00
2019-04-26 17:23:32 +02:00
return devPlugins
} ) ( )
: [ ] ) ,
2019-03-10 05:27:33 +01:00
! dev && new webpack . HashedModuleIdsPlugin ( ) ,
2019-03-14 16:04:08 +01:00
// This must come after HashedModuleIdsPlugin (it sets any modules that
// were missed by HashedModuleIdsPlugin)
2019-04-24 18:50:29 +02:00
! dev && selectivePageBuilding && new AllModulesIdentifiedPlugin ( dir ) ,
2019-03-15 02:38:57 +01:00
// This sets chunk ids to be hashed versions of their names to reduce
// bundle churn
2019-04-24 18:50:29 +02:00
! dev && selectivePageBuilding && new HashedChunkIdsPlugin ( buildId ) ,
2019-03-26 17:30:31 +01:00
// On the client we want to share the same runtime cache
2019-04-10 04:05:40 +02:00
! isServer && selectivePageBuilding && new SharedRuntimePlugin ( ) ,
2019-04-26 17:23:32 +02:00
! 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 )
)
} ,
} ) ,
2019-08-06 00:26:20 +02:00
isLikeServerless &&
new ServerlessPlugin ( buildId , {
isServer ,
isFlyingShuttle : selectivePageBuilding ,
isTrace : isServerlessTrace ,
} ) ,
isServer && new PagesManifestPlugin ( isLikeServerless ) ,
target === 'server' &&
2019-04-26 17:23:32 +02:00
isServer &&
new NextJsSSRModuleCachePlugin ( { outputPath } ) ,
2019-03-10 05:27:33 +01:00
isServer && new NextJsSsrImportPlugin ( ) ,
2019-08-08 19:14:33 +02:00
! isServer &&
new BuildManifestPlugin ( {
buildId ,
clientManifest : config.experimental.granularChunks ,
modern : config.experimental.modern ,
} ) ,
2019-04-26 17:23:32 +02:00
config . experimental . profiling &&
new webpack . debug . ProfilingPlugin ( {
outputPath : path.join (
distDir ,
` profile-events- ${ isServer ? 'server' : 'client' } .json `
) ,
} ) ,
2019-05-09 04:51:23 +02:00
! isServer &&
useTypeScript &&
2019-05-08 03:11:56 +02:00
new ForkTsCheckerWebpackPlugin ( {
2019-05-09 04:51:23 +02:00
typescript : typeScriptPath ,
2019-06-26 20:54:23 +02:00
async : dev ,
2019-05-08 03:11:56 +02:00
useTypescriptIncrementalApi : true ,
checkSyntacticErrors : true ,
tsconfig : tsConfigPath ,
reportFiles : [ '**' , '!**/__tests__/**' , '!**/?(*.)(spec|test).*' ] ,
compilerOptions : { isolatedModules : true , noEmit : true } ,
silent : true ,
formatter : 'codeframe' ,
} ) ,
2019-07-25 04:16:32 +02:00
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' )
2019-08-12 05:32:18 +02:00
: escapePathVariables (
args [ 0 ] . chunk . name . replace ( /\.js$/ , '.module.js' )
)
2019-07-25 04:16:32 +02:00
} ,
chunkFilename : ( inputChunkName : string ) = >
inputChunkName . replace ( /\.js$/ , '.module.js' ) ,
} ) ,
2019-04-26 17:23:32 +02:00
] . filter ( ( Boolean as any ) as ExcludesFalse ) ,
2016-12-17 19:38:11 +01:00
}
2016-12-22 02:36:00 +01:00
2018-01-30 16:40:52 +01:00
if ( typeof config . webpack === 'function' ) {
2019-04-26 17:23:32 +02:00
webpackConfig = config . webpack ( webpackConfig , {
dir ,
dev ,
isServer ,
buildId ,
config ,
defaultLoaders ,
totalPages ,
webpack ,
} )
2019-02-28 14:39:51 +01:00
// @ts-ignore: Property 'then' does not exist on type 'Configuration'
if ( typeof webpackConfig . then === 'function' ) {
2019-04-26 17:23:32 +02:00
console . warn (
'> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config.md'
)
2019-02-28 14:39:51 +01:00
}
2016-12-17 19:38:11 +01:00
}
2018-01-30 16:40:52 +01:00
2019-04-25 22:49:39 +02:00
// check if using @zeit/next-typescript and show warning
2019-04-26 17:23:32 +02:00
if (
isServer &&
webpackConfig . module &&
2019-04-25 22:49:39 +02:00
Array . isArray ( webpackConfig . module . rules )
) {
let foundTsRule = false
2019-04-26 17:23:32 +02:00
webpackConfig . module . rules = webpackConfig . module . rules . filter (
( rule ) : boolean = > {
2019-04-25 22:49:39 +02:00
if ( ! ( rule . test instanceof RegExp ) ) return true
2019-04-26 17:23:32 +02:00
if ( 'noop.ts' . match ( rule . test ) && ! 'noop.js' . match ( rule . test ) ) {
2019-04-25 22:49:39 +02:00
// remove if it matches @zeit/next-typescript
foundTsRule = rule . use === defaultLoaders . babel
return ! foundTsRule
}
return true
2019-04-26 17:23:32 +02:00
}
)
2019-04-25 22:49:39 +02:00
if ( foundTsRule ) {
2019-04-26 17:23:32 +02:00
console . warn (
2019-08-11 13:09:01 +02:00
'\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'
2019-04-26 17:23:32 +02:00
)
2019-04-25 22:49:39 +02:00
}
}
2018-07-24 11:24:40 +02:00
// Backwards compat for `main.js` entry key
2019-03-24 14:33:10 +01:00
const originalEntry : any = webpackConfig . entry
2019-02-20 20:24:02 +01:00
if ( typeof originalEntry !== 'undefined' ) {
webpackConfig . entry = async ( ) = > {
2019-04-26 17:23:32 +02:00
const entry : WebpackEntrypoints =
typeof originalEntry === 'function'
? await originalEntry ( )
: originalEntry
2019-03-25 15:08:02 +01:00
// 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' ] ,
2019-04-26 17:23:32 +02:00
originalFile ,
2019-03-25 15:08:02 +01:00
]
2019-02-20 20:24:02 +01:00
}
2019-03-25 15:08:02 +01:00
delete entry [ 'main.js' ]
2018-07-24 11:24:40 +02:00
2019-02-20 20:24:02 +01:00
return entry
2018-07-24 11:24:40 +02:00
}
}
2019-04-26 17:23:32 +02:00
if ( ! dev ) {
2019-04-22 20:57:02 +02:00
// @ts-ignore entry is always a function
webpackConfig . entry = await webpackConfig . entry ( )
}
2018-01-30 16:40:52 +01:00
return webpackConfig
2016-10-14 17:05:08 +02:00
}