2019-09-11 22:41:29 +02:00
import crypto from 'crypto'
2019-05-08 03:11:56 +02:00
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
2019-04-26 18:12:40 +02:00
import path from 'path'
2019-09-06 15:49:38 +02:00
// @ts-ignore: Currently missing types
import PnpWebpackPlugin from 'pnp-webpack-plugin'
2019-09-11 22:41:29 +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-09-11 22:41:29 +02:00
import { resolveRequest } from '../lib/resolve-request'
import {
CLIENT_STATIC_FILES_RUNTIME_MAIN ,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK ,
REACT_LOADABLE_MANIFEST ,
SERVER_DIRECTORY ,
SERVERLESS_DIRECTORY ,
} from '../next-server/lib/constants'
2019-04-26 18:12:40 +02:00
import { WebpackEntrypoints } from './entries'
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-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'
2019-09-11 22:41:29 +02:00
// @ts-ignore: JS file
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
2019-04-26 18:12:40 +02:00
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'
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 ,
2019-08-18 21:45:39 +02:00
tracer ,
2019-04-26 17:23:32 +02:00
} : {
2019-08-18 21:45:39 +02:00
tracer? : any
2019-04-26 17:23:32 +02:00
dev? : boolean
isServer? : boolean
buildId : string
config : any
target? : string
entrypoints : WebpackEntrypoints
}
) : 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-08-20 17:07:57 +02:00
cache : true ,
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 {
2019-09-09 17:47:42 +02:00
typeScriptPath = resolveRequest ( 'typescript' , ` ${ dir } / ` )
2019-05-09 04:51:23 +02:00
} 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
2019-09-04 16:00:54 +02:00
'next/head' : 'next/dist/next-server/lib/head.js' ,
2019-03-24 14:33:10 +01:00
'next/router' : 'next/dist/client/router.js' ,
2019-09-04 16:00:54 +02:00
'next/config' : 'next/dist/next-server/lib/runtime-config.js' ,
'next/dynamic' : 'next/dist/next-server/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' ] ,
2019-09-06 15:49:38 +02:00
plugins : [ PnpWebpackPlugin ] ,
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-08-20 17:07:57 +02:00
cache : true ,
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 ,
} ,
} ,
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 : {
2019-08-22 16:46:11 +02:00
// Framework chunk applies to modules in dynamic chunks, unlike shared chunks
// TODO(atcastle): Analyze if other cache groups should be set to 'all' as well
chunks : 'all' ,
2019-08-08 19:14:33 +02:00
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 ( ) )
)
} ,
2019-08-23 16:28:48 +02:00
name ( module : { libIdent : Function } ) : string {
return crypto
. createHash ( 'sha1' )
. update ( module . libIdent ( { context : dir } ) )
. digest ( 'hex' )
. substring ( 0 , 8 )
2019-08-08 19:14:33 +02:00
} ,
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
} ,
''
)
)
2019-09-03 16:55:48 +02:00
. digest ( 'hex' )
2019-08-08 19:14:33 +02:00
} ,
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 {
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-09-09 17:47:42 +02:00
let res
try {
res = resolveRequest ( request , context )
} catch ( err ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-09-09 17:47:42 +02:00
if ( ! res ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-09-09 17:47:42 +02:00
// 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 ( )
}
2019-03-07 17:40:08 +01:00
2019-09-09 17:47:42 +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-09-09 17:47:42 +02:00
if ( res . match ( /node_modules[/\\].*\.js$/ ) ) {
return callback ( undefined , ` commonjs ${ request } ` )
}
2019-03-07 17:40:08 +01:00
2019-09-09 17:47:42 +02:00
callback ( )
2019-04-26 17:23:32 +02:00
} ,
]
: [
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-09-04 16:00:54 +02:00
if ( context . replace ( /\\/g , '/' ) . includes ( 'next-server/server' ) ) {
2019-07-15 16:41:53 +02:00
return callback ( undefined , ` commonjs ${ request } ` )
}
}
return callback ( )
} ,
2019-04-26 17:23:32 +02:00
] ,
2019-08-20 17:07:57 +02:00
optimization : {
checkWasmTypes : false ,
nodeEnv : false ,
splitChunks : isServer ? false : splitChunksConfig ,
runtimeChunk : isServer
? undefined
: { name : CLIENT_STATIC_FILES_RUNTIME_WEBPACK } ,
minimize : ! ( dev || isServer ) ,
minimizer : [
new TerserPlugin ( {
. . . terserPluginConfig ,
terserOptions ,
} ) ,
] ,
} ,
recordsPath : 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 : {
2019-08-27 22:37:47 +02:00
// The loaders Next.js provides
alias : [
'emit-file-loader' ,
'next-babel-loader' ,
'next-client-pages-loader' ,
'next-data-loader' ,
'next-serverless-loader' ,
'noop-loader' ,
] . reduce (
( alias , loader ) = > {
// using multiple aliases to replace `resolveLoader.modules`
alias [ loader ] = path . join ( __dirname , 'webpack' , 'loaders' , loader )
return alias
} ,
{ } as Record < string , string >
) ,
2016-12-28 19:16:52 +01:00
modules : [
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
] ,
2019-09-06 15:49:38 +02:00
plugins : [ PnpWebpackPlugin ] ,
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
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 ,
2019-09-04 16:00:54 +02:00
/next[\\/]dist[\\/]next-server[\\/]lib/ ,
2019-05-01 19:16:52 +02:00
/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 (
2019-09-04 16:00:54 +02:00
/next[\\/]dist[\\/]next-server[\\/]lib/ . test ( path ) ||
2019-05-08 03:11:56 +02:00
/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-22 22:34:24 +02:00
'process.env.__NEXT_TEST_MODE' : JSON . stringify (
process . env . __NEXT_TEST_MODE
) ,
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' :
2019-08-20 17:07:57 +02:00
config . experimental . granularChunks && ! 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-08-20 21:19:45 +02:00
// 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$/ ) ,
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-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-30 13:26:30 +02:00
isServerless && isServer && new ServerlessPlugin ( ) ,
2019-08-06 00:26:20 +02:00
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-08-18 21:45:39 +02:00
tracer &&
new ProfilingPlugin ( {
tracer ,
2019-04-26 17:23:32 +02:00
} ) ,
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 (
2019-08-21 17:58:31 +02:00
'> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config'
2019-04-26 17:23:32 +02:00
)
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 ]
2019-09-04 16:00:54 +02:00
// @ts-ignore TODO: investigate type error
2019-03-25 15:08:02 +01:00
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
}