Unverified Commit 0222a09c authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable polyfillsOptimization (#10574)

* Enable polyfillsOptimization

* Update sizes

* Commons is no longer there

* Update test
parent 72823f04
...@@ -64,9 +64,7 @@ module.exports = ( ...@@ -64,9 +64,7 @@ module.exports = (
const supportsESM = api.caller(supportsStaticESM) const supportsESM = api.caller(supportsStaticESM)
const isServer = api.caller((caller: any) => !!caller && caller.isServer) const isServer = api.caller((caller: any) => !!caller && caller.isServer)
const isModern = api.caller((caller: any) => !!caller && caller.isModern) const isModern = api.caller((caller: any) => !!caller && caller.isModern)
const isPolyfillsOptimization = api.caller(
(caller: any) => !!caller && caller.polyfillsOptimization
)
const isLaxModern = const isLaxModern =
isModern || isModern ||
(options['preset-env']?.targets && (options['preset-env']?.targets &&
...@@ -155,7 +153,7 @@ module.exports = ( ...@@ -155,7 +153,7 @@ module.exports = (
!isServer && [ !isServer && [
require('@babel/plugin-transform-runtime'), require('@babel/plugin-transform-runtime'),
{ {
corejs: isPolyfillsOptimization ? false : 2, corejs: false,
helpers: true, helpers: true,
regenerator: true, regenerator: true,
useESModules: supportsESM && presetEnvConfig.modules !== 'commonjs', useESModules: supportsESM && presetEnvConfig.modules !== 'commonjs',
......
...@@ -54,10 +54,7 @@ const escapePathVariables = (value: any) => { ...@@ -54,10 +54,7 @@ const escapePathVariables = (value: any) => {
: value : value
} }
function getOptimizedAliases( function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
isServer: boolean,
polyfillsOptimization: boolean
): { [pkg: string]: string } {
if (isServer) { if (isServer) {
return {} return {}
} }
...@@ -68,12 +65,6 @@ function getOptimizedAliases( ...@@ -68,12 +65,6 @@ function getOptimizedAliases(
const shimAssign = path.join(__dirname, 'polyfills', 'object.assign') const shimAssign = path.join(__dirname, 'polyfills', 'object.assign')
return Object.assign( return Object.assign(
{}, {},
// Polyfill: Window#fetch
polyfillsOptimization
? undefined
: {
__next_polyfill__fetch: require.resolve('whatwg-fetch'),
},
{ {
unfetch$: stubWindowFetch, unfetch$: stubWindowFetch,
'isomorphic-unfetch$': stubWindowFetch, 'isomorphic-unfetch$': stubWindowFetch,
...@@ -84,13 +75,6 @@ function getOptimizedAliases( ...@@ -84,13 +75,6 @@ function getOptimizedAliases(
'whatwg-fetch.js' 'whatwg-fetch.js'
), ),
}, },
polyfillsOptimization
? undefined
: {
// Polyfill: Object.assign
__next_polyfill__object_assign: require.resolve('object-assign'),
'@babel/runtime-corejs2/core-js/object/assign': stubObjectAssign,
},
{ {
'object-assign$': stubObjectAssign, 'object-assign$': stubObjectAssign,
...@@ -168,7 +152,6 @@ export default async function getBaseWebpackConfig( ...@@ -168,7 +152,6 @@ export default async function getBaseWebpackConfig(
babelPresetPlugins, babelPresetPlugins,
hasModern: !!config.experimental.modern, hasModern: !!config.experimental.modern,
development: dev, development: dev,
polyfillsOptimization: !!config.experimental.polyfillsOptimization,
}, },
}, },
// Backwards compat // Backwards compat
...@@ -215,9 +198,7 @@ export default async function getBaseWebpackConfig( ...@@ -215,9 +198,7 @@ export default async function getBaseWebpackConfig(
), ),
[CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join( [CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join(
NEXT_PROJECT_ROOT_DIST_CLIENT, NEXT_PROJECT_ROOT_DIST_CLIENT,
config.experimental.polyfillsOptimization 'polyfills.js'
? 'polyfills-nomodule.js'
: 'polyfills.js'
), ),
} as ClientEntries) } as ClientEntries)
: undefined : undefined
...@@ -267,17 +248,7 @@ export default async function getBaseWebpackConfig( ...@@ -267,17 +248,7 @@ export default async function getBaseWebpackConfig(
next: NEXT_PROJECT_ROOT, next: NEXT_PROJECT_ROOT,
[PAGES_DIR_ALIAS]: pagesDir, [PAGES_DIR_ALIAS]: pagesDir,
[DOT_NEXT_ALIAS]: distDir, [DOT_NEXT_ALIAS]: distDir,
...getOptimizedAliases( ...getOptimizedAliases(isServer),
isServer,
!!config.experimental.polyfillsOptimization
),
// Temporary to allow runtime-corejs2 to be stubbed in experimental polyfillsOptimization
...(config.experimental.polyfillsOptimization
? {
'@babel/runtime-corejs2': '@babel/runtime',
}
: undefined),
}, },
mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'], mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
plugins: [PnpWebpackPlugin], plugins: [PnpWebpackPlugin],
...@@ -528,11 +499,7 @@ export default async function getBaseWebpackConfig( ...@@ -528,11 +499,7 @@ export default async function getBaseWebpackConfig(
!res.match(/next[/\\]dist[/\\]next-server[/\\]/) && !res.match(/next[/\\]dist[/\\]next-server[/\\]/) &&
(res.match(/[/\\]next[/\\]dist[/\\]/) || (res.match(/[/\\]next[/\\]dist[/\\]/) ||
// This is the @babel/plugin-transform-runtime "helpers: true" option // This is the @babel/plugin-transform-runtime "helpers: true" option
res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) || res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/))
(!config.experimental.polyfillsOptimization &&
res.match(
/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/
)))
) { ) {
return callback() return callback()
} }
...@@ -728,9 +695,6 @@ export default async function getBaseWebpackConfig( ...@@ -728,9 +695,6 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_MODERN_BUILD': JSON.stringify( 'process.env.__NEXT_MODERN_BUILD': JSON.stringify(
config.experimental.modern && !dev config.experimental.modern && !dev
), ),
'process.env.__NEXT_POLYFILLS_OPTIMIZATION': JSON.stringify(
!!config.experimental.polyfillsOptimization
),
'process.env.__NEXT_GRANULAR_CHUNKS': JSON.stringify( 'process.env.__NEXT_GRANULAR_CHUNKS': JSON.stringify(
config.experimental.granularChunks && !dev config.experimental.granularChunks && !dev
), ),
......
...@@ -59,7 +59,6 @@ module.exports = babelLoader.custom(babel => { ...@@ -59,7 +59,6 @@ module.exports = babelLoader.custom(babel => {
hasModern: opts.hasModern, hasModern: opts.hasModern,
babelPresetPlugins: opts.babelPresetPlugins, babelPresetPlugins: opts.babelPresetPlugins,
development: opts.development, development: opts.development,
polyfillsOptimization: opts.polyfillsOptimization,
} }
const filename = join(opts.cwd, 'noop.js') const filename = join(opts.cwd, 'noop.js')
const loader = Object.assign( const loader = Object.assign(
...@@ -72,7 +71,7 @@ module.exports = babelLoader.custom(babel => { ...@@ -72,7 +71,7 @@ module.exports = babelLoader.custom(babel => {
(opts.isServer ? '-server' : '') + (opts.isServer ? '-server' : '') +
(opts.isModern ? '-modern' : '') + (opts.isModern ? '-modern' : '') +
(opts.hasModern ? '-has-modern' : '') + (opts.hasModern ? '-has-modern' : '') +
(opts.polyfillsOptimization ? '-new-polyfills' : '') + '-new-polyfills' +
(opts.development ? '-development' : '-production') + (opts.development ? '-development' : '-production') +
JSON.stringify( JSON.stringify(
babel.loadPartialConfig({ babel.loadPartialConfig({
...@@ -95,7 +94,6 @@ module.exports = babelLoader.custom(babel => { ...@@ -95,7 +94,6 @@ module.exports = babelLoader.custom(babel => {
delete loader.hasModern delete loader.hasModern
delete loader.pagesDir delete loader.pagesDir
delete loader.babelPresetPlugins delete loader.babelPresetPlugins
delete loader.polyfillsOptimization
delete loader.development delete loader.development
return { loader, custom } return { loader, custom }
}, },
...@@ -110,7 +108,6 @@ module.exports = babelLoader.custom(babel => { ...@@ -110,7 +108,6 @@ module.exports = babelLoader.custom(babel => {
pagesDir, pagesDir,
babelPresetPlugins, babelPresetPlugins,
development, development,
polyfillsOptimization,
}, },
} }
) { ) {
...@@ -134,7 +131,6 @@ module.exports = babelLoader.custom(babel => { ...@@ -134,7 +131,6 @@ module.exports = babelLoader.custom(babel => {
options.caller.isServer = isServer options.caller.isServer = isServer
options.caller.isModern = isModern options.caller.isModern = isModern
options.caller.polyfillsOptimization = polyfillsOptimization
options.caller.isDev = development options.caller.isDev = development
options.plugins = options.plugins || [] options.plugins = options.plugins || []
......
...@@ -14,20 +14,9 @@ import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic' ...@@ -14,20 +14,9 @@ import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
if (process.env.__NEXT_POLYFILLS_OPTIMIZATION) { if (!('finally' in Promise.prototype)) {
if (!('finally' in Promise.prototype)) { // eslint-disable-next-line no-extend-native
// eslint-disable-next-line no-extend-native Promise.prototype.finally = require('finally-polyfill')
Promise.prototype.finally = require('finally-polyfill')
}
} else {
// Polyfill Promise globally
// This is needed because Webpack's dynamic loading(common chunks) code
// depends on Promise.
// So, we need to polyfill it.
// See: https://webpack.js.org/guides/code-splitting/#dynamic-imports
if (!self.Promise) {
self.Promise = require('@babel/runtime-corejs2/core-js/promise')
}
} }
const data = JSON.parse(document.getElementById('__NEXT_DATA__').textContent) const data = JSON.parse(document.getElementById('__NEXT_DATA__').textContent)
......
import '__next_polyfill__fetch' import '@next/polyfill-nomodule'
import 'url-polyfill'
Object.assign = require('__next_polyfill__object_assign')
...@@ -72,7 +72,6 @@ ...@@ -72,7 +72,6 @@
"@babel/preset-react": "7.7.0", "@babel/preset-react": "7.7.0",
"@babel/preset-typescript": "7.7.2", "@babel/preset-typescript": "7.7.2",
"@babel/runtime": "7.7.2", "@babel/runtime": "7.7.2",
"@babel/runtime-corejs2": "7.7.2",
"@babel/types": "7.7.4", "@babel/types": "7.7.4",
"@next/polyfill-nomodule": "9.2.3-canary.0", "@next/polyfill-nomodule": "9.2.3-canary.0",
"amphtml-validator": "1.0.23", "amphtml-validator": "1.0.23",
...@@ -117,7 +116,6 @@ ...@@ -117,7 +116,6 @@
"mini-css-extract-plugin": "0.8.0", "mini-css-extract-plugin": "0.8.0",
"mkdirp": "0.5.1", "mkdirp": "0.5.1",
"node-fetch": "2.6.0", "node-fetch": "2.6.0",
"object-assign": "4.1.1",
"ora": "3.4.0", "ora": "3.4.0",
"path-to-regexp": "6.1.0", "path-to-regexp": "6.1.0",
"pnp-webpack-plugin": "1.5.0", "pnp-webpack-plugin": "1.5.0",
...@@ -148,8 +146,7 @@ ...@@ -148,8 +146,7 @@
"webpack": "4.41.2", "webpack": "4.41.2",
"webpack-dev-middleware": "3.7.0", "webpack-dev-middleware": "3.7.0",
"webpack-hot-middleware": "2.25.0", "webpack-hot-middleware": "2.25.0",
"webpack-sources": "1.4.3", "webpack-sources": "1.4.3"
"whatwg-fetch": "3.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^16.6.0", "react": "^16.6.0",
......
...@@ -95,11 +95,6 @@ module.exports = function(task) { ...@@ -95,11 +95,6 @@ module.exports = function(task) {
const output = transform(file.data, options) const output = transform(file.data, options)
const ext = extname(file.base) const ext = extname(file.base)
output.code = output.code.replace(
/@babel\/runtime\//g,
'@babel/runtime-corejs2/'
)
// Replace `.ts|.tsx` with `.js` in files with an extension // Replace `.ts|.tsx` with `.js` in files with an extension
if (ext) { if (ext) {
const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i') const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i')
......
module.exports = { module.exports = {
experimental: {
polyfillsOptimization: true,
},
webpack(config, options) { webpack(config, options) {
if (!options.isServer) { if (!options.isServer) {
config.profile = true config.profile = true
......
...@@ -40,14 +40,7 @@ describe('Modern Mode', () => { ...@@ -40,14 +40,7 @@ describe('Modern Mode', () => {
it('should generate client side modern and legacy build files', async () => { it('should generate client side modern and legacy build files', async () => {
const buildId = readFileSync(join(appDir, '.next/BUILD_ID'), 'utf8') const buildId = readFileSync(join(appDir, '.next/BUILD_ID'), 'utf8')
const expectedFiles = [ const expectedFiles = ['index', '_app', '_error', 'main', 'webpack']
'index',
'_app',
'_error',
'main',
'webpack',
'commons',
]
const buildFiles = [ const buildFiles = [
...readdirSync(join(appDir, '.next/static', buildId, 'pages')), ...readdirSync(join(appDir, '.next/static', buildId, 'pages')),
...readdirSync(join(appDir, '.next/static/runtime')).map( ...readdirSync(join(appDir, '.next/static/runtime')).map(
......
module.exports = { module.exports = {}
experimental: {
polyfillsOptimization: true,
},
}
...@@ -80,7 +80,7 @@ describe('Production response size', () => { ...@@ -80,7 +80,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 233 * 1024 const delta = responseSizesBytes - 241 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
...@@ -100,7 +100,7 @@ describe('Production response size', () => { ...@@ -100,7 +100,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 201 * 1024 const delta = responseSizesBytes - 171 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
...@@ -69,7 +69,7 @@ describe('next/babel', () => { ...@@ -69,7 +69,7 @@ describe('next/babel', () => {
expect(output).toMatch(`__jsx("a",{href:"/"`) expect(output).toMatch(`__jsx("a",{href:"/"`)
expect(babel(`const a = ()=><a href="/">home</a>`)).toMatchInlineSnapshot( expect(babel(`const a = ()=><a href="/">home</a>`)).toMatchInlineSnapshot(
`"\\"use strict\\";var _interopRequireDefault=require(\\"@babel/runtime-corejs2/helpers/interopRequireDefault\\");var _react=_interopRequireDefault(require(\\"react\\"));var __jsx=_react[\\"default\\"].createElement;var a=function a(){return __jsx(\\"a\\",{href:\\"/\\"},\\"home\\");};"` `"\\"use strict\\";var _interopRequireDefault=require(\\"@babel/runtime/helpers/interopRequireDefault\\");var _react=_interopRequireDefault(require(\\"react\\"));var __jsx=_react[\\"default\\"].createElement;var a=function a(){return __jsx(\\"a\\",{href:\\"/\\"},\\"home\\");};"`
) )
}) })
......
...@@ -1036,14 +1036,6 @@ ...@@ -1036,14 +1036,6 @@
"@babel/helper-plugin-utils" "^7.0.0" "@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-transform-typescript" "^7.7.4" "@babel/plugin-transform-typescript" "^7.7.4"
"@babel/runtime-corejs2@7.7.2":
version "7.7.2"
resolved "https://registry.yarnpkg.com/@babel/runtime-corejs2/-/runtime-corejs2-7.7.2.tgz#5a8c4e2f8688ce58adc9eb1d8320b6e7341f96ce"
integrity sha512-GfVnHchOBvIMsweQ13l4jd9lT4brkevnavnVOej5g2y7PpTRY+R4pcQlCjWMZoUla5rMLFzaS/Ll2s59cB1TqQ==
dependencies:
core-js "^2.6.5"
regenerator-runtime "^0.13.2"
"@babel/runtime@7.7.2": "@babel/runtime@7.7.2":
version "7.7.2" version "7.7.2"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.7.2.tgz#111a78002a5c25fc8e3361bedc9529c696b85a6a" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.7.2.tgz#111a78002a5c25fc8e3361bedc9529c696b85a6a"
...@@ -1099,7 +1091,7 @@ ...@@ -1099,7 +1091,7 @@
globals "^11.1.0" globals "^11.1.0"
lodash "^4.17.13" lodash "^4.17.13"
"@babel/types@^7.0.0", "@babel/types@^7.3.0", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.7.1", "@babel/types@^7.7.2", "@babel/types@^7.7.4": "@babel/types@7.7.4", "@babel/types@^7.0.0", "@babel/types@^7.3.0", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.7.1", "@babel/types@^7.7.2", "@babel/types@^7.7.4":
version "7.7.4" version "7.7.4"
resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.7.4.tgz#516570d539e44ddf308c07569c258ff94fde9193" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.7.4.tgz#516570d539e44ddf308c07569c258ff94fde9193"
integrity sha512-cz5Ji23KCi4T+YIE/BolWosrJuSmoZeN1EFnRtBwF+KKLi8GG/Z2c2hOJJeCXPk4mwk4QFvTmwIodJowXgttRA== integrity sha512-cz5Ji23KCi4T+YIE/BolWosrJuSmoZeN1EFnRtBwF+KKLi8GG/Z2c2hOJJeCXPk4mwk4QFvTmwIodJowXgttRA==
......
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