Unverified Commit e1502bc9 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable webpack5 for all apps (#25639)

* Enable webpack 5 by default for all apps

Still provides a way to opt-out using `webpack5: false` in next.config.js. Also throws an error for `future.webpack5`.

* Update tests

* Update test to run on webpack 4 instead of webpack 5

* disable webpack5 for legacy tests

* Fix stats-config for webpack4

* update tests

* update size for webpack4 test

* move basic suite first

* update basic test

* Add logs

* remove outdated testFutureDependencies job
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 069f7e82
...@@ -156,15 +156,15 @@ jobs: ...@@ -156,15 +156,15 @@ jobs:
steps: steps:
- run: exit 0 - run: exit 0
testFutureDependencies: testLegacyWebpack:
name: Webpack 5 (Basic, Production, Acceptance) name: Webpack 4 (Basic, Production, Acceptance)
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: build needs: build
env: env:
NEXT_TELEMETRY_DISABLED: 1 NEXT_TELEMETRY_DISABLED: 1
NEXT_TEST_JOB: 1 NEXT_TEST_JOB: 1
HEADLESS: true HEADLESS: true
NEXT_PRIVATE_TEST_WEBPACK5_MODE: 1 NEXT_PRIVATE_TEST_WEBPACK4_MODE: 1
steps: steps:
- uses: actions/cache@v2 - uses: actions/cache@v2
...@@ -174,37 +174,9 @@ jobs: ...@@ -174,37 +174,9 @@ jobs:
path: ./* path: ./*
key: ${{ github.sha }} key: ${{ github.sha }}
- run: xvfb-run node run-tests.js test/integration/{fallback-modules,link-ref,production,basic,async-modules,font-optimization,ssr-ctx}/test/index.test.js test/acceptance/*.test.js - run: xvfb-run node run-tests.js test/integration/{basic,fallback-modules,link-ref,production,async-modules,font-optimization,ssr-ctx}/test/index.test.js test/acceptance/*.test.js
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
testLegacyWebpack:
name: Webpack 4 (Basic, Production, Acceptance)
runs-on: ubuntu-latest
env:
NEXT_TELEMETRY_DISABLED: 1
NEXT_TEST_JOB: 1
HEADLESS: true
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 25
- run: echo ::set-output name=DOCS_CHANGE::$(node skip-docs-change.js echo 'not-docs-only-change')
id: docs-change
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
- run: yarn install --check-files
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
- run: yarn list react react-dom
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
- run: xvfb-run node run-tests.js test/integration/{link-ref,production,basic,async-modules,font-optimization,ssr-ctx,worker-loader}/test/index.test.js test/acceptance/*.test.js
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
testFirefox: testFirefox:
name: Test Firefox (production) name: Test Firefox (production)
runs-on: ubuntu-latest runs-on: ubuntu-latest
......
# `future.webpack5` has been moved to `webpack5`
#### Why This Error Occurred
The `future.webpack5` option has been moved to `webpack5` in `next.config.js`.
#### Possible Ways to Fix It
If you had the value `true` you can removed the option as webpack 5 is now the default for all Next.js apps unless opted out.
If you had he value `false` you can update `next.config.js`:
Change `future.webpack5` to `webpack5`.
Current `next.config.js`:
```js
// next.config.js
module.exports = {
future: {
webpack5: false,
},
}
```
Updated `next.config.js`:
```js
// next.config.js
module.exports = {
webpack5: false,
}
```
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
#### Why This Message Occurred #### Why This Message Occurred
Next.js will soon adopt webpack 5 as the default for compilation. We've spent a lot of effort into ensuring the transition from webpack 4 to 5 will be as smooth as possible. For example Next.js now comes with both webpack 4 and 5 allowing you to adopt webpack 5 by adding a flag to your `next.config.js`: Next.js has adopted webpack 5 as the default for compilation. We've spent a lot of effort into ensuring the transition from webpack 4 to 5 will be as smooth as possible. For example Next.js now comes with both webpack 4 and 5 allowing you to adopt webpack 5 by adding a flag to your `next.config.js`:
```js ```js
module.exports = { module.exports = {
future: { // Webpack 5 is enabled by default
webpack5: true, // You can still use webpack 4 while upgrading to the latest version of Next.js by adding the "webpack5: false" flag
}, webpack5: false,
} }
``` ```
Adopting webpack 5 in your application has many benefits, notably: Using webpack 5 in your application has many benefits, notably:
- Improved Disk Caching: `next build` is significantly faster on subsequent builds - Improved Disk Caching: `next build` is significantly faster on subsequent builds
- Improved Fast Refresh: Fast Refresh work is prioritized - Improved Fast Refresh: Fast Refresh work is prioritized
...@@ -22,11 +22,13 @@ Adopting webpack 5 in your application has many benefits, notably: ...@@ -22,11 +22,13 @@ Adopting webpack 5 in your application has many benefits, notably:
- Support for web workers using `new Worker(new URL("worker.js", import.meta.url))` - Support for web workers using `new Worker(new URL("worker.js", import.meta.url))`
- Support for `exports`/`imports` field in `package.json` - Support for `exports`/`imports` field in `package.json`
In upcoming releases we'll gradually roll out webpack 5 to applications that are compatible with webpack 5: In the past releases we have gradually rolled out webpack 5 to Next.js applications:
- In the next minor version we'll automatically opt-in applications without custom webpack configuration in `next.config.js` - In Next.js 10.2 we automatically opted-in applications without custom webpack configuration in `next.config.js`
- In the next minor version we'll automatically opt-in applications that do not have a `next.config.js` - In Next.js 10.2 we automatically opted-in applications that do not have a `next.config.js`
- In the next major version we'll enable webpack 5 by default. You'll still be able to opt-out and use webpack 4 to help with backwards compatibility - In Next.js 11 webpack 5 was enabled by default for all applications. You can still opt-out and use webpack 4 to help with backwards compatibility using `webpack5: false` in `next.config.js`
In the next major version webpack 4 support will be removed.
#### Custom webpack configuration #### Custom webpack configuration
......
...@@ -27,13 +27,16 @@ export type NextConfig = { [key: string]: any } & { ...@@ -27,13 +27,16 @@ export type NextConfig = { [key: string]: any } & {
} }
> >
redirects?: () => Promise<Redirect[]> redirects?: () => Promise<Redirect[]>
trailingSlash?: boolean trailingSlash?: boolean
webpack5?: false
future: { future: {
/**
* @deprecated this options was moved to the top level
*/
webpack5?: false
strictPostcssConfiguration?: boolean strictPostcssConfiguration?: boolean
excludeDefaultMomentLocales?: boolean excludeDefaultMomentLocales?: boolean
webpack5?: boolean
} }
experimental: { experimental: {
cpus?: number cpus?: number
...@@ -112,10 +115,11 @@ export const defaultConfig: NextConfig = { ...@@ -112,10 +115,11 @@ export const defaultConfig: NextConfig = {
disableOptimizedLoading: true, disableOptimizedLoading: true,
gzipSize: true, gzipSize: true,
}, },
webpack5:
Number(process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE) > 0 ? false : undefined,
future: { future: {
strictPostcssConfiguration: false, strictPostcssConfiguration: false,
excludeDefaultMomentLocales: false, excludeDefaultMomentLocales: false,
webpack5: Number(process.env.NEXT_PRIVATE_TEST_WEBPACK5_MODE) > 0,
}, },
serverRuntimeConfig: {}, serverRuntimeConfig: {},
publicRuntimeConfig: {}, publicRuntimeConfig: {},
......
...@@ -22,11 +22,9 @@ export function install(useWebpack5: boolean) { ...@@ -22,11 +22,9 @@ export function install(useWebpack5: boolean) {
export type CheckReasons = export type CheckReasons =
| 'test-mode' | 'test-mode'
| 'no-config' | 'default'
| 'flag-disabled'
| 'future-flag' | 'future-flag'
| 'no-future-flag'
| 'no-webpack-config'
| 'webpack-config'
export type CheckResult = { export type CheckResult = {
enabled: boolean enabled: boolean
...@@ -43,20 +41,18 @@ export async function shouldLoadWithWebpack5( ...@@ -43,20 +41,18 @@ export async function shouldLoadWithWebpack5(
cwd: dir, cwd: dir,
}) })
if (Number(process.env.NEXT_PRIVATE_TEST_WEBPACK5_MODE) > 0) { if (Number(process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE) > 0) {
return { return {
enabled: true, enabled: false,
reason: 'test-mode', reason: 'test-mode',
} }
} }
// No `next.config.js`: // Use webpack 5 by default in apps that do not have next.config.js
if (!path?.length) { if (!path?.length) {
// Uncomment to add auto-enable when there is no next.config.js
// Use webpack 5 by default in new apps:
return { return {
enabled: true, enabled: true,
reason: 'no-config', reason: 'default',
} }
} }
...@@ -69,33 +65,21 @@ export async function shouldLoadWithWebpack5( ...@@ -69,33 +65,21 @@ export async function shouldLoadWithWebpack5(
userConfigModule.default || userConfigModule userConfigModule.default || userConfigModule
) )
// Opted-in manually if (userConfig.future?.webpack5) {
if (userConfig.future?.webpack5 === true) {
return { return {
enabled: true, enabled: false,
reason: 'future-flag', reason: 'future-flag',
} }
} }
if (userConfig.webpack5 === false) {
// Opted-out manually
if (userConfig.future?.webpack5 === false) {
return { return {
enabled: false, enabled: false,
reason: 'no-future-flag', reason: 'flag-disabled',
} }
} }
// Uncomment to add auto-enable when there is no custom webpack config
// The user isn't configuring webpack
if (!userConfig.webpack) {
return { return {
enabled: true, enabled: true,
reason: 'no-webpack-config', reason: 'default',
}
}
return {
enabled: false,
reason: 'webpack-config',
} }
} }
...@@ -9,16 +9,10 @@ export { install, shouldLoadWithWebpack5 } ...@@ -9,16 +9,10 @@ export { install, shouldLoadWithWebpack5 }
function reasonMessage(reason: CheckReasons) { function reasonMessage(reason: CheckReasons) {
switch (reason) { switch (reason) {
case 'future-flag': case 'default':
return 'future.webpack5 option enabled' return 'Enabled by default'
case 'no-future-flag': case 'flag-disabled':
return 'future.webpack5 option disabled' return 'webpack5 flag is set to false in next.config.js'
case 'no-config':
return 'no next.config.js'
case 'webpack-config':
return 'custom webpack configuration in next.config.js'
case 'no-webpack-config':
return 'no custom webpack configuration in next.config.js'
case 'test-mode': case 'test-mode':
return 'internal test mode' return 'internal test mode'
default: default:
...@@ -27,7 +21,8 @@ function reasonMessage(reason: CheckReasons) { ...@@ -27,7 +21,8 @@ function reasonMessage(reason: CheckReasons) {
} }
export async function loadWebpackHook(phase: string, dir: string) { export async function loadWebpackHook(phase: string, dir: string) {
let useWebpack5 = false let useWebpack5 = true
let usesRemovedFlag = false
const worker: any = new Worker( const worker: any = new Worker(
path.resolve(__dirname, './config-utils-worker.js'), path.resolve(__dirname, './config-utils-worker.js'),
{ {
...@@ -37,7 +32,9 @@ export async function loadWebpackHook(phase: string, dir: string) { ...@@ -37,7 +32,9 @@ export async function loadWebpackHook(phase: string, dir: string) {
) )
try { try {
const result: CheckResult = await worker.shouldLoadWithWebpack5(phase, dir) const result: CheckResult = await worker.shouldLoadWithWebpack5(phase, dir)
// Don't log which webpack version is being used when booting production server as it's not used after build if (result.reason === 'future-flag') {
usesRemovedFlag = true
} else {
if (phase !== PHASE_PRODUCTION_SERVER) { if (phase !== PHASE_PRODUCTION_SERVER) {
Log.info( Log.info(
`Using webpack ${result.enabled ? '5' : '4'}. Reason: ${reasonMessage( `Using webpack ${result.enabled ? '5' : '4'}. Reason: ${reasonMessage(
...@@ -45,6 +42,7 @@ export async function loadWebpackHook(phase: string, dir: string) { ...@@ -45,6 +42,7 @@ export async function loadWebpackHook(phase: string, dir: string) {
)} https://nextjs.org/docs/messages/webpack5` )} https://nextjs.org/docs/messages/webpack5`
) )
} }
}
useWebpack5 = Boolean(result.enabled) useWebpack5 = Boolean(result.enabled)
} catch { } catch {
...@@ -54,5 +52,11 @@ export async function loadWebpackHook(phase: string, dir: string) { ...@@ -54,5 +52,11 @@ export async function loadWebpackHook(phase: string, dir: string) {
worker.end() worker.end()
} }
if (usesRemovedFlag) {
throw new Error(
'`future.webpack5` in `next.config.js` has moved to the top level `webpack5` flag https://nextjs.org/docs/messages/future-webpack5-moved-to-webpack5'
)
}
install(useWebpack5) install(useWebpack5)
} }
...@@ -65,9 +65,6 @@ module.exports = { ...@@ -65,9 +65,6 @@ module.exports = {
content: ` content: `
module.exports = { module.exports = {
generateBuildId: () => 'BUILD_ID', generateBuildId: () => 'BUILD_ID',
future: {
webpack5: true
},
webpack(config) { webpack(config) {
config.optimization.minimize = false config.optimization.minimize = false
config.optimization.minimizer = undefined config.optimization.minimizer = undefined
...@@ -138,9 +135,7 @@ module.exports = { ...@@ -138,9 +135,7 @@ module.exports = {
content: ` content: `
module.exports = { module.exports = {
generateBuildId: () => 'BUILD_ID', generateBuildId: () => 'BUILD_ID',
future: { webpack5: false,
webpack5: false
},
webpack(config) { webpack(config) {
config.optimization.minimize = false config.optimization.minimize = false
config.optimization.minimizer = undefined config.optimization.minimizer = undefined
...@@ -157,10 +152,8 @@ module.exports = { ...@@ -157,10 +152,8 @@ module.exports = {
content: ` content: `
module.exports = { module.exports = {
generateBuildId: () => 'BUILD_ID', generateBuildId: () => 'BUILD_ID',
future: {
webpack5: false webpack5: false
} }
}
`, `,
}, },
], ],
......
...@@ -36,6 +36,12 @@ describe('Basic Features', () => { ...@@ -36,6 +36,12 @@ describe('Basic Features', () => {
it('should polyfill Node.js modules', async () => { it('should polyfill Node.js modules', async () => {
const browser = await webdriver(context.appPort, '/node-browser-polyfills') const browser = await webdriver(context.appPort, '/node-browser-polyfills')
console.error({
logs: await browser.log('browser'),
content: await browser.eval('document.documentElement.innerHTML'),
})
await browser.waitForCondition('window.didRender') await browser.waitForCondition('window.didRender')
const data = await browser const data = await browser
......
...@@ -3,6 +3,8 @@ const withSass = require('@zeit/next-sass') ...@@ -3,6 +3,8 @@ const withSass = require('@zeit/next-sass')
const path = require('path') const path = require('path')
module.exports = withCSS( module.exports = withCSS(
withSass({ withSass({
// @zeit/next-sass is not supported with webpack 5
webpack5: false,
onDemandEntries: { onDemandEntries: {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60, maxInactiveAge: 1000 * 60 * 60,
......
const withCSS = require('@zeit/next-css') const withCSS = require('@zeit/next-css')
module.exports = withCSS({ module.exports = withCSS({
// @zeit/next-css is not supported with webpack 5
webpack5: false,
onDemandEntries: { onDemandEntries: {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60, maxInactiveAge: 1000 * 60 * 60,
......
...@@ -7,7 +7,4 @@ module.exports = { ...@@ -7,7 +7,4 @@ module.exports = {
return config return config
}, },
future: {
webpack5: true,
},
} }
...@@ -48,7 +48,9 @@ describe('Build Output', () => { ...@@ -48,7 +48,9 @@ describe('Build Output', () => {
expect(parseFloat(indexSize)).toBeGreaterThanOrEqual(2) expect(parseFloat(indexSize)).toBeGreaterThanOrEqual(2)
expect(indexSize.endsWith('kB')).toBe(true) expect(indexSize.endsWith('kB')).toBe(true)
expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(67.9) expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(
process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE ? 68 : 67.9
)
expect(parseFloat(indexFirstLoad)).toBeGreaterThanOrEqual(60) expect(parseFloat(indexFirstLoad)).toBeGreaterThanOrEqual(60)
expect(indexFirstLoad.endsWith('kB')).toBe(true) expect(indexFirstLoad.endsWith('kB')).toBe(true)
}) })
......
const withSass = require('@zeit/next-sass') const withSass = require('@zeit/next-sass')
module.exports = withSass() module.exports = withSass({
// @zeit/next-sass is not supported with webpack 5
webpack5: false,
})
module.exports = { module.exports = {
future: {
webpack5: false, webpack5: false,
},
} }
...@@ -3,6 +3,8 @@ const withSass = require('@zeit/next-sass') ...@@ -3,6 +3,8 @@ const withSass = require('@zeit/next-sass')
const path = require('path') const path = require('path')
module.exports = withCSS( module.exports = withCSS(
withSass({ withSass({
// @zeit/next-sass is not supported with webpack 5
webpack5: false,
env: { env: {
...(process.env.ENABLE_ENV_FAIL_UNDERSCORE ...(process.env.ENABLE_ENV_FAIL_UNDERSCORE
? { ? {
......
...@@ -85,6 +85,6 @@ describe('Production response size', () => { ...@@ -85,6 +85,6 @@ describe('Production response size', () => {
const delta = responseSizesBytes / 1024 const delta = responseSizesBytes / 1024
// Expected difference: < 0.5 // Expected difference: < 0.5
expect(delta).toBeCloseTo(289.3, 0) expect(delta).toBeCloseTo(286.8, 0)
}) })
}) })
module.exports = { module.exports = {
future: { webpack(config) {
webpack5: true,
},
webpack(config, options) {
console.log('Initialized config') console.log('Initialized config')
if ( if (
require('webpack/lib/node/NodeTargetPlugin') !== require('webpack/lib/node/NodeTargetPlugin') !==
......
module.exports = { module.exports = {
// worker-loader is webpack 4 specific, new Worker should be used
// in webpack 5
webpack5: false,
webpack: (config, { isServer }) => { webpack: (config, { isServer }) => {
config.module.rules.unshift({ config.module.rules.unshift({
test: /\.worker\.(js|ts|tsx)$/, test: /\.worker\.(js|ts|tsx)$/,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment