2020-03-10 19:29:40 +01:00
import chalk from 'chalk'
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
import PnpWebpackPlugin from 'pnp-webpack-plugin'
2019-09-11 22:41:29 +02:00
import webpack from 'webpack'
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 ,
2019-11-02 02:00:56 +01:00
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS ,
2019-09-11 22:41:29 +02:00
CLIENT_STATIC_FILES_RUNTIME_WEBPACK ,
REACT_LOADABLE_MANIFEST ,
SERVERLESS_DIRECTORY ,
2019-12-09 21:08:15 +01:00
SERVER_DIRECTORY ,
2019-09-11 22:41:29 +02:00
} from '../next-server/lib/constants'
2019-09-17 22:05:20 +02:00
import { findPageFile } from '../server/lib/find-page-file'
2019-04-26 18:12:40 +02:00
import { WebpackEntrypoints } from './entries'
2019-11-04 17:14:04 +01:00
import {
collectPlugins ,
PluginMetaData ,
VALID_MIDDLEWARE ,
} from './plugins/collect-plugins'
2019-12-09 21:08:15 +01:00
import { build as buildConfiguration } from './webpack/config'
2020-01-22 15:32:51 +01:00
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
2019-11-04 17:14:04 +01:00
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
2019-04-26 18:12:40 +02:00
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
2019-09-18 19:59:46 +02:00
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-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
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'
2020-01-23 22:09:12 +01:00
import WebpackConformancePlugin , {
MinificationConformanceCheck ,
2020-03-02 22:53:18 +01:00
ReactSyncScriptsConformanceCheck ,
DuplicatePolyfillsConformanceCheck ,
2020-01-23 22:09:12 +01:00
} from './webpack/plugins/webpack-conformance-plugin'
2019-04-26 18:12:40 +02:00
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
}
2020-02-18 19:26:55 +01:00
function getOptimizedAliases ( isServer : boolean ) : { [ pkg : string ] : string } {
2019-11-02 02:00:56 +01:00
if ( isServer ) {
return { }
}
2019-11-15 07:47:08 +01:00
const stubWindowFetch = path . join ( __dirname , 'polyfills' , 'fetch' , 'index.js' )
2019-11-11 05:48:11 +01:00
const stubObjectAssign = path . join ( __dirname , 'polyfills' , 'object-assign.js' )
const shimAssign = path . join ( __dirname , 'polyfills' , 'object.assign' )
2020-01-30 07:04:29 +01:00
return Object . assign (
{ } ,
{
unfetch$ : stubWindowFetch ,
'isomorphic-unfetch$' : stubWindowFetch ,
'whatwg-fetch$' : path . join (
__dirname ,
'polyfills' ,
'fetch' ,
'whatwg-fetch.js'
) ,
} ,
{
'object-assign$' : stubObjectAssign ,
// Stub Package: object.assign
'object.assign/auto' : path . join ( shimAssign , 'auto.js' ) ,
'object.assign/implementation' : path . join (
shimAssign ,
'implementation.js'
) ,
'object.assign$' : path . join ( shimAssign , 'index.js' ) ,
'object.assign/polyfill' : path . join ( shimAssign , 'polyfill.js' ) ,
'object.assign/shim' : path . join ( shimAssign , 'shim.js' ) ,
2020-02-28 04:08:58 +01:00
// Replace: full URL polyfill with platform-based polyfill
url : require.resolve ( 'native-url' ) ,
2020-01-30 07:04:29 +01:00
}
)
2019-11-02 02:00:56 +01:00
}
2020-02-17 22:16:19 +01:00
type ClientEntries = {
'main.js' : string [ ]
} & {
[ key : string ] : string
}
2019-04-26 17:23:32 +02:00
export default async function getBaseWebpackConfig (
dir : string ,
{
buildId ,
config ,
2019-09-24 17:15:14 +02:00
dev = false ,
isServer = false ,
pagesDir ,
tracer ,
2019-04-26 17:23:32 +02:00
target = 'server' ,
entrypoints ,
} : {
buildId : string
config : any
2019-09-24 17:15:14 +02:00
dev? : boolean
isServer? : boolean
pagesDir : string
2019-04-26 17:23:32 +02:00
target? : string
2019-09-24 17:15:14 +02:00
tracer? : any
2019-04-26 17:23:32 +02:00
entrypoints : WebpackEntrypoints
}
) : Promise < webpack.Configuration > {
2019-11-01 20:13:13 +01:00
let plugins : PluginMetaData [ ] = [ ]
let babelPresetPlugins : { dir : string ; config : any } [ ] = [ ]
if ( config . experimental . plugins ) {
plugins = await collectPlugins ( dir , config . env , config . plugins )
pluginLoaderOptions . plugins = plugins
for ( const plugin of plugins ) {
if ( plugin . middleware . includes ( 'babel-preset-build' ) ) {
babelPresetPlugins . push ( {
dir : plugin.directory ,
config : plugin.config ,
} )
}
}
}
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 ,
distDir ,
2019-09-24 17:15:14 +02:00
pagesDir ,
2019-04-26 17:23:32 +02:00
cwd : dir ,
2019-08-20 17:07:57 +02:00
cache : true ,
2019-11-01 20:13:13 +01:00
babelPresetPlugins ,
hasModern : ! ! config . experimental . modern ,
2019-12-03 22:08:49 +01:00
development : dev ,
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
}
2019-11-01 20:13:13 +01:00
const babelIncludeRegexes : RegExp [ ] = [
/next[\\/]dist[\\/]next-server[\\/]lib/ ,
/next[\\/]dist[\\/]client/ ,
/next[\\/]dist[\\/]pages/ ,
/[\\/](strip-ansi|ansi-regex)[\\/]/ ,
. . . ( config . experimental . plugins
2019-11-02 04:06:34 +01:00
? VALID_MIDDLEWARE . map ( name = > new RegExp ( ` src( \\ \\ |/) ${ name } ` ) )
2019-11-01 20:13:13 +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
2020-02-17 22:16:19 +01:00
? ( {
2019-04-26 17:23:32 +02:00
// 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'
)
) ,
2019-11-02 02:00:56 +01:00
[ CLIENT_STATIC_FILES_RUNTIME_POLYFILLS ] : path . join (
NEXT_PROJECT_ROOT_DIST_CLIENT ,
2020-02-18 19:26:55 +01:00
'polyfills.js'
2019-11-02 02:00:56 +01:00
) ,
2020-02-17 22:16:19 +01:00
} as ClientEntries )
2019-04-26 17:23:32 +02:00
: 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-10-28 19:02:03 +01:00
const ignoreTypeScriptErrors = dev
2020-01-08 17:30:53 +01:00
? config . typescript ? . ignoreDevErrors
: config . typescript ? . ignoreBuildErrors
2019-04-26 18:12:40 +02:00
2020-03-19 17:34:24 +01:00
let jsConfig
// jsconfig is a subset of tsconfig
if ( useTypeScript ) {
jsConfig = require ( tsConfigPath )
}
const jsConfigPath = path . join ( dir , 'jsconfig.json' )
if ( ! useTypeScript && ( await fileExists ( jsConfigPath ) ) ) {
jsConfig = require ( jsConfigPath )
}
let resolvedBaseUrl
if ( jsConfig ? . compilerOptions ? . baseUrl ) {
resolvedBaseUrl = path . resolve ( dir , jsConfig . compilerOptions . baseUrl )
}
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-09-24 17:15:14 +02:00
[ PAGES_DIR_ALIAS ] : pagesDir ,
2019-04-15 11:26:23 +02:00
[ DOT_NEXT_ALIAS ] : distDir ,
2020-02-18 19:26:55 +01:00
. . . getOptimizedAliases ( isServer ) ,
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 = {
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-10-29 01:01:25 +01:00
parallel : true ,
sourceMap : false ,
workerThreads : config.experimental.workerThreads ,
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
2020-02-04 20:22:26 +01:00
const isModuleCSS = ( module : { type : string } ) : boolean = > {
return (
// mini-css-extract-plugin
module . type === ` css/mini-extract ` ||
// extract-css-chunks-webpack-plugin (old)
module . type === ` css/extract-chunks ` ||
// extract-css-chunks-webpack-plugin (new)
module . type === ` css/extract-css-chunks `
)
}
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-10-18 17:23:06 +02:00
test : /[\\/]node_modules[\\/](react|react-dom|scheduler|use-subscription)[\\/]/ ,
2019-07-29 18:19:31 +02:00
} ,
} ,
} ,
2019-08-08 19:14:33 +02:00
prodGranular : {
2019-10-30 02:27:41 +01:00
chunks : 'all' ,
2019-08-08 19:14:33 +02:00
cacheGroups : {
default : false ,
vendors : false ,
framework : {
2019-08-22 16:46:11 +02:00
chunks : 'all' ,
2019-08-08 19:14:33 +02:00
name : 'framework' ,
2019-10-16 06:01:11 +02:00
// This regex ignores nested copies of framework libraries so they're
2019-10-14 20:02:11 +02:00
// bundled with their issuer.
// https://github.com/zeit/next.js/pull/9012
2019-10-18 17:23:06 +02:00
test : /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/ ,
2019-08-08 19:14:33 +02:00
priority : 40 ,
2019-11-04 17:25:14 +01:00
// Don't let webpack eliminate this chunk (prevents this chunk from
// becoming a part of the commons chunk)
enforce : true ,
2019-08-08 19:14:33 +02:00
} ,
lib : {
test ( module : { size : Function ; identifier : Function } ) : boolean {
return (
module . size ( ) > 160000 &&
/node_modules[/\\]/ . test ( module . identifier ( ) )
)
} ,
2019-11-25 22:52:29 +01:00
name ( module : {
type : string
libIdent? : Function
updateHash : ( hash : crypto.Hash ) = > void
} ) : string {
const hash = crypto . createHash ( 'sha1' )
2020-02-04 20:22:26 +01:00
if ( isModuleCSS ( module ) ) {
2019-11-25 22:52:29 +01:00
module . updateHash ( hash )
} else {
if ( ! module . libIdent ) {
throw new Error (
` Encountered unknown module type: ${ module . type } . Please open an issue. `
)
}
hash . update ( module . libIdent ( { context : dir } ) )
}
return hash . digest ( 'hex' ) . substring ( 0 , 8 )
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 ) {
2020-02-04 20:22:26 +01:00
return (
crypto
. createHash ( 'sha1' )
. update (
chunks . reduce (
( acc : string , chunk : webpack.compilation.Chunk ) = > {
return acc + chunk . name
} ,
''
)
2019-08-08 19:14:33 +02:00
)
2020-02-04 20:22:26 +01:00
. digest ( 'hex' ) + ( isModuleCSS ( module ) ? '_CSS' : '' )
)
2019-08-08 19:14:33 +02:00
} ,
priority : 10 ,
minChunks : 2 ,
reuseExistingChunk : true ,
} ,
} ,
2019-10-18 19:36:03 +02:00
maxInitialRequests : 25 ,
minSize : 20000 ,
2019-08-08 19:14:33 +02:00
} ,
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-09-17 22:05:20 +02:00
let customAppFile : string | null = config . experimental . css
2019-10-09 01:48:09 +02:00
? await findPageFile ( pagesDir , '/_app' , config . pageExtensions )
2019-09-17 22:05:20 +02:00
: null
if ( customAppFile ) {
2019-10-09 01:48:09 +02:00
customAppFile = path . resolve ( path . join ( pagesDir , customAppFile ) )
2019-09-17 22:05:20 +02:00
}
2020-03-02 22:53:18 +01:00
const conformanceConfig = Object . assign (
{
ReactSyncScriptsConformanceCheck : {
enabled : true ,
} ,
MinificationConformanceCheck : {
enabled : true ,
} ,
DuplicatePolyfillsConformanceCheck : {
enabled : true ,
BlockedAPIToBePolyfilled : Object.assign (
[ ] ,
[ 'fetch' ] ,
config . conformance ? . DuplicatePolyfillsConformanceCheck
? . BlockedAPIToBePolyfilled || [ ]
) ,
} ,
} ,
config . conformance
)
2019-02-20 20:24:02 +01:00
let webpackConfig : webpack.Configuration = {
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-11-01 20:13:13 +01:00
// make sure we don't externalize anything that is
// supposed to be transpiled
if ( babelIncludeRegexes . some ( r = > r . test ( request ) ) ) {
return callback ( )
}
2019-10-30 04:36:22 +01:00
// Relative requires don't need custom resolution, because they
// are relative to requests we've already resolved here.
// Absolute requires (require('/foo')) are extremely uncommon, but
// also have no need for customization as they're already resolved.
2020-01-14 10:40:45 +01:00
if ( request . startsWith ( '.' ) || request . startsWith ( '/' ) ) {
2019-10-30 12:35:51 +01:00
return callback ( )
2019-10-30 04:36:22 +01:00
}
2019-09-14 22:58:45 +02:00
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
2019-09-09 17:47:42 +02:00
let res
try {
2019-09-14 23:41:05 +02:00
res = resolveRequest ( request , ` ${ context } / ` )
2019-09-09 17:47:42 +02:00
} catch ( err ) {
2019-09-14 22:58:45 +02:00
// If the request cannot be resolved, we need to tell webpack to
// "bundle" it so that webpack shows an error (that it cannot be
// resolved).
2019-09-09 17:47:42 +02:00
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-09-14 22:58:45 +02:00
// Same as above, if the request cannot be resolved we need to have
// webpack "bundle" it so it surfaces the not found error.
2019-09-09 17:47:42 +02:00
if ( ! res ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2019-09-14 22:58:45 +02:00
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
2019-09-14 22:12:25 +02:00
let baseRes
try {
2019-09-14 23:41:05 +02:00
baseRes = resolveRequest ( request , ` ${ dir } / ` )
2019-09-14 22:12:25 +02:00
} catch ( err ) { }
2019-09-14 22:58:45 +02:00
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
2019-09-14 22:12:25 +02:00
if ( baseRes !== res ) {
return callback ( )
}
2019-09-09 17:47:42 +02:00
// Default pages have to be transpiled
if (
! res . match ( /next[/\\]dist[/\\]next-server[/\\]/ ) &&
2020-01-06 20:27:36 +01:00
( res . match ( /[/\\]next[/\\]dist[/\\]/ ) ||
2020-01-30 07:04:29 +01:00
// This is the @babel/plugin-transform-runtime "helpers: true" option
2020-02-18 19:26:55 +01:00
res . match ( /node_modules[/\\]@babel[/\\]runtime[/\\]/ ) )
2019-09-09 17:47:42 +02:00
) {
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-14 22:58:45 +02:00
// Anything else that is standard JavaScript within `node_modules`
// can be externalized.
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-14 22:58:45 +02:00
// Default behavior: bundle the code!
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-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 : [
2019-09-17 22:05:20 +02:00
// Minify JavaScript
2019-08-20 17:07:57 +02:00
new TerserPlugin ( {
. . . terserPluginConfig ,
terserOptions ,
} ) ,
2019-09-17 22:05:20 +02:00
// Minify CSS
config . experimental . css &&
2019-09-18 19:59:46 +02:00
new CssMinimizerPlugin ( {
postcssOptions : {
2019-09-17 22:05:20 +02:00
map : {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline : false ,
2019-09-18 19:59:46 +02:00
// `annotation: false` skips appending the `sourceMappingURL`
// to the end of the CSS file. Webpack already handles this.
annotation : false ,
2019-09-17 22:05:20 +02:00
} ,
} ,
} ) ,
] . filter ( Boolean ) ,
2019-08-20 17:07:57 +02:00
} ,
2016-10-14 17:05:08 +02:00
context : dir ,
2020-02-20 18:52:28 +01:00
node : {
setImmediate : false ,
} ,
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 ,
2019-11-01 20:13:13 +01:00
. . . ( isServer
? {
'init-server.js' : 'next-plugin-loader?middleware=on-init-server!' ,
'on-error-server.js' :
'next-plugin-loader?middleware=on-error-server!' ,
}
: { } ) ,
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 ||
2019-11-02 02:00:56 +01:00
chunk . name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK ||
chunk . name === CLIENT_STATIC_FILES_RUNTIME_POLYFILLS )
2019-04-26 17:23:32 +02:00
) {
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' ,
2019-10-04 17:55:18 +02:00
'error-loader' ,
2019-08-27 22:37:47 +02:00
'next-babel-loader' ,
'next-client-pages-loader' ,
'next-data-loader' ,
'next-serverless-loader' ,
'noop-loader' ,
2019-11-01 20:13:13 +01:00
'next-plugin-loader' ,
2019-11-11 04:24:53 +01:00
] . reduce ( ( alias , loader ) = > {
// using multiple aliases to replace `resolveLoader.modules`
alias [ loader ] = path . join ( __dirname , 'webpack' , 'loaders' , loader )
2019-08-27 22:37:47 +02:00
2019-11-11 04:24:53 +01:00
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
} ,
module : {
2018-01-03 13:43:48 +01:00
rules : [
2018-01-30 16:40:52 +01:00
{
2019-04-23 11:54:08 +02:00
test : /\.(tsx|ts|js|mjs|jsx)$/ ,
2019-11-01 20:13:13 +01:00
include : [ dir , . . . babelIncludeRegexes ] ,
2019-02-20 20:24:02 +01:00
exclude : ( path : string ) = > {
2019-11-01 20:13:13 +01:00
if ( babelIncludeRegexes . some ( r = > r . test ( path ) ) ) {
2019-05-01 19:16:52 +02:00
return false
}
2019-02-20 20:24:02 +01:00
return /node_modules/ . test ( path )
2018-11-28 15:03:02 +01:00
} ,
2019-12-24 16:58:50 +01:00
use : config.experimental.babelMultiThread
? [
// Move Babel transpilation into a thread pool (2 workers, unlimited batch size).
// Applying a cache to the off-thread work avoids paying transfer costs for unchanged modules.
{
loader : 'cache-loader' ,
options : {
cacheContext : dir ,
cacheDirectory : path.join ( dir , '.next' , 'cache' , 'webpack' ) ,
cacheIdentifier : ` webpack ${ isServer ? '-server' : '' } ${
config . experimental . modern ? '-hasmodern' : ''
} ` ,
} ,
} ,
{
loader : 'thread-loader' ,
options : {
workers : 2 ,
workerParallelJobs : Infinity ,
} ,
} ,
defaultLoaders . babel ,
]
: 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-09-15 23:18:11 +02:00
'process.env.__NEXT_MODERN_BUILD' : JSON . stringify (
config . experimental . modern && ! dev
) ,
'process.env.__NEXT_GRANULAR_CHUNKS' : JSON . stringify (
config . experimental . granularChunks && ! dev
) ,
'process.env.__NEXT_BUILD_INDICATOR' : JSON . stringify (
config . devIndicators . buildActivity
) ,
'process.env.__NEXT_PRERENDER_INDICATOR' : JSON . stringify (
config . devIndicators . autoPrerender
) ,
2019-11-01 20:13:13 +01:00
'process.env.__NEXT_PLUGINS' : JSON . stringify (
config . experimental . plugins
) ,
2019-10-26 00:20:38 +02:00
'process.env.__NEXT_STRICT_MODE' : JSON . stringify (
config . reactStrictMode
) ,
2019-10-30 14:39:58 +01:00
'process.env.__NEXT_REACT_MODE' : JSON . stringify (
config . experimental . reactMode
) ,
2019-12-29 20:03:12 +01:00
'process.env.__NEXT_ROUTER_BASEPATH' : JSON . stringify (
config . experimental . basePath
) ,
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-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-10-28 19:02:03 +01:00
! ignoreTypeScriptErrors &&
2019-09-24 14:54:52 +02:00
new ForkTsCheckerWebpackPlugin (
PnpWebpackPlugin . forkTsCheckerOptions ( {
typescript : typeScriptPath ,
async : dev ,
useTypescriptIncrementalApi : true ,
checkSyntacticErrors : true ,
tsconfig : tsConfigPath ,
reportFiles : [ '**' , '!**/__tests__/**' , '!**/?(*.)(spec|test).*' ] ,
compilerOptions : { isolatedModules : true , noEmit : true } ,
silent : true ,
formatter : 'codeframe' ,
} )
) ,
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' ) ,
} ) ,
2020-01-23 22:09:12 +01:00
config . experimental . conformance &&
! dev &&
new WebpackConformancePlugin ( {
2020-03-02 22:53:18 +01:00
tests : [
! isServer &&
conformanceConfig . MinificationConformanceCheck . enabled &&
new MinificationConformanceCheck ( ) ,
conformanceConfig . ReactSyncScriptsConformanceCheck . enabled &&
new ReactSyncScriptsConformanceCheck ( {
AllowedSources :
conformanceConfig . ReactSyncScriptsConformanceCheck
. allowedSources || [ ] ,
} ) ,
! isServer &&
conformanceConfig . DuplicatePolyfillsConformanceCheck . enabled &&
new DuplicatePolyfillsConformanceCheck ( {
BlockedAPIToBePolyfilled :
conformanceConfig . DuplicatePolyfillsConformanceCheck
. BlockedAPIToBePolyfilled ,
} ) ,
] . filter ( Boolean ) ,
2020-01-23 22:09:12 +01:00
} ) ,
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
2020-03-19 17:34:24 +01:00
// Support tsconfig and jsconfig baseUrl
if ( resolvedBaseUrl ) {
webpackConfig . resolve ? . modules ? . push ( resolvedBaseUrl )
}
2019-12-09 21:08:15 +01:00
webpackConfig = await buildConfiguration ( webpackConfig , {
rootDirectory : dir ,
customAppFile ,
isDevelopment : dev ,
isServer ,
hasSupportCss : ! ! config . experimental . css ,
2020-01-22 21:26:51 +01:00
hasSupportScss : ! ! config . experimental . scss ,
2020-01-03 18:45:04 +01:00
assetPrefix : config.assetPrefix || '' ,
2020-03-16 10:55:16 +01:00
sassOptions : config.experimental.sassOptions ,
2019-12-09 21:08:15 +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
2020-02-17 22:16:19 +01:00
if ( typeof ( webpackConfig as any ) . 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-12-13 21:23:28 +01:00
function canMatchCss ( rule : webpack.RuleSetCondition | undefined ) : boolean {
if ( ! rule ) {
return false
}
2020-01-10 22:07:06 +01:00
const fileNames = [
'/tmp/test.css' ,
'/tmp/test.scss' ,
'/tmp/test.sass' ,
'/tmp/test.less' ,
'/tmp/test.styl' ,
]
if ( rule instanceof RegExp && fileNames . some ( input = > rule . test ( input ) ) ) {
2019-12-13 21:23:28 +01:00
return true
}
if ( typeof rule === 'function' ) {
2020-01-10 22:07:06 +01:00
if (
fileNames . some ( input = > {
try {
if ( rule ( input ) ) {
return true
}
} catch ( _ ) { }
return false
} )
) {
return true
}
2019-12-13 21:23:28 +01:00
}
if ( Array . isArray ( rule ) && rule . some ( canMatchCss ) ) {
return true
}
return false
}
if ( config . experimental . css ) {
const hasUserCssConfig =
2020-01-10 22:07:06 +01:00
webpackConfig . module ? . rules . some (
2019-12-13 21:23:28 +01:00
rule = > canMatchCss ( rule . test ) || canMatchCss ( rule . include )
2020-01-10 22:07:06 +01:00
) ? ? false
2019-12-13 21:23:28 +01:00
if ( hasUserCssConfig ) {
2020-03-10 19:29:40 +01:00
// only show warning for one build
if ( isServer ) {
console . warn (
chalk . yellow . bold ( 'Warning: ' ) +
chalk . bold (
'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n'
) +
'See here for more info: https://err.sh/next.js/built-in-css-disabled\n'
)
}
2019-12-13 21:23:28 +01:00
if ( webpackConfig . module ? . rules . length ) {
// Remove default CSS Loader
webpackConfig . module . rules = webpackConfig . module . rules . filter (
r = >
! (
typeof r . oneOf ? . [ 0 ] ? . options === 'object' &&
r . oneOf [ 0 ] . options . __next_css_remove === true
)
)
}
if ( webpackConfig . plugins ? . length ) {
// Disable CSS Extraction Plugin
webpackConfig . plugins = webpackConfig . plugins . filter (
p = > ( p as any ) . __next_css_remove !== true
)
}
if ( webpackConfig . optimization ? . minimizer ? . length ) {
// Disable CSS Minifier
webpackConfig . optimization . minimizer = webpackConfig . optimization . minimizer . filter (
e = > ( e as any ) . __next_css_remove !== true
)
}
2019-12-31 00:53:35 +01:00
} else {
2020-01-07 22:59:58 +01:00
await __overrideCssConfiguration ( dir , ! dev , webpackConfig )
2019-12-13 21:23:28 +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
}
}
2019-11-11 04:56:29 +01:00
// Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
2019-10-05 04:53:14 +02:00
if ( webpackConfig . module && Array . isArray ( webpackConfig . module . rules ) ) {
2019-10-03 16:08:49 +02:00
; [ ] . forEach . call ( webpackConfig . module . rules , function (
rule : webpack.RuleSetRule
) {
if ( ! ( rule . test instanceof RegExp && Array . isArray ( rule . use ) ) ) {
return
}
2019-10-03 19:10:42 +02:00
const isSass =
rule . test . source === '\\.scss$' || rule . test . source === '\\.sass$'
const isLess = rule . test . source === '\\.less$'
const isCss = rule . test . source === '\\.css$'
2019-11-11 04:56:29 +01:00
const isStylus = rule . test . source === '\\.styl$'
2019-10-03 19:10:42 +02:00
// Check if the rule we're iterating over applies to Sass, Less, or CSS
2019-11-11 04:56:29 +01:00
if ( ! ( isSass || isLess || isCss || isStylus ) ) {
2019-10-03 16:08:49 +02:00
return
}
; [ ] . forEach . call ( rule . use , function ( use : webpack.RuleSetUseItem ) {
if (
! (
use &&
typeof use === 'object' &&
// Identify use statements only pertaining to `css-loader`
2019-10-04 02:01:40 +02:00
( use . loader === 'css-loader' ||
use . loader === 'css-loader/locals' ) &&
2019-10-03 16:08:49 +02:00
use . options &&
typeof use . options === 'object' &&
// The `minimize` property is a good heuristic that we need to
// perform this hack. The `minimize` property was only valid on
2019-11-11 04:56:29 +01:00
// old `css-loader` versions. Custom setups (that aren't next-sass,
// next-less or next-stylus) likely have the newer version.
2019-10-03 16:08:49 +02:00
// We still handle this gracefully below.
2019-10-08 20:28:15 +02:00
( Object . prototype . hasOwnProperty . call ( use . options , 'minimize' ) ||
Object . prototype . hasOwnProperty . call (
use . options ,
'exportOnlyLocals'
) )
2019-10-03 16:08:49 +02:00
)
) {
return
}
// Try to monkey patch within a try-catch. We shouldn't fail the build
// if we cannot pull this off.
2019-11-11 04:56:29 +01:00
// The user may not even be using the `next-sass` or `next-less` or
// `next-stylus` plugins.
2019-10-03 16:08:49 +02:00
// If it does work, great!
try {
2019-11-11 04:56:29 +01:00
// Resolve the version of `@zeit/next-css` as depended on by the Sass,
// Less or Stylus plugin.
2019-10-03 16:08:49 +02:00
const correctNextCss = resolveRequest (
'@zeit/next-css' ,
2019-10-03 19:10:42 +02:00
isCss
? // Resolve `@zeit/next-css` from the base directory
` ${ dir } / `
: // Else, resolve it from the specific plugins
require . resolve (
isSass
? '@zeit/next-sass'
: isLess
? '@zeit/next-less'
2019-11-11 04:56:29 +01:00
: isStylus
? '@zeit/next-stylus'
2019-10-03 19:10:42 +02:00
: 'next'
)
2019-10-03 16:08:49 +02:00
)
// If we found `@zeit/next-css` ...
if ( correctNextCss ) {
// ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your
// `node_modules` tree.
2019-10-04 02:01:40 +02:00
const correctCssLoader = resolveRequest ( use . loader , correctNextCss )
2019-10-03 16:08:49 +02:00
if ( correctCssLoader ) {
// We saved the user from a failed build!
use . loader = correctCssLoader
}
}
} catch ( _ ) {
// The error is not required to be handled.
}
} )
} )
}
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 ) {
2020-02-17 22:16:19 +01:00
// entry is always a function
webpackConfig . entry = await ( webpackConfig . entry as webpack . EntryFunc ) ( )
2019-04-22 20:57:02 +02:00
}
2018-01-30 16:40:52 +01:00
return webpackConfig
2016-10-14 17:05:08 +02:00
}