2020-11-06 03:33:14 +01:00
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
2020-04-19 19:58:31 +02:00
import ReactRefreshWebpackPlugin from '@next/react-refresh-utils/ReactRefreshWebpackPlugin'
2019-09-11 22:41:29 +02:00
import crypto from 'crypto'
2020-10-14 13:36:59 +02:00
import { readFileSync , realpathSync } from 'fs'
2020-11-06 03:33:14 +01:00
import chalk from 'chalk'
2020-09-01 17:29:25 +02:00
import semver from 'next/dist/compiled/semver'
2020-12-12 21:28:53 +01:00
// @ts-ignore No typings yet
import TerserPlugin from './webpack/plugins/terser-webpack-plugin/src/index.js'
2019-04-26 18:12:40 +02:00
import path from 'path'
2021-01-14 02:59:08 +01:00
import {
webpack ,
isWebpack5 ,
init as initWebpack ,
} from 'next/dist/compiled/webpack/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'
2020-09-01 17:29:25 +02:00
import { getPackageVersion } from '../lib/get-package-version'
import { Rewrite } from '../lib/load-custom-routes'
2020-07-28 12:00:27 +02:00
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
2019-09-11 22:41:29 +02:00
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'
2020-06-24 06:15:57 +02:00
import { execOnce } from '../next-server/lib/utils'
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'
2020-08-04 23:24:56 +02:00
import * as Log from './output/log'
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'
2020-04-15 20:20:25 +02:00
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
2019-05-08 03:11:56 +02:00
import { DropClientPage } from './webpack/plugins/next-drop-client-page-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'
2020-01-23 22:09:12 +01:00
import WebpackConformancePlugin , {
2020-04-15 20:20:25 +02:00
DuplicatePolyfillsConformanceCheck ,
2020-06-24 06:15:57 +02:00
GranularChunksConformanceCheck ,
2020-01-23 22:09:12 +01:00
MinificationConformanceCheck ,
2020-03-02 22:53:18 +01:00
ReactSyncScriptsConformanceCheck ,
2020-01-23 22:09:12 +01:00
} from './webpack/plugins/webpack-conformance-plugin'
2020-05-13 17:43:41 +02:00
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
2020-12-04 11:14:55 +01:00
import { NextConfig } from '../next-server/server/config'
2020-09-01 17:29:25 +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
2021-01-14 02:59:08 +01:00
const devtoolRevertWarning = execOnce (
( devtool : webpack.Configuration [ 'devtool' ] ) = > {
console . warn (
chalk . yellow . bold ( 'Warning: ' ) +
chalk . bold ( ` Reverting webpack devtool to ' ${ devtool } '. \ n ` ) +
'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
'Read more: https://err.sh/next.js/improper-devtool'
)
}
)
2020-06-24 06:15:57 +02:00
2020-06-01 23:00:22 +02:00
function parseJsonFile ( filePath : string ) {
2020-03-29 01:36:15 +01:00
const JSON5 = require ( 'next/dist/compiled/json5' )
2020-06-01 23:00:22 +02:00
const contents = readFileSync ( filePath , 'utf8' )
2020-05-18 18:31:15 +02:00
// Special case an empty file
if ( contents . trim ( ) === '' ) {
return { }
}
2020-05-18 18:07:08 +02:00
try {
return JSON5 . parse ( contents )
} catch ( err ) {
const codeFrame = codeFrameColumns (
String ( contents ) ,
{ start : { line : err.lineNumber , column : err.columnNumber } } ,
{ message : err.message , highlightCode : true }
)
2020-06-01 23:00:22 +02:00
throw new Error ( ` Failed to parse " ${ filePath } ": \ n ${ codeFrame } ` )
2020-05-18 18:07:08 +02:00
}
2020-03-27 11:20:13 +01:00
}
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 = {
2020-07-17 10:38:06 +02:00
[ key : string ] : string | string [ ]
2020-02-17 22:16:19 +01:00
}
2020-08-04 23:24:56 +02:00
export function attachReactRefresh (
webpackConfig : webpack.Configuration ,
targetLoader : webpack.RuleSetUseItem
) {
let injections = 0
const reactRefreshLoaderName = '@next/react-refresh-utils/loader'
const reactRefreshLoader = require . resolve ( reactRefreshLoaderName )
webpackConfig . module ? . rules . forEach ( ( rule ) = > {
const curr = rule . use
// When the user has configured `defaultLoaders.babel` for a input file:
if ( curr === targetLoader ) {
++ injections
rule . use = [ reactRefreshLoader , curr as webpack . RuleSetUseItem ]
} else if (
Array . isArray ( curr ) &&
curr . some ( ( r ) = > r === targetLoader ) &&
// Check if loader already exists:
! curr . some (
( r ) = > r === reactRefreshLoader || r === reactRefreshLoaderName
)
) {
++ injections
const idx = curr . findIndex ( ( r ) = > r === targetLoader )
// Clone to not mutate user input
rule . use = [ . . . curr ]
// inject / input: [other, babel] output: [other, refresh, babel]:
rule . use . splice ( idx , 0 , reactRefreshLoader )
}
} )
if ( injections ) {
Log . info (
` automatically enabled Fast Refresh for ${ injections } custom loader ${
injections > 1 ? 's' : ''
} `
)
}
}
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 ,
2019-04-26 17:23:32 +02:00
target = 'server' ,
2020-07-09 13:39:12 +02:00
reactProductionProfiling = false ,
2019-04-26 17:23:32 +02:00
entrypoints ,
2020-08-13 14:39:36 +02:00
rewrites ,
2019-04-26 17:23:32 +02:00
} : {
buildId : string
2020-12-04 11:14:55 +01:00
config : NextConfig
2019-09-24 17:15:14 +02:00
dev? : boolean
isServer? : boolean
pagesDir : string
2019-04-26 17:23:32 +02:00
target? : string
2020-07-09 13:39:12 +02:00
reactProductionProfiling? : boolean
2019-04-26 17:23:32 +02:00
entrypoints : WebpackEntrypoints
2020-08-13 14:39:36 +02:00
rewrites : Rewrite [ ]
2019-04-26 17:23:32 +02:00
}
) : Promise < webpack.Configuration > {
2021-01-14 02:59:08 +01:00
initWebpack (
config . future ? . webpack5 ||
( config . future ? . webpack5 !== false &&
Number ( process . env . NEXT_WEBPACK5 ) > 0 )
)
2019-11-01 20:13:13 +01:00
let plugins : PluginMetaData [ ] = [ ]
let babelPresetPlugins : { dir : string ; config : any } [ ] = [ ]
2020-08-13 14:39:36 +02:00
const hasRewrites = rewrites . length > 0 || dev
2019-11-01 20:13:13 +01:00
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 ,
} )
}
}
}
2020-04-19 19:58:31 +02:00
2020-09-01 17:29:25 +02:00
const reactVersion = await getPackageVersion ( { cwd : dir , name : 'react' } )
const hasReactRefresh : boolean = dev && ! isServer
const hasJsxRuntime : boolean =
Boolean ( reactVersion ) &&
// 17.0.0-rc.0 had a breaking change not compatible with Next.js, but was
// fixed in rc.1.
semver . gte ( reactVersion ! , '17.0.0-rc.1' )
2020-04-19 19:58:31 +02:00
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 ,
2020-08-18 15:46:55 +02:00
// Webpack 5 has a built-in loader cache
2020-08-25 00:37:52 +02:00
cache : ! isWebpack5 ,
2019-11-01 20:13:13 +01:00
babelPresetPlugins ,
2019-12-03 22:08:49 +01:00
development : dev ,
2020-04-19 19:58:31 +02:00
hasReactRefresh ,
2020-09-01 17:29:25 +02:00
hasJsxRuntime ,
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
2020-05-18 21:24:37 +02: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' ? ';' : ':' )
2020-05-18 21:24:37 +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 ] :
2020-07-09 14:31:06 +02:00
` ./ ` +
path
. relative (
dir ,
path . join (
NEXT_PROJECT_ROOT_DIST_CLIENT ,
dev ? ` next-dev.js ` : 'next.js'
)
2019-04-26 17:23:32 +02:00
)
2020-07-09 14:31:06 +02:00
. replace ( /\\/g , '/' ) ,
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
2020-08-06 16:41:11 +02:00
let typeScriptPath : string | undefined
2019-05-09 04:51:23 +02:00
try {
2021-01-11 15:43:08 +01:00
typeScriptPath = require . resolve ( 'typescript' , { paths : [ 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
2020-03-19 17:34:24 +01:00
let jsConfig
// jsconfig is a subset of tsconfig
if ( useTypeScript ) {
2020-08-06 16:41:11 +02:00
const ts = ( await import ( typeScriptPath ! ) ) as typeof import ( 'typescript' )
2020-07-28 12:00:27 +02:00
const tsConfig = await getTypeScriptConfiguration ( ts , tsConfigPath )
jsConfig = { compilerOptions : tsConfig.options }
2020-03-19 17:34:24 +01:00
}
const jsConfigPath = path . join ( dir , 'jsconfig.json' )
if ( ! useTypeScript && ( await fileExists ( jsConfigPath ) ) ) {
2020-03-27 11:20:13 +01:00
jsConfig = parseJsonFile ( jsConfigPath )
2020-03-19 17:34:24 +01:00
}
let resolvedBaseUrl
if ( jsConfig ? . compilerOptions ? . baseUrl ) {
resolvedBaseUrl = path . resolve ( dir , jsConfig . compilerOptions . baseUrl )
}
2020-06-28 13:23:29 +02:00
function getReactProfilingInProduction() {
2020-07-09 13:39:12 +02:00
if ( reactProductionProfiling ) {
2020-06-28 13:23:29 +02:00
return {
'react-dom$' : 'react-dom/profiling' ,
'scheduler/tracing' : 'scheduler/tracing-profiling' ,
}
}
}
2020-08-13 14:39:36 +02:00
const clientResolveRewrites = require . resolve (
'next/dist/next-server/lib/router/utils/resolve-rewrites'
)
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
? [
'.js' ,
'.mjs' ,
2020-04-19 07:12:36 +02:00
. . . ( useTypeScript ? [ '.tsx' , '.ts' ] : [ ] ) ,
2019-04-26 18:12:40 +02:00
'.jsx' ,
'.json' ,
'.wasm' ,
]
: [
'.mjs' ,
'.js' ,
2020-04-19 07:12:36 +02:00
. . . ( useTypeScript ? [ '.tsx' , '.ts' ] : [ ] ) ,
2019-04-26 18:12:40 +02:00
'.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 : {
2020-08-21 20:50:24 +02:00
next : NEXT_PROJECT_ROOT ,
. . . ( isWebpack5 && ! isServer
? {
2020-08-10 11:45:10 +02:00
stream : require.resolve ( 'stream-browserify' ) ,
path : require.resolve ( 'path-browserify' ) ,
crypto : require.resolve ( 'crypto-browserify' ) ,
buffer : require.resolve ( 'buffer' ) ,
vm : require.resolve ( 'vm-browserify' ) ,
2020-08-21 20:50:24 +02:00
}
: undefined ) ,
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 ) ,
2020-06-28 13:23:29 +02:00
. . . getReactProfilingInProduction ( ) ,
2020-08-13 14:39:36 +02:00
[ clientResolveRewrites ] : hasRewrites
? clientResolveRewrites
: require . resolve ( 'next/dist/client/dev/noop.js' ) ,
2018-12-04 10:59:12 +01:00
} ,
2019-04-26 17:23:32 +02:00
mainFields : isServer ? [ 'main' , 'module' ] : [ 'browser' , 'module' , 'main' ] ,
2020-04-15 20:25:02 +02:00
plugins : isWebpack5
? // webpack 5+ has the PnP resolver built-in by default:
[ ]
2020-06-17 17:00:29 +02:00
: [ require ( 'pnp-webpack-plugin' ) ] ,
2018-08-14 00:09:05 +02:00
}
2020-04-26 21:16:43 +02:00
const terserOptions : any = {
2019-06-11 19:34:45 +02:00
parse : {
ecma : 8 ,
} ,
compress : {
ecma : 5 ,
warnings : false ,
// The following two options are known to break valid JavaScript code
comparisons : false ,
2020-05-27 23:51:11 +02:00
inline : 2 , // https://github.com/vercel/next.js/issues/7178#issuecomment-493048965
2019-06-11 19:34:45 +02:00
} ,
mangle : { safari10 : true } ,
output : {
ecma : 5 ,
safari10 : true ,
comments : false ,
// Fixes usage of Emoji and certain Regex
ascii_only : true ,
} ,
}
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 ,
2020-06-17 17:00:29 +02:00
// In webpack 5 vendors was renamed to defaultVendors
defaultVendors : false ,
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 ,
2020-06-17 17:00:29 +02:00
// In webpack 5 vendors was renamed to defaultVendors
defaultVendors : false ,
2019-08-08 19:14:33 +02:00
framework : {
2019-08-22 16:46:11 +02:00
chunks : 'all' ,
2020-07-16 01:33:41 +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.
2020-05-27 23:51:11 +02:00
// https://github.com/vercel/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 } ) )
}
2020-07-16 01:33:41 +02:00
return hash . digest ( 'hex' ) . substring ( 0 , 8 )
2019-08-08 19:14:33 +02:00
} ,
priority : 30 ,
minChunks : 1 ,
reuseExistingChunk : true ,
} ,
commons : {
2020-07-16 01:33:41 +02:00
name : 'commons' ,
2019-08-08 19:14:33 +02:00
minChunks : totalPages ,
priority : 20 ,
} ,
shared : {
name ( module , chunks ) {
2020-02-04 20:22:26 +01:00
return (
2020-07-16 01:33:41 +02:00
crypto
2020-02-04 20:22:26 +01:00
. createHash ( 'sha1' )
. update (
chunks . reduce (
( acc : string , chunk : webpack.compilation.Chunk ) = > {
return acc + chunk . name
} ,
''
)
2019-08-08 19:14:33 +02:00
)
2020-07-17 10:38:06 +02:00
. digest ( 'hex' ) + ( isModuleCSS ( module ) ? '_CSS' : '' )
2020-02-04 20:22:26 +01:00
)
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 {
2020-06-02 16:13:11 +02:00
splitChunksConfig = splitChunksConfigs . prodGranular
2019-07-29 18:19:31 +02:00
}
2020-11-18 19:30:00 +01:00
const crossOrigin = config . crossOrigin
2019-07-25 04:16:32 +02:00
2020-04-25 21:00:41 +02:00
let customAppFile : string | null = await findPageFile (
pagesDir ,
'/_app' ,
config . pageExtensions
)
2019-09-17 22:05:20 +02:00
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 || [ ]
) ,
} ,
2020-05-20 08:40:23 +02:00
GranularChunksConformanceCheck : {
enabled : true ,
} ,
2020-03-02 22:53:18 +01:00
} ,
config . conformance
)
2020-04-07 21:13:01 +02:00
2020-08-03 14:26:23 +02:00
function handleExternals ( context : any , request : any , callback : any ) {
if ( request === 'next' ) {
return callback ( undefined , ` commonjs ${ request } ` )
}
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +02:00
const notExternalModules = [
'next/app' ,
'next/document' ,
'next/link' ,
2020-10-14 11:57:10 +02:00
'next/image' ,
2020-08-03 14:26:23 +02:00
'next/error' ,
'string-hash' ,
'next/constants' ,
]
if ( notExternalModules . indexOf ( request ) !== - 1 ) {
return callback ( )
}
2019-10-30 04:36:22 +01:00
2020-08-03 14:26:23 +02:00
// We need to externalize internal requests for files intended to
// not be bundled.
const isLocal : boolean =
request . startsWith ( '.' ) ||
// Always check for unix-style path, as webpack sometimes
// normalizes as posix.
path . posix . isAbsolute ( request ) ||
// When on Windows, we also want to check for Windows-specific
// absolute paths.
( process . platform === 'win32' && path . win32 . isAbsolute ( request ) )
const isLikelyNextExternal =
isLocal && /[/\\]next-server[/\\]/ . test ( request )
// 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.
if ( isLocal && ! isLikelyNextExternal ) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +02:00
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
let res : string
try {
2021-01-11 15:43:08 +01:00
res = require . resolve ( request , { paths : [ context ] } )
2020-08-03 14:26:23 +02:00
} catch ( err ) {
// 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).
return callback ( )
}
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +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.
if ( ! res ) {
return callback ( )
}
2020-04-14 09:50:39 +02:00
2020-08-03 14:26:23 +02:00
let isNextExternal : boolean = false
if ( isLocal ) {
// we need to process next-server/lib/router/router so that
// the DefinePlugin can inject process.env values
isNextExternal = /next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/ . test (
res
)
2019-09-14 22:12:25 +02:00
2020-08-03 14:26:23 +02:00
if ( ! isNextExternal ) {
return callback ( )
}
}
2020-04-11 12:36:06 +02:00
2020-08-03 14:26:23 +02:00
// `isNextExternal` special cases Next.js' internal requires that
// should not be bundled. We need to skip the base resolve routine
// to prevent it from being bundled (assumes Next.js version cannot
// mismatch).
if ( ! isNextExternal ) {
// 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).
let baseRes : string | null
try {
2021-01-11 15:43:08 +01:00
baseRes = require . resolve ( request , { paths : [ dir ] } )
2020-08-03 14:26:23 +02:00
} catch ( err ) {
baseRes = null
}
2019-09-14 22:12:25 +02:00
2020-08-03 14:26:23 +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.
2020-10-14 13:36:59 +02:00
if (
! baseRes ||
( baseRes !== res &&
// if res and baseRes are symlinks they could point to the the same file
realpathSync ( baseRes ) !== realpathSync ( res ) )
) {
2020-08-03 14:26:23 +02:00
return callback ( )
}
}
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +02:00
// Default pages have to be transpiled
if (
! res . match ( /next[/\\]dist[/\\]next-server[/\\]/ ) &&
( res . match ( /[/\\]next[/\\]dist[/\\]/ ) ||
// This is the @babel/plugin-transform-runtime "helpers: true" option
res . match ( /node_modules[/\\]@babel[/\\]runtime[/\\]/ ) )
) {
return callback ( )
}
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +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 ( )
}
2020-04-11 12:36:06 +02:00
2020-08-03 14:26:23 +02:00
// Anything else that is standard JavaScript within `node_modules`
// can be externalized.
if ( isNextExternal || res . match ( /node_modules[/\\].*\.js$/ ) ) {
const externalRequest = isNextExternal
? // Generate Next.js external import
path . posix . join (
'next' ,
'dist' ,
path
. relative (
// Root of Next.js package:
path . join ( __dirname , '..' ) ,
res
)
// Windows path normalization
. replace ( /\\/g , '/' )
)
: request
2019-03-07 17:40:08 +01:00
2020-08-03 14:26:23 +02:00
return callback ( undefined , ` commonjs ${ externalRequest } ` )
}
// Default behavior: bundle the code!
callback ( )
}
2020-12-29 17:12:36 +01:00
const emacsLockfilePattern = '**/.#*'
2020-08-03 14:26:23 +02:00
let webpackConfig : webpack.Configuration = {
externals : ! isServer
? // make sure importing "next" is handled gracefully for client
// bundles in case a user imported types and it wasn't removed
// TODO: should we warn/error for this instead?
[ 'next' ]
: ! isServerless
? [
isWebpack5
? ( { context , request } , callback ) = >
handleExternals ( context , request , callback )
: ( context , request , callback ) = >
handleExternals ( context , request , 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
2020-12-01 19:02:07 +01:00
// Mark this as external if not enabled so it doesn't cause a
// webpack error from being missing
. . . ( config . experimental . optimizeCss ? [ ] : [ 'critters' ] ) ,
2019-04-26 17:23:32 +02:00
] ,
2019-08-20 17:07:57 +02:00
optimization : {
2020-08-03 14:57:17 +02:00
// Webpack 5 uses a new property for the same functionality
. . . ( isWebpack5 ? { emitOnErrors : ! dev } : { noEmitOnErrors : dev } ) ,
2019-08-20 17:07:57 +02:00
checkWasmTypes : false ,
nodeEnv : false ,
splitChunks : isServer ? false : splitChunksConfig ,
runtimeChunk : isServer
2020-07-01 17:34:00 +02:00
? isWebpack5 && ! isLikeServerless
? { name : 'webpack-runtime' }
: undefined
2019-08-20 17:07:57 +02:00
: { 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 ( {
2020-12-12 21:28:53 +01:00
cacheDir : path.join ( distDir , 'cache' , 'next-minifier' ) ,
parallel : config.experimental.cpus ,
2019-08-20 17:07:57 +02:00
terserOptions ,
} ) ,
2019-09-17 22:05:20 +02:00
// Minify CSS
2020-04-25 21:00:41 +02:00
new CssMinimizerPlugin ( {
postcssOptions : {
map : {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline : false ,
// `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
} ,
2020-04-25 21:00:41 +02:00
} ,
} ) ,
] ,
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
}
} ,
2020-06-26 06:26:09 +02:00
watchOptions : {
2020-12-29 17:12:36 +01:00
ignored : [
'**/.git/**' ,
'**/node_modules/**' ,
'**/.next/**' ,
// can be removed after https://github.com/paulmillr/chokidar/issues/955 is released
emacsLockfilePattern ,
] ,
2020-06-26 06:26:09 +02:00
} ,
2016-10-14 17:05:08 +02:00
output : {
[Fix] `webpack@5.0.0-beta.30`: Invalid configuration (#17045)
Earlier today #17038 was merged which I opened to fix a problem when using `webpack@5.0.0-beta.30` with Next.js using the new Webpack 5 support. In that PR, the only change was the renaming of a configuration key. I later discovered that the change on the Webpack side was different than I initially thought, and this meant that the fix I submittted to Next.js didn't work.
This PR intends to fix the remaining problems. Webpack 5 now accepts a `environment` key that can be used to configure the target output. Previously, this was known as `ecmaVersion` and accepted a number. Now, `environment` accepts a configuration object with individual options. I've configured this in such a way where it resembles an ES5 environment:
```js
environment: {
arrowFunction: false,
bigIntLiteral: false,
const: false,
destructuring: false,
dynamicImport: false,
forOf: false,
module: false,
}
```
2020-09-14 15:21:17 +02:00
. . . ( isWebpack5
? {
environment : {
arrowFunction : false ,
bigIntLiteral : false ,
const : false ,
destructuring : false ,
dynamicImport : false ,
forOf : false ,
module : false ,
} ,
}
: { } ) ,
2018-07-24 11:24:40 +02:00
path : outputPath ,
2020-06-22 23:12:36 +02:00
// On the server we don't use the chunkhash
2020-07-17 10:38:06 +02:00
filename : isServer
? '[name].js'
: ` static/chunks/[name] ${ dev ? '' : '-[chunkhash]' } .js ` ,
2020-06-26 06:26:09 +02:00
library : isServer ? undefined : '_N_E' ,
libraryTarget : isServer ? 'commonjs2' : 'assign' ,
2020-04-15 20:25:02 +02:00
hotUpdateChunkFilename : isWebpack5
? 'static/webpack/[id].[fullhash].hot-update.js'
: 'static/webpack/[id].[hash].hot-update.js' ,
hotUpdateMainFilename : isWebpack5
? 'static/webpack/[fullhash].hot-update.json'
: 'static/webpack/[hash].hot-update.json' ,
2018-07-24 11:24:40 +02:00
// 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-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
] ,
2020-06-17 17:00:29 +02:00
plugins : isWebpack5 ? [ ] : [ require ( 'pnp-webpack-plugin' ) ] ,
2016-10-14 17:05:08 +02:00
} ,
module : {
2018-01-03 13:43:48 +01:00
rules : [
2020-09-15 05:27:43 +02:00
. . . ( isWebpack5
? [
// TODO: FIXME: do NOT webpack 5 support with this
// x-ref: https://github.com/webpack/webpack/issues/11467
{
test : /\.m?js/ ,
resolve : {
fullySpecified : false ,
} ,
} as any ,
]
: [ ] ) ,
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 ] ,
2020-06-01 23:00:22 +02:00
exclude : ( excludePath : string ) = > {
if ( babelIncludeRegexes . some ( ( r ) = > r . test ( excludePath ) ) ) {
2019-05-01 19:16:52 +02:00
return false
}
2020-06-01 23:00:22 +02:00
return /node_modules/ . test ( excludePath )
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.
{
2020-03-30 03:25:10 +02:00
loader : 'next/dist/compiled/cache-loader' ,
2019-12-24 16:58:50 +01:00
options : {
cacheContext : dir ,
cacheDirectory : path.join ( dir , '.next' , 'cache' , 'webpack' ) ,
2020-11-18 19:30:00 +01:00
cacheIdentifier : ` webpack ${ isServer ? '-server' : '' } ` ,
2019-12-24 16:58:50 +01:00
} ,
} ,
{
2020-03-30 01:20:35 +02:00
loader : require.resolve ( 'next/dist/compiled/thread-loader' ) ,
2019-12-24 16:58:50 +01:00
options : {
workers : 2 ,
workerParallelJobs : Infinity ,
} ,
} ,
2020-04-19 19:58:31 +02:00
hasReactRefresh
? require . resolve ( '@next/react-refresh-utils/loader' )
: '' ,
2020-05-10 00:37:04 +02:00
defaultLoaders . babel ,
2020-04-19 19:58:31 +02:00
] . filter ( Boolean )
: hasReactRefresh
? [
require . resolve ( '@next/react-refresh-utils/loader' ) ,
2020-05-10 00:37:04 +02:00
defaultLoaders . babel ,
2019-12-24 16:58:50 +01:00
]
: 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 : [
2021-01-14 02:59:08 +01:00
hasReactRefresh && new ReactRefreshWebpackPlugin ( webpack ) ,
2021-01-11 13:31:31 +01:00
// Makes sure `Buffer` and `process` are polyfilled in client-side bundles (same behavior as webpack 4)
2020-07-28 11:33:21 +02:00
isWebpack5 &&
! isServer &&
2021-01-11 13:31:31 +01:00
new webpack . ProvidePlugin ( {
Buffer : [ require . resolve ( 'buffer' ) , 'Buffer' ] ,
process : [ require . resolve ( 'process' ) ] ,
} ) ,
2018-07-24 11:24:40 +02:00
// This plugin makes sure `output.filename` is used for entry chunks
2020-06-23 17:47:50 +02:00
! isWebpack5 && new ChunkNamesPlugin ( ) ,
2019-02-15 17:49:40 +01:00
new webpack . DefinePlugin ( {
2020-04-17 16:28:17 +02:00
. . . Object . keys ( process . env ) . reduce (
( prev : { [ key : string ] : string } , key : string ) = > {
if ( key . startsWith ( 'NEXT_PUBLIC_' ) ) {
prev [ ` process.env. ${ key } ` ] = JSON . stringify ( process . env [ key ] ! )
}
return prev
} ,
{ }
) ,
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 (
2020-05-27 23:51:11 +02:00
` The key " ${ key } " under "env" in next.config.js is not allowed. https://err.sh/vercel/next.js/env-key-not-allowed `
2019-04-26 17:23:32 +02:00
)
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
} , { } ) ,
2021-01-02 01:36:16 +01:00
// TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV' : JSON . stringify (
dev ? 'development' : 'production'
) ,
2020-06-07 01:00:03 +02:00
'process.env.__NEXT_CROSS_ORIGIN' : 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 ) ,
}
: { } ) ,
2020-06-23 13:38:49 +02:00
'process.env.__NEXT_TRAILING_SLASH' : JSON . stringify (
2020-07-20 18:16:59 +02:00
config . trailingSlash
2020-06-23 13:38:49 +02:00
) ,
2019-09-15 23:18:11 +02:00
'process.env.__NEXT_BUILD_INDICATOR' : JSON . stringify (
config . devIndicators . buildActivity
) ,
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
) ,
2020-12-21 20:26:00 +01:00
'process.env.__NEXT_OPTIMIZE_FONTS' : JSON . stringify (
config . experimental . optimizeFonts && ! dev
) ,
2020-08-05 19:49:44 +02:00
'process.env.__NEXT_OPTIMIZE_IMAGES' : JSON . stringify (
config . experimental . optimizeImages
) ,
2020-12-01 19:02:07 +01:00
'process.env.__NEXT_OPTIMIZE_CSS' : JSON . stringify (
! ! config . experimental . optimizeCss && ! dev
) ,
2020-07-06 16:27:45 +02:00
'process.env.__NEXT_SCROLL_RESTORATION' : JSON . stringify (
config . experimental . scrollRestoration
) ,
2020-10-20 18:43:24 +02:00
'process.env.__NEXT_IMAGE_OPTS' : JSON . stringify ( {
2020-10-26 21:07:52 +01:00
deviceSizes : config.images.deviceSizes ,
2020-10-27 14:19:23 +01:00
imageSizes : config.images.imageSizes ,
2020-10-20 18:43:24 +02:00
path : config.images.path ,
loader : config.images.loader ,
2020-10-25 06:22:47 +01:00
. . . ( dev
? {
// pass domains in development to allow validating on the client
domains : config.images.domains ,
}
: { } ) ,
2020-10-20 18:43:24 +02:00
} ) ,
2020-06-18 12:10:20 +02:00
'process.env.__NEXT_ROUTER_BASEPATH' : JSON . stringify ( config . basePath ) ,
2020-08-13 14:39:36 +02:00
'process.env.__NEXT_HAS_REWRITES' : JSON . stringify ( hasRewrites ) ,
2020-10-27 16:30:34 +01:00
'process.env.__NEXT_I18N_SUPPORT' : JSON . stringify ( ! ! config . i18n ) ,
2020-12-04 11:14:55 +01:00
'process.env.__NEXT_I18N_DOMAINS' : JSON . stringify ( config . i18n ? . domains ) ,
2020-10-27 04:36:31 +01:00
'process.env.__NEXT_ANALYTICS_ID' : JSON . stringify ( config . analyticsId ) ,
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 ) ,
2020-04-15 08:42:37 +02:00
// stub process.env with proxy to warn a missing value is
2020-04-20 20:25:36 +02:00
// being accessed in development mode
2021-01-02 01:36:16 +01:00
. . . ( config . experimental . pageEnv && dev
2020-04-15 08:42:37 +02:00
? {
2020-04-20 20:25:36 +02:00
'process.env' : `
2020-04-15 08:42:37 +02:00
new Proxy ( $ { isServer ? 'process.env' : '{}' } , {
get ( target , prop ) {
if ( typeof target [ prop ] === 'undefined' ) {
console . warn ( \ ` An environment variable ( \ ${ prop } ) that was not provided in the environment was accessed. \ nSee more info here: https://err.sh/next.js/missing-env-value \` )
}
return target [ prop ]
}
} )
` ,
}
: { } ) ,
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 &&
2020-06-17 17:00:29 +02:00
new webpack . IgnorePlugin ( {
resourceRegExp : /^\.\/locale$/ ,
contextRegExp : /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' )
2020-06-26 06:26:09 +02:00
const devPlugins = [ new NextJsRequireCacheHotReloader ( ) ]
2019-03-10 05:27:33 +01:00
2020-06-26 06:26:09 +02:00
if ( ! isServer ) {
2019-04-26 17:23:32 +02:00
devPlugins . push ( new webpack . HotModuleReplacementPlugin ( ) )
}
2019-03-10 05:27:33 +01:00
2019-04-26 17:23:32 +02:00
return devPlugins
} ) ( )
: [ ] ) ,
2020-04-15 20:25:02 +02:00
// Webpack 5 no longer requires this plugin in production:
! isWebpack5 && ! dev && new webpack . HashedModuleIdsPlugin ( ) ,
2019-04-26 17:23:32 +02:00
! dev &&
new webpack . IgnorePlugin ( {
2020-04-15 20:25:02 +02:00
resourceRegExp : /react-is/ ,
contextRegExp : /(next-server|next)[\\/]dist[\\/]/ ,
2019-04-26 17:23:32 +02:00
} ) ,
2019-08-30 13:26:30 +02:00
isServerless && isServer && new ServerlessPlugin ( ) ,
2019-08-06 00:26:20 +02:00
isServer && new PagesManifestPlugin ( isLikeServerless ) ,
2020-07-01 17:34:00 +02:00
! isWebpack5 &&
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 ,
2020-08-13 14:39:36 +02:00
rewrites ,
2019-08-08 19:14:33 +02:00
} ) ,
2021-01-10 02:12:13 +01:00
new ProfilingPlugin ( ) ,
2020-12-21 20:26:00 +01:00
config . experimental . optimizeFonts &&
! dev &&
2020-07-28 12:19:28 +02:00
isServer &&
2020-07-30 01:19:32 +02:00
( function ( ) {
const {
FontStylesheetGatheringPlugin ,
} = require ( './webpack/plugins/font-stylesheet-gathering-plugin' )
return new FontStylesheetGatheringPlugin ( )
} ) ( ) ,
2020-01-23 22:09:12 +01:00
config . experimental . conformance &&
2020-07-16 01:33:41 +02:00
! isWebpack5 &&
2020-01-23 22:09:12 +01:00
! 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 ,
} ) ,
2020-05-20 08:40:23 +02:00
! isServer &&
conformanceConfig . GranularChunksConformanceCheck . enabled &&
new GranularChunksConformanceCheck (
splitChunksConfigs . prodGranular
) ,
2020-03-02 22:53:18 +01:00
] . filter ( Boolean ) ,
2020-01-23 22:09:12 +01:00
} ) ,
2020-05-13 17:43:41 +02:00
new WellKnownErrorsPlugin ( ) ,
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 )
}
2020-04-17 16:28:17 +02:00
if ( jsConfig ? . compilerOptions ? . paths && resolvedBaseUrl ) {
2020-04-24 15:50:36 +02:00
webpackConfig . resolve ? . plugins ? . unshift (
2020-03-23 15:45:51 +01:00
new JsConfigPathsPlugin ( jsConfig . compilerOptions . paths , resolvedBaseUrl )
)
}
2020-04-15 20:25:02 +02:00
if ( isWebpack5 ) {
2020-08-25 00:37:52 +02:00
// futureEmitAssets is on by default in webpack 5
2020-04-15 20:25:02 +02:00
delete webpackConfig . output ? . futureEmitAssets
2020-08-25 00:37:52 +02:00
// webpack 5 no longer polyfills Node.js modules:
2020-04-15 20:25:02 +02:00
if ( webpackConfig . node ) delete webpackConfig . node . setImmediate
2020-07-09 14:31:06 +02:00
if ( dev ) {
if ( ! webpackConfig . optimization ) {
webpackConfig . optimization = { }
}
2020-12-28 20:18:51 +01:00
webpackConfig . optimization . providedExports = false
2020-07-09 14:31:06 +02:00
webpackConfig . optimization . usedExports = false
}
2020-08-18 15:46:55 +02:00
2020-12-04 15:08:02 +01:00
const nextPublicVariables = Object . keys ( process . env )
. reduce ( ( acc : string [ ] , key : string ) = > {
2020-08-25 00:37:52 +02:00
if ( key . startsWith ( 'NEXT_PUBLIC_' ) ) {
2020-12-04 15:08:02 +01:00
return [ . . . acc , ` ${ key } = ${ process . env [ key ] } ` ]
2020-08-25 00:37:52 +02:00
}
2020-12-04 15:08:02 +01:00
return acc
} , [ ] )
. join ( '|' )
2020-08-25 00:37:52 +02:00
const nextEnvVariables = Object . keys ( config . env ) . reduce (
( prev : string , key : string ) = > {
return ` ${ prev } | ${ key } = ${ config . env [ key ] } `
} ,
''
)
2020-08-24 03:37:48 +02:00
2020-08-25 00:37:52 +02:00
const configVars = JSON . stringify ( {
crossOrigin : config.crossOrigin ,
pageExtensions : config.pageExtensions ,
trailingSlash : config.trailingSlash ,
buildActivity : config.devIndicators.buildActivity ,
plugins : config.experimental.plugins ,
reactStrictMode : config.reactStrictMode ,
reactMode : config.experimental.reactMode ,
2020-12-21 20:26:00 +01:00
optimizeFonts : config.experimental.optimizeFonts ,
2020-08-25 00:37:52 +02:00
optimizeImages : config.experimental.optimizeImages ,
scrollRestoration : config.experimental.scrollRestoration ,
basePath : config.basePath ,
pageEnv : config.experimental.pageEnv ,
excludeDefaultMomentLocales : config.future.excludeDefaultMomentLocales ,
assetPrefix : config.assetPrefix ,
target ,
reactProductionProfiling ,
} )
const cache : any = {
type : 'filesystem' ,
// Includes:
// - Next.js version
// - NEXT_PUBLIC_ variable values (they affect caching) TODO: make this module usage only
// - next.config.js `env` key
// - next.config.js keys that affect compilation
version : ` ${ process . env . __NEXT_VERSION } | ${ nextPublicVariables } | ${ nextEnvVariables } | ${ configVars } ` ,
cacheDirectory : path.join ( dir , '.next' , 'cache' , 'webpack' ) ,
}
2020-08-24 03:37:48 +02:00
2020-08-25 00:37:52 +02:00
// Adds `next.config.js` as a buildDependency when custom webpack config is provided
if ( config . webpack && config . configFile ) {
cache . buildDependencies = {
config : [ config . configFile ] ,
2020-08-24 03:37:48 +02:00
}
2020-08-25 00:37:52 +02:00
}
2020-08-24 03:37:48 +02:00
2020-08-25 00:37:52 +02:00
webpackConfig . cache = cache
2020-08-24 03:37:48 +02:00
2020-08-25 00:37:52 +02:00
// @ts-ignore TODO: remove ignore when webpack 5 is stable
webpackConfig . optimization . realContentHash = false
2020-04-15 20:25:02 +02:00
}
2019-12-09 21:08:15 +01:00
webpackConfig = await buildConfiguration ( webpackConfig , {
rootDirectory : dir ,
customAppFile ,
isDevelopment : dev ,
isServer ,
2020-01-03 18:45:04 +01:00
assetPrefix : config.assetPrefix || '' ,
2020-05-11 04:11:48 +02:00
sassOptions : config.sassOptions ,
2021-01-01 21:30:50 +01:00
productionBrowserSourceMaps : config.productionBrowserSourceMaps ,
2021-01-11 18:19:56 +01:00
future : config.future ,
2019-12-09 21:08:15 +01:00
} )
2020-06-24 06:15:57 +02:00
let originalDevtool = webpackConfig . devtool
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-12-01 22:58:52 +01:00
if ( ! webpackConfig ) {
throw new Error (
'Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js.\n' +
'See more info here https://err.sh/next.js/undefined-webpack-config'
)
}
2020-06-24 06:15:57 +02:00
if ( dev && originalDevtool !== webpackConfig . devtool ) {
webpackConfig . devtool = originalDevtool
devtoolRevertWarning ( originalDevtool )
}
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 (
2020-05-27 23:51:11 +02:00
'> Promise returned in next config. https://err.sh/vercel/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
2020-06-26 06:26:09 +02:00
// Backwards compat with webpack-dev-middleware options object
if ( typeof config . webpackDevMiddleware === 'function' ) {
const options = config . webpackDevMiddleware ( {
watchOptions : webpackConfig.watchOptions ,
} )
if ( options . watchOptions ) {
webpackConfig . watchOptions = options . watchOptions
}
}
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' ,
]
2020-05-18 21:24:37 +02:00
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 (
2020-05-18 21:24:37 +02:00
fileNames . some ( ( input ) = > {
2020-01-10 22:07:06 +01:00
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
}
2020-04-25 21:00:41 +02:00
const hasUserCssConfig =
webpackConfig . module ? . rules . some (
2020-05-18 21:24:37 +02:00
( rule ) = > canMatchCss ( rule . test ) || canMatchCss ( rule . include )
2020-04-25 21:00:41 +02:00
) ? ? false
2020-03-10 19:29:40 +01:00
2020-04-25 21:00:41 +02:00
if ( hasUserCssConfig ) {
// 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'
)
}
if ( webpackConfig . module ? . rules . length ) {
// Remove default CSS Loader
webpackConfig . module . rules = webpackConfig . module . rules . filter (
2020-05-18 21:24:37 +02:00
( r ) = >
2020-04-25 21:00:41 +02:00
! (
typeof r . oneOf ? . [ 0 ] ? . options === 'object' &&
r . oneOf [ 0 ] . options . __next_css_remove === true
)
)
2019-12-13 21:23:28 +01:00
}
2020-04-25 21:00:41 +02:00
if ( webpackConfig . plugins ? . length ) {
// Disable CSS Extraction Plugin
webpackConfig . plugins = webpackConfig . plugins . filter (
2020-05-18 21:24:37 +02:00
( p ) = > ( p as any ) . __next_css_remove !== true
2020-04-25 21:00:41 +02:00
)
}
if ( webpackConfig . optimization ? . minimizer ? . length ) {
// Disable CSS Minifier
webpackConfig . optimization . minimizer = webpackConfig . optimization . minimizer . filter (
2020-05-18 21:24:37 +02:00
( e ) = > ( e as any ) . __next_css_remove !== true
2020-04-25 21:00:41 +02:00
)
}
2021-01-11 18:19:56 +01:00
} else if ( ! config . future . strictPostcssConfiguration ) {
2020-04-25 21:00:41 +02:00
await __overrideCssConfiguration ( dir , ! dev , webpackConfig )
2019-12-13 21:23:28 +01:00
}
2020-08-04 23:24:56 +02:00
// Inject missing React Refresh loaders so that development mode is fast:
if ( hasReactRefresh ) {
attachReactRefresh ( webpackConfig , defaultLoaders . babel )
}
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 ) ) {
2020-05-18 21:24:37 +02:00
; [ ] . forEach . call ( webpackConfig . module . rules , function (
2019-10-03 16:08:49 +02:00
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
}
2020-05-18 21:24:37 +02:00
; [ ] . forEach . call ( rule . use , function ( use : webpack.RuleSetUseItem ) {
2019-10-03 16:08:49 +02:00
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.
2021-01-11 15:43:08 +01:00
const correctNextCss = require . resolve ( '@zeit/next-css' , {
paths : [
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'
: isStylus
? '@zeit/next-stylus'
: '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.
2021-01-11 15:43:08 +01:00
const correctCssLoader = require . resolve ( use . loader , {
paths : [ 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 ) {
2020-07-17 10:38:06 +02:00
const originalFile = clientEntries [
CLIENT_STATIC_FILES_RUNTIME_MAIN
] as string
2020-07-20 04:16:50 +02:00
entry [ CLIENT_STATIC_FILES_RUNTIME_MAIN ] = [
. . . entry [ 'main.js' ] ,
originalFile ,
]
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
}