Unverified Commit 30c2dfdc authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Remove old modern mode experiment (#19275)

This PR removes the modern mode experiment because:

- It does not yield meaningful bundle size wins when compared to other initiatives we've taken
- It's not compatible with webpack 5 (which we're upgrading to)
- It's currently broken and causes most apps to malfunction
- There's no champion currently owning the experiment

We can re-introduce this in the future when we'd like to make it a default for all Next.js apps.

Note: **Next.js still supports Differential Loading (`nomodule`) and does it by default.** This PR strictly removes the experimental modern _syntax_, and does not disable our existing modern/legacy polyfilling.

---

Fixes #19200
Fixes #18960
Fixes #14707
Fixes #14465
parent ce5d9c85
...@@ -66,16 +66,15 @@ module.exports = ( ...@@ -66,16 +66,15 @@ module.exports = (
): BabelPreset => { ): BabelPreset => {
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 useJsxRuntime = const useJsxRuntime =
options['preset-react']?.runtime === 'automatic' || options['preset-react']?.runtime === 'automatic' ||
(Boolean(api.caller((caller: any) => !!caller && caller.hasJsxRuntime)) && (Boolean(api.caller((caller: any) => !!caller && caller.hasJsxRuntime)) &&
options['preset-react']?.runtime !== 'classic') options['preset-react']?.runtime !== 'classic')
const isLaxModern = const isLaxModern =
isModern || options['preset-env']?.targets &&
(options['preset-env']?.targets && options['preset-env'].targets.esmodules === true
options['preset-env'].targets.esmodules === true)
const presetEnvConfig = { const presetEnvConfig = {
// In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option // In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option
......
...@@ -540,8 +540,7 @@ export default async function build( ...@@ -540,8 +540,7 @@ export default async function build(
const [selfSize, allSize] = await getJsPageSizeInKb( const [selfSize, allSize] = await getJsPageSizeInKb(
actualPage, actualPage,
distDir, distDir,
buildManifest, buildManifest
config.experimental.modern
) )
let isSsg = false let isSsg = false
...@@ -1114,7 +1113,6 @@ export default async function build( ...@@ -1114,7 +1113,6 @@ export default async function build(
await generateClientSsgManifest(prerenderManifest, { await generateClientSsgManifest(prerenderManifest, {
distDir, distDir,
buildId, buildId,
isModern: !!config.experimental.modern,
}) })
} else { } else {
const prerenderManifest: PrerenderManifest = { const prerenderManifest: PrerenderManifest = {
...@@ -1177,7 +1175,6 @@ export default async function build( ...@@ -1177,7 +1175,6 @@ export default async function build(
useStatic404, useStatic404,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
buildManifest, buildManifest,
isModern: config.experimental.modern,
} }
) )
...@@ -1259,11 +1256,7 @@ export type ClientSsgManifest = Set<string> ...@@ -1259,11 +1256,7 @@ export type ClientSsgManifest = Set<string>
function generateClientSsgManifest( function generateClientSsgManifest(
prerenderManifest: PrerenderManifest, prerenderManifest: PrerenderManifest,
{ { buildId, distDir }: { buildId: string; distDir: string }
buildId,
distDir,
isModern,
}: { buildId: string; distDir: string; isModern: boolean }
) { ) {
const ssgPages: ClientSsgManifest = new Set<string>([ const ssgPages: ClientSsgManifest = new Set<string>([
...Object.entries(prerenderManifest.routes) ...Object.entries(prerenderManifest.routes)
...@@ -1273,21 +1266,12 @@ function generateClientSsgManifest( ...@@ -1273,21 +1266,12 @@ function generateClientSsgManifest(
...Object.keys(prerenderManifest.dynamicRoutes), ...Object.keys(prerenderManifest.dynamicRoutes),
]) ])
const clientSsgManifestPaths = [
'_ssgManifest.js',
isModern && '_ssgManifest.module.js',
]
.filter(Boolean)
.map((f) =>
path.join(`${CLIENT_STATIC_FILES_PATH}/${buildId}`, f as string)
)
const clientSsgManifestContent = `self.__SSG_MANIFEST=${devalue( const clientSsgManifestContent = `self.__SSG_MANIFEST=${devalue(
ssgPages ssgPages
)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()` )};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
clientSsgManifestPaths.forEach((clientSsgManifestPath) =>
writeFileSync( writeFileSync(
path.join(distDir, clientSsgManifestPath), path.join(distDir, CLIENT_STATIC_FILES_PATH, buildId, '_ssgManifest.js'),
clientSsgManifestContent clientSsgManifestContent
)
) )
} }
...@@ -66,7 +66,6 @@ export async function printTreeView( ...@@ -66,7 +66,6 @@ export async function printTreeView(
pagesDir, pagesDir,
pageExtensions, pageExtensions,
buildManifest, buildManifest,
isModern,
useStatic404, useStatic404,
}: { }: {
distPath: string distPath: string
...@@ -74,7 +73,6 @@ export async function printTreeView( ...@@ -74,7 +73,6 @@ export async function printTreeView(
pagesDir: string pagesDir: string
pageExtensions: string[] pageExtensions: string[]
buildManifest: BuildManifest buildManifest: BuildManifest
isModern: boolean
useStatic404: boolean useStatic404: boolean
} }
) { ) {
...@@ -114,12 +112,7 @@ export async function printTreeView( ...@@ -114,12 +112,7 @@ export async function printTreeView(
list = [...list, '/404'] list = [...list, '/404']
} }
const sizeData = await computeFromManifest( const sizeData = await computeFromManifest(buildManifest, distPath, pageInfos)
buildManifest,
distPath,
isModern,
pageInfos
)
const pageList = list const pageList = list
.slice() .slice()
...@@ -374,18 +367,15 @@ type ComputeManifestShape = { ...@@ -374,18 +367,15 @@ type ComputeManifestShape = {
let cachedBuildManifest: BuildManifest | undefined let cachedBuildManifest: BuildManifest | undefined
let lastCompute: ComputeManifestShape | undefined let lastCompute: ComputeManifestShape | undefined
let lastComputeModern: boolean | undefined
let lastComputePageInfo: boolean | undefined let lastComputePageInfo: boolean | undefined
async function computeFromManifest( async function computeFromManifest(
manifest: BuildManifest, manifest: BuildManifest,
distPath: string, distPath: string,
isModern: boolean,
pageInfos?: Map<string, PageInfo> pageInfos?: Map<string, PageInfo>
): Promise<ComputeManifestShape> { ): Promise<ComputeManifestShape> {
if ( if (
Object.is(cachedBuildManifest, manifest) && Object.is(cachedBuildManifest, manifest) &&
lastComputeModern === isModern &&
lastComputePageInfo === !!pageInfos lastComputePageInfo === !!pageInfos
) { ) {
return lastCompute! return lastCompute!
...@@ -405,13 +395,6 @@ async function computeFromManifest( ...@@ -405,13 +395,6 @@ async function computeFromManifest(
++expected ++expected
manifest.pages[key].forEach((file) => { manifest.pages[key].forEach((file) => {
if (
// Select Modern or Legacy scripts
file.endsWith('.module.js') !== isModern
) {
return
}
if (key === '/_app') { if (key === '/_app') {
files.set(file, Infinity) files.set(file, Infinity)
} else if (files.has(file)) { } else if (files.has(file)) {
...@@ -471,7 +454,6 @@ async function computeFromManifest( ...@@ -471,7 +454,6 @@ async function computeFromManifest(
} }
cachedBuildManifest = manifest cachedBuildManifest = manifest
lastComputeModern = isModern
lastComputePageInfo = !!pageInfos lastComputePageInfo = !!pageInfos
return lastCompute! return lastCompute!
} }
...@@ -495,18 +477,16 @@ function sum(a: number[]): number { ...@@ -495,18 +477,16 @@ function sum(a: number[]): number {
export async function getJsPageSizeInKb( export async function getJsPageSizeInKb(
page: string, page: string,
distPath: string, distPath: string,
buildManifest: BuildManifest, buildManifest: BuildManifest
isModern: boolean
): Promise<[number, number]> { ): Promise<[number, number]> {
const data = await computeFromManifest(buildManifest, distPath, isModern) const data = await computeFromManifest(buildManifest, distPath)
const fnFilterModern = (entry: string) => const fnFilterJs = (entry: string) => entry.endsWith('.js')
entry.endsWith('.js') && entry.endsWith('.module.js') === isModern
const pageFiles = ( const pageFiles = (
buildManifest.pages[denormalizePagePath(page)] || [] buildManifest.pages[denormalizePagePath(page)] || []
).filter(fnFilterModern) ).filter(fnFilterJs)
const appFiles = (buildManifest.pages['/_app'] || []).filter(fnFilterModern) const appFiles = (buildManifest.pages['/_app'] || []).filter(fnFilterJs)
const fnMapRealPath = (dep: string) => `${distPath}/${dep}` const fnMapRealPath = (dep: string) => `${distPath}/${dep}`
......
...@@ -62,12 +62,6 @@ type ExcludesFalse = <T>(x: T | false) => x is T ...@@ -62,12 +62,6 @@ type ExcludesFalse = <T>(x: T | false) => x is T
const isWebpack5 = parseInt(webpack.version!) === 5 const isWebpack5 = parseInt(webpack.version!) === 5
const escapePathVariables = (value: any) => {
return typeof value === 'string'
? value.replace(/\[(\\*[\w:]+\\*)\]/gi, '[\\$1\\]')
: value
}
const devtoolRevertWarning = execOnce((devtool: Configuration['devtool']) => { const devtoolRevertWarning = execOnce((devtool: Configuration['devtool']) => {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + chalk.yellow.bold('Warning: ') +
...@@ -249,7 +243,6 @@ export default async function getBaseWebpackConfig( ...@@ -249,7 +243,6 @@ export default async function getBaseWebpackConfig(
// Webpack 5 has a built-in loader cache // Webpack 5 has a built-in loader cache
cache: !isWebpack5, cache: !isWebpack5,
babelPresetPlugins, babelPresetPlugins,
hasModern: !!config.experimental.modern,
development: dev, development: dev,
hasReactRefresh, hasReactRefresh,
hasJsxRuntime, hasJsxRuntime,
...@@ -536,10 +529,7 @@ export default async function getBaseWebpackConfig( ...@@ -536,10 +529,7 @@ export default async function getBaseWebpackConfig(
splitChunksConfig = splitChunksConfigs.prodGranular splitChunksConfig = splitChunksConfigs.prodGranular
} }
const crossOrigin = const crossOrigin = config.crossOrigin
!config.crossOrigin && config.experimental.modern
? 'anonymous'
: config.crossOrigin
let customAppFile: string | null = await findPageFile( let customAppFile: string | null = await findPageFile(
pagesDir, pagesDir,
...@@ -888,9 +878,7 @@ export default async function getBaseWebpackConfig( ...@@ -888,9 +878,7 @@ export default async function getBaseWebpackConfig(
options: { options: {
cacheContext: dir, cacheContext: dir,
cacheDirectory: path.join(dir, '.next', 'cache', 'webpack'), cacheDirectory: path.join(dir, '.next', 'cache', 'webpack'),
cacheIdentifier: `webpack${isServer ? '-server' : ''}${ cacheIdentifier: `webpack${isServer ? '-server' : ''}`,
config.experimental.modern ? '-hasmodern' : ''
}`,
}, },
}, },
{ {
...@@ -963,9 +951,6 @@ export default async function getBaseWebpackConfig( ...@@ -963,9 +951,6 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_TRAILING_SLASH': JSON.stringify( 'process.env.__NEXT_TRAILING_SLASH': JSON.stringify(
config.trailingSlash config.trailingSlash
), ),
'process.env.__NEXT_MODERN_BUILD': JSON.stringify(
config.experimental.modern && !dev
),
'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify( 'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify(
config.devIndicators.buildActivity config.devIndicators.buildActivity
), ),
...@@ -1077,35 +1062,11 @@ export default async function getBaseWebpackConfig( ...@@ -1077,35 +1062,11 @@ export default async function getBaseWebpackConfig(
new BuildManifestPlugin({ new BuildManifestPlugin({
buildId, buildId,
rewrites, rewrites,
modern: config.experimental.modern,
}), }),
tracer && tracer &&
new ProfilingPlugin({ new ProfilingPlugin({
tracer, tracer,
}), }),
!isWebpack5 &&
config.experimental.modern &&
!isServer &&
!dev &&
(() => {
const { NextEsmPlugin } = require('./webpack/plugins/next-esm-plugin')
return new NextEsmPlugin({
filename: (getFileName: Function | string) => (...args: any[]) => {
const name =
typeof getFileName === 'function'
? getFileName(...args)
: getFileName
return name.includes('.js')
? name.replace(/\.js$/, '.module.js')
: escapePathVariables(
args[0].chunk.name.replace(/\.js$/, '.module.js')
)
},
chunkFilename: (inputChunkName: string) =>
inputChunkName.replace(/\.js$/, '.module.js'),
})
})(),
config.experimental.optimizeFonts && config.experimental.optimizeFonts &&
!dev && !dev &&
isServer && isServer &&
...@@ -1191,7 +1152,6 @@ export default async function getBaseWebpackConfig( ...@@ -1191,7 +1152,6 @@ export default async function getBaseWebpackConfig(
crossOrigin: config.crossOrigin, crossOrigin: config.crossOrigin,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
trailingSlash: config.trailingSlash, trailingSlash: config.trailingSlash,
modern: config.experimental.modern,
buildActivity: config.devIndicators.buildActivity, buildActivity: config.devIndicators.buildActivity,
plugins: config.experimental.plugins, plugins: config.experimental.plugins,
reactStrictMode: config.reactStrictMode, reactStrictMode: config.reactStrictMode,
......
...@@ -8,34 +8,6 @@ import * as Log from '../../output/log' ...@@ -8,34 +8,6 @@ import * as Log from '../../output/log'
const cacheKey = 'babel-cache-' + 'n' + '-' const cacheKey = 'babel-cache-' + 'n' + '-'
const nextBabelPreset = require('../../babel/preset') const nextBabelPreset = require('../../babel/preset')
const getModernOptions = (babelOptions = {}) => {
const presetEnvOptions = Object.assign({}, babelOptions['preset-env'])
const transformRuntimeOptions = Object.assign(
{},
babelOptions['transform-runtime'],
{ regenerator: false }
)
presetEnvOptions.targets = {
esmodules: true,
}
presetEnvOptions.exclude = [
...(presetEnvOptions.exclude || []),
// Block accidental inclusions
'transform-regenerator',
'transform-async-to-generator',
]
return {
...babelOptions,
'preset-env': presetEnvOptions,
'transform-runtime': transformRuntimeOptions,
}
}
const nextBabelPresetModern = (presetOptions) => (context) =>
nextBabelPreset(context, getModernOptions(presetOptions))
module.exports = babelLoader.custom((babel) => { module.exports = babelLoader.custom((babel) => {
const presetItem = babel.createConfigItem(nextBabelPreset, { const presetItem = babel.createConfigItem(nextBabelPreset, {
type: 'preset', type: 'preset',
...@@ -55,9 +27,7 @@ module.exports = babelLoader.custom((babel) => { ...@@ -55,9 +27,7 @@ module.exports = babelLoader.custom((babel) => {
customOptions(opts) { customOptions(opts) {
const custom = { const custom = {
isServer: opts.isServer, isServer: opts.isServer,
isModern: opts.isModern,
pagesDir: opts.pagesDir, pagesDir: opts.pagesDir,
hasModern: opts.hasModern,
babelPresetPlugins: opts.babelPresetPlugins, babelPresetPlugins: opts.babelPresetPlugins,
development: opts.development, development: opts.development,
hasReactRefresh: opts.hasReactRefresh, hasReactRefresh: opts.hasReactRefresh,
...@@ -72,8 +42,6 @@ module.exports = babelLoader.custom((babel) => { ...@@ -72,8 +42,6 @@ module.exports = babelLoader.custom((babel) => {
cacheIdentifier: cacheIdentifier:
cacheKey + cacheKey +
(opts.isServer ? '-server' : '') + (opts.isServer ? '-server' : '') +
(opts.isModern ? '-modern' : '') +
(opts.hasModern ? '-has-modern' : '') +
'-new-polyfills' + '-new-polyfills' +
(opts.development ? '-development' : '-production') + (opts.development ? '-development' : '-production') +
(opts.hasReactRefresh ? '-react-refresh' : '') + (opts.hasReactRefresh ? '-react-refresh' : '') +
...@@ -95,8 +63,6 @@ module.exports = babelLoader.custom((babel) => { ...@@ -95,8 +63,6 @@ module.exports = babelLoader.custom((babel) => {
delete loader.isServer delete loader.isServer
delete loader.cache delete loader.cache
delete loader.distDir delete loader.distDir
delete loader.isModern
delete loader.hasModern
delete loader.pagesDir delete loader.pagesDir
delete loader.babelPresetPlugins delete loader.babelPresetPlugins
delete loader.development delete loader.development
...@@ -110,8 +76,6 @@ module.exports = babelLoader.custom((babel) => { ...@@ -110,8 +76,6 @@ module.exports = babelLoader.custom((babel) => {
source, source,
customOptions: { customOptions: {
isServer, isServer,
isModern,
hasModern,
pagesDir, pagesDir,
babelPresetPlugins, babelPresetPlugins,
development, development,
...@@ -138,7 +102,6 @@ module.exports = babelLoader.custom((babel) => { ...@@ -138,7 +102,6 @@ module.exports = babelLoader.custom((babel) => {
} }
options.caller.isServer = isServer options.caller.isServer = isServer
options.caller.isModern = isModern
options.caller.isDev = development options.caller.isDev = development
options.caller.hasJsxRuntime = hasJsxRuntime options.caller.hasJsxRuntime = hasJsxRuntime
...@@ -198,28 +161,9 @@ module.exports = babelLoader.custom((babel) => { ...@@ -198,28 +161,9 @@ module.exports = babelLoader.custom((babel) => {
options.plugins.push(nextDataPlugin) options.plugins.push(nextDataPlugin)
} }
if (isModern) {
const nextPreset = options.presets.find(
(preset) => preset && preset.value === nextBabelPreset
) || { options: {} }
const additionalPresets = options.presets.filter(
(preset) => preset !== nextPreset
)
const presetItemModern = babel.createConfigItem(
nextBabelPresetModern(nextPreset.options),
{
type: 'preset',
}
)
options.presets = [...additionalPresets, presetItemModern]
}
// If the file has `module.exports` we have to transpile commonjs because Babel adds `import` statements // If the file has `module.exports` we have to transpile commonjs because Babel adds `import` statements
// That break webpack, since webpack doesn't support combining commonjs and esmodules // That break webpack, since webpack doesn't support combining commonjs and esmodules
if (!hasModern && source.indexOf('module.exports') !== -1) { if (source.indexOf('module.exports') !== -1) {
options.plugins.push(applyCommonJs) options.plugins.push(applyCommonJs)
} }
......
...@@ -28,7 +28,6 @@ export type ClientBuildManifest = Record<string, string[]> ...@@ -28,7 +28,6 @@ export type ClientBuildManifest = Record<string, string[]>
// reduced version to send to the client. // reduced version to send to the client.
function generateClientManifest( function generateClientManifest(
assetMap: BuildManifest, assetMap: BuildManifest,
isModern: boolean,
rewrites: Rewrite[] rewrites: Rewrite[]
): string { ): string {
const clientManifest: ClientBuildManifest = { const clientManifest: ClientBuildManifest = {
...@@ -44,11 +43,7 @@ function generateClientManifest( ...@@ -44,11 +43,7 @@ function generateClientManifest(
if (page === '/_app') return if (page === '/_app') return
// Filter out dependencies in the _app entry, because those will have already // Filter out dependencies in the _app entry, because those will have already
// been loaded by the client prior to a navigation event // been loaded by the client prior to a navigation event
const filteredDeps = dependencies.filter( const filteredDeps = dependencies.filter((dep) => !appDependencies.has(dep))
(dep) =>
!appDependencies.has(dep) &&
(!dep.endsWith('.js') || dep.endsWith('.module.js') === isModern)
)
// The manifest can omit the page if it has no requirements // The manifest can omit the page if it has no requirements
if (filteredDeps.length) { if (filteredDeps.length) {
...@@ -82,16 +77,11 @@ function getFilesArray(files: any) { ...@@ -82,16 +77,11 @@ function getFilesArray(files: any) {
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production // It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin { export default class BuildManifestPlugin {
private buildId: string private buildId: string
private modern: boolean
private rewrites: Rewrite[] private rewrites: Rewrite[]
constructor(options: { constructor(options: { buildId: string; rewrites: Rewrite[] }) {
buildId: string
modern: boolean
rewrites: Rewrite[]
}) {
this.buildId = options.buildId this.buildId = options.buildId
this.modern = options.modern
this.rewrites = options.rewrites.map((r) => { this.rewrites = options.rewrites.map((r) => {
const rewrite = { ...r } const rewrite = { ...r }
...@@ -185,11 +175,6 @@ export default class BuildManifestPlugin { ...@@ -185,11 +175,6 @@ export default class BuildManifestPlugin {
assetMap.lowPriorityFiles.push( assetMap.lowPriorityFiles.push(
`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js` `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
) )
if (this.modern) {
assetMap.lowPriorityFiles.push(
`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.module.js`
)
}
// Add the runtime ssg manifest file as a lazy-loaded file dependency. // Add the runtime ssg manifest file as a lazy-loaded file dependency.
// We also stub this file out for development mode (when it is not // We also stub this file out for development mode (when it is not
...@@ -200,12 +185,6 @@ export default class BuildManifestPlugin { ...@@ -200,12 +185,6 @@ export default class BuildManifestPlugin {
assetMap.lowPriorityFiles.push(ssgManifestPath) assetMap.lowPriorityFiles.push(ssgManifestPath)
assets[ssgManifestPath] = new RawSource(srcEmptySsgManifest) assets[ssgManifestPath] = new RawSource(srcEmptySsgManifest)
if (this.modern) {
const ssgManifestPathModern = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.module.js`
assetMap.lowPriorityFiles.push(ssgManifestPathModern)
assets[ssgManifestPathModern] = new RawSource(srcEmptySsgManifest)
}
assetMap.pages = Object.keys(assetMap.pages) assetMap.pages = Object.keys(assetMap.pages)
.sort() .sort()
// eslint-disable-next-line // eslint-disable-next-line
...@@ -218,23 +197,10 @@ export default class BuildManifestPlugin { ...@@ -218,23 +197,10 @@ export default class BuildManifestPlugin {
assets[clientManifestPath] = new RawSource( assets[clientManifestPath] = new RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest( `self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap, assetMap,
false,
this.rewrites this.rewrites
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()` )};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
) )
if (this.modern) {
const modernClientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.module.js`
assets[modernClientManifestPath] = new RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap,
true,
this.rewrites
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
)
}
return assets return assets
} }
......
This diff is collapsed.
...@@ -327,7 +327,6 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -327,7 +327,6 @@ Read more: https://err.sh/next.js/export-image-api`
hotReloader: null, hotReloader: null,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
canonicalBase: nextConfig.amp?.canonicalBase || '', canonicalBase: nextConfig.amp?.canonicalBase || '',
isModern: nextConfig.experimental.modern,
ampValidatorPath: nextConfig.experimental.amp?.validator || undefined, ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false, ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined, ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
......
...@@ -46,7 +46,6 @@ const defaultConfig: { [key: string]: any } = { ...@@ -46,7 +46,6 @@ const defaultConfig: { [key: string]: any } = {
(Number(process.env.CIRCLE_NODE_TOTAL) || (Number(process.env.CIRCLE_NODE_TOTAL) ||
(os.cpus() || { length: 1 }).length) - 1 (os.cpus() || { length: 1 }).length) - 1
), ),
modern: false,
plugins: false, plugins: false,
profiling: false, profiling: false,
sprFlushToDisk: true, sprFlushToDisk: true,
......
...@@ -37,13 +37,6 @@ function dedupe<T extends { file: string }>(bundles: T[]): T[] { ...@@ -37,13 +37,6 @@ function dedupe<T extends { file: string }>(bundles: T[]): T[] {
return kept return kept
} }
function getOptionalModernScriptVariant(path: string): string {
if (process.env.__NEXT_MODERN_BUILD) {
return path.replace(/\.js$/, '.module.js')
}
return path
}
type DocumentFiles = { type DocumentFiles = {
sharedFiles: readonly string[] sharedFiles: readonly string[]
pageFiles: readonly string[] pageFiles: readonly string[]
...@@ -225,10 +218,7 @@ export class Head extends Component< ...@@ -225,10 +218,7 @@ export class Head extends Component<
return ( return (
dedupe(dynamicImports) dedupe(dynamicImports)
.map((bundle) => { .map((bundle) => {
// `dynamicImports` will contain both `.js` and `.module.js` when the if (!bundle.file.endsWith('.js')) {
// feature is enabled. This clause will filter down to the modern
// variants only.
if (!bundle.file.endsWith(getOptionalModernScriptVariant('.js'))) {
return null return null
} }
...@@ -255,10 +245,7 @@ export class Head extends Component< ...@@ -255,10 +245,7 @@ export class Head extends Component<
getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null { getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null {
const { assetPrefix, devOnlyCacheBusterQueryString } = this.context const { assetPrefix, devOnlyCacheBusterQueryString } = this.context
const preloadFiles = files.allFiles.filter((file: string) => { const preloadFiles = files.allFiles.filter((file: string) => {
// `dynamicImports` will contain both `.js` and `.module.js` when return file.endsWith('.js')
// the feature is enabled. This clause will filter down to the
// modern variants only.
return file.endsWith(getOptionalModernScriptVariant('.js'))
}) })
return !preloadFiles.length return !preloadFiles.length
...@@ -560,13 +547,6 @@ export class NextScript extends Component<OriginProps> { ...@@ -560,13 +547,6 @@ export class NextScript extends Component<OriginProps> {
} = this.context } = this.context
return dedupe(dynamicImports).map((bundle) => { return dedupe(dynamicImports).map((bundle) => {
let modernProps = {}
if (process.env.__NEXT_MODERN_BUILD) {
modernProps = bundle.file.endsWith('.module.js')
? { type: 'module' }
: { noModule: true }
}
if (!bundle.file.endsWith('.js') || files.allFiles.includes(bundle.file)) if (!bundle.file.endsWith('.js') || files.allFiles.includes(bundle.file))
return null return null
...@@ -581,7 +561,6 @@ export class NextScript extends Component<OriginProps> { ...@@ -581,7 +561,6 @@ export class NextScript extends Component<OriginProps> {
crossOrigin={ crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
} }
{...modernProps}
/> />
) )
}) })
...@@ -601,13 +580,6 @@ export class NextScript extends Component<OriginProps> { ...@@ -601,13 +580,6 @@ export class NextScript extends Component<OriginProps> {
) )
return [...normalScripts, ...lowPriorityScripts].map((file) => { return [...normalScripts, ...lowPriorityScripts].map((file) => {
let modernProps = {}
if (process.env.__NEXT_MODERN_BUILD) {
modernProps = file.endsWith('.module.js')
? { type: 'module' }
: { noModule: true }
}
return ( return (
<script <script
key={file} key={file}
...@@ -619,7 +591,6 @@ export class NextScript extends Component<OriginProps> { ...@@ -619,7 +591,6 @@ export class NextScript extends Component<OriginProps> {
crossOrigin={ crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
} }
{...modernProps}
/> />
) )
}) })
...@@ -761,18 +732,6 @@ export class NextScript extends Component<OriginProps> { ...@@ -761,18 +732,6 @@ export class NextScript extends Component<OriginProps> {
}} }}
/> />
)} )}
{process.env.__NEXT_MODERN_BUILD && !disableRuntimeJS ? (
<script
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
noModule={true}
dangerouslySetInnerHTML={{
__html: NextScript.safariNomoduleFix,
}}
/>
) : null}
{!disableRuntimeJS && this.getPolyfillScripts()} {!disableRuntimeJS && this.getPolyfillScripts()}
{disableRuntimeJS ? null : this.getDynamicChunks(files)} {disableRuntimeJS ? null : this.getDynamicChunks(files)}
{disableRuntimeJS ? null : this.getScripts(files)} {disableRuntimeJS ? null : this.getScripts(files)}
......
...@@ -2,28 +2,17 @@ const clientGlobs = [ ...@@ -2,28 +2,17 @@ const clientGlobs = [
{ {
name: 'Client Bundles (main, webpack, commons)', name: 'Client Bundles (main, webpack, commons)',
globs: [ globs: [
'.next/static/runtime/+(main|webpack)-!(*.module.js)', '.next/static/runtime/+(main|webpack)-*',
'.next/static/chunks/!(polyfills-*|*.module.js)', '.next/static/chunks/!(polyfills*)',
],
},
{
name: 'Client Bundles (main, webpack, commons) Modern',
globs: [
'.next/static/runtime/+(main|webpack)-*.module.js',
'.next/static/chunks/!(polyfills-*)*.module.js',
], ],
}, },
{ {
name: 'Legacy Client Bundles (polyfills)', name: 'Legacy Client Bundles (polyfills)',
globs: ['.next/static/chunks/+(polyfills)-!(*.module.js)'], globs: ['.next/static/chunks/+(polyfills)-*'],
}, },
{ {
name: 'Client Pages', name: 'Client Pages',
globs: ['.next/static/*/pages/**/!(*.module.js)'], globs: ['.next/static/*/pages/**/*'],
},
{
name: 'Client Pages Modern',
globs: ['.next/static/*/pages/**/*.module.js'],
}, },
{ {
name: 'Client Build Manifests', name: 'Client Build Manifests',
...@@ -41,51 +30,30 @@ const renames = [ ...@@ -41,51 +30,30 @@ const renames = [
dest: '.next/static/BUILD_ID/pages', dest: '.next/static/BUILD_ID/pages',
}, },
{ {
srcGlob: '.next/static/runtime/main-!(*.module.js)', srcGlob: '.next/static/runtime/main-*',
dest: '.next/static/runtime/main-HASH.js', dest: '.next/static/runtime/main-HASH.js',
}, },
{ {
srcGlob: '.next/static/runtime/webpack-!(*.module.js)', srcGlob: '.next/static/runtime/webpack-*',
dest: '.next/static/runtime/webpack-HASH.js', dest: '.next/static/runtime/webpack-HASH.js',
}, },
{ {
srcGlob: '.next/static/runtime/polyfills-!(*.module.js)', srcGlob: '.next/static/runtime/polyfills-*',
dest: '.next/static/runtime/polyfills-HASH.js', dest: '.next/static/runtime/polyfills-HASH.js',
}, },
{ {
srcGlob: '.next/static/chunks/commons!(*.module.js)', srcGlob: '.next/static/chunks/commons*',
dest: '.next/static/chunks/commons.HASH.js', dest: '.next/static/chunks/commons.HASH.js',
}, },
{ {
srcGlob: '.next/static/chunks/framework!(*.module.js)', srcGlob: '.next/static/chunks/framework*',
dest: '.next/static/chunks/framework.HASH.js', dest: '.next/static/chunks/framework.HASH.js',
}, },
// modern
{
srcGlob: '.next/static/runtime/main-*.module.js',
dest: '.next/static/runtime/main-HASH.module.js',
},
{
srcGlob: '.next/static/runtime/webpack-*.module.js',
dest: '.next/static/runtime/webpack-HASH.module.js',
},
{
srcGlob: '.next/static/chunks/commons*.module.js',
dest: '.next/static/chunks/commons.HASH.module.js',
},
{
srcGlob: '.next/static/chunks/framework*.module.js',
dest: '.next/static/chunks/framework.HASH.module.js',
},
// misc // misc
{ {
srcGlob: '.next/static/*/_buildManifest.js', srcGlob: '.next/static/*/_buildManifest.js',
dest: '.next/static/BUILD_ID/_buildManifest.js', dest: '.next/static/BUILD_ID/_buildManifest.js',
}, },
{
srcGlob: '.next/static/*/_buildManifest.module.js',
dest: '.next/static/BUILD_ID/_buildManifest.module.js',
},
] ]
module.exports = { module.exports = {
...@@ -110,9 +78,6 @@ module.exports = { ...@@ -110,9 +78,6 @@ module.exports = {
config.optimization.minimize = false config.optimization.minimize = false
config.optimization.minimizer = undefined config.optimization.minimizer = undefined
return config return config
},
experimental: {
modern: true
} }
} }
`, `,
...@@ -125,10 +90,7 @@ module.exports = { ...@@ -125,10 +90,7 @@ module.exports = {
path: 'next.config.js', path: 'next.config.js',
content: ` content: `
module.exports = { module.exports = {
generateBuildId: () => 'BUILD_ID', generateBuildId: () => 'BUILD_ID'
experimental: {
modern: true
}
} }
`, `,
}, },
...@@ -160,10 +122,7 @@ module.exports = { ...@@ -160,10 +122,7 @@ module.exports = {
content: ` content: `
module.exports = { module.exports = {
generateBuildId: () => 'BUILD_ID', generateBuildId: () => 'BUILD_ID',
target: 'serverless', target: 'serverless'
experimental: {
modern: true
}
} }
`, `,
}, },
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import { validateAMP } from 'amp-test-utils' import { validateAMP } from 'amp-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { readFile, readFileSync, writeFile, writeFileSync } from 'fs-extra' import { readFileSync, writeFileSync } from 'fs-extra'
import { import {
check, check,
findPort, findPort,
...@@ -235,58 +235,6 @@ describe('AMP Usage', () => { ...@@ -235,58 +235,6 @@ describe('AMP Usage', () => {
}) })
}) })
describe('production mode modern', () => {
let origNextConfig = ''
const nextConfigPath = join(appDir, 'next.config.js')
beforeAll(async () => {
origNextConfig = await readFile(nextConfigPath, 'utf8')
await writeFile(
nextConfigPath,
origNextConfig.replace(
'// edit here',
`
experimental: {
modern: true
}
`
)
)
await nextBuild(appDir)
app = nextServer({
dir: join(__dirname, '../'),
dev: false,
quiet: true,
})
server = await startApp(app)
context.appPort = appPort = server.address().port
})
afterAll(async () => {
await stopApp(server)
await writeFile(nextConfigPath, origNextConfig)
})
it('should not output client pages for AMP only', async () => {
const browser = await webdriver(appPort, '/nav')
await browser.elementByCss('#only-amp-link').click()
const result = await browser.eval('window.NAV_PAGE_LOADED')
expect(result).toBe(null)
})
it('should not output client pages for AMP only with config exported after declaration', async () => {
const browser = await webdriver(appPort, '/nav')
await browser.elementByCss('#var-before-export-link').click()
const result = await browser.eval('window.NAV_PAGE_LOADED')
expect(result).toBe(null)
})
})
describe('AMP dev no-warn', () => { describe('AMP dev no-warn', () => {
let dynamicAppPort let dynamicAppPort
let ampDynamic let ampDynamic
......
...@@ -155,162 +155,3 @@ describe('CSS Module client-side navigation in Production', () => { ...@@ -155,162 +155,3 @@ describe('CSS Module client-side navigation in Production', () => {
} }
}) })
}) })
// TODO: Make webpack 5 work with nest-esm-plugin
describe.skip('CSS Module client-side navigation in Production (Modern)', () => {
const appDir = join(fixturesDir, 'multi-module-modern')
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
let appPort
let app
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
it('should be able to client-side navigate from red to blue', async () => {
let browser
try {
browser = await webdriver(appPort, '/red')
await browser.eval(`window.__did_not_ssr = 'make sure this is set'`)
const redColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-red')).color`
)
expect(redColor).toMatchInlineSnapshot(`"rgb(255, 0, 0)"`)
await browser.elementByCss('#link-blue').click()
await browser.waitForElementByCss('#verify-blue')
const blueColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-blue')).color`
)
expect(blueColor).toMatchInlineSnapshot(`"rgb(0, 0, 255)"`)
expect(await browser.eval(`window.__did_not_ssr`)).toMatchInlineSnapshot(
`"make sure this is set"`
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should be able to client-side navigate from blue to red', async () => {
const content = await renderViaHTTP(appPort, '/blue')
const $ = cheerio.load(content)
// Ensure only `/blue` page's CSS is preloaded
const serverCssPreloads = $('link[rel="preload"][as="style"]')
expect(serverCssPreloads.length).toBe(1)
const serverCssPrefetches = $('link[rel="prefetch"][as="style"]')
expect(serverCssPrefetches.length).toBe(0)
let browser
try {
browser = await webdriver(appPort, '/blue')
await browser.eval(`window.__did_not_ssr = 'make sure this is set'`)
const redColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-blue')).color`
)
expect(redColor).toMatchInlineSnapshot(`"rgb(0, 0, 255)"`)
// Check that Red was preloaded
const result = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="fetch"]')).map(e=>({href:e.href})).sort()`
)
expect(result.length).toBe(1)
// Check that CSS was not loaded as script
const cssPreloads = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=preload][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads.every((e) => e === 'style' || e === 'fetch')).toBe(
true
)
const cssPreloads2 = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=prefetch][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads2.every((e) => e === 'fetch')).toBe(true)
await browser.elementByCss('#link-red').click()
await browser.waitForElementByCss('#verify-red')
const blueColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-red')).color`
)
expect(blueColor).toMatchInlineSnapshot(`"rgb(255, 0, 0)"`)
expect(await browser.eval(`window.__did_not_ssr`)).toMatchInlineSnapshot(
`"make sure this is set"`
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should be able to client-side navigate from none to red', async () => {
let browser
try {
browser = await webdriver(appPort, '/none')
await browser.eval(`window.__did_not_ssr = 'make sure this is set'`)
await browser.elementByCss('#link-red').click()
await browser.waitForElementByCss('#verify-red')
const blueColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-red')).color`
)
expect(blueColor).toMatchInlineSnapshot(`"rgb(255, 0, 0)"`)
expect(await browser.eval(`window.__did_not_ssr`)).toMatchInlineSnapshot(
`"make sure this is set"`
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should be able to client-side navigate from none to blue', async () => {
let browser
try {
browser = await webdriver(appPort, '/none')
await browser.eval(`window.__did_not_ssr = 'make sure this is set'`)
await browser.elementByCss('#link-blue').click()
await browser.waitForElementByCss('#verify-blue')
const blueColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#verify-blue')).color`
)
expect(blueColor).toMatchInlineSnapshot(`"rgb(0, 0, 255)"`)
expect(await browser.eval(`window.__did_not_ssr`)).toMatchInlineSnapshot(
`"make sure this is set"`
)
} finally {
if (browser) {
await browser.close()
}
}
})
})
const parent = require('../next.config')
module.exports = {
...parent,
experimental: {
...parent.experimental,
modern: true,
},
}
import Link from 'next/link'
import { blueText } from './blue.module.css'
export default function Blue() {
return (
<>
<div id="verify-blue" className={blueText}>
This text should be blue.
</div>
<br />
<Link href="/red" prefetch>
<a id="link-red">Red</a>
</Link>
<br />
<Link href="/none" prefetch={false}>
<a id="link-none">None</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function None() {
return (
<>
<div id="verify-black" style={{ color: 'black' }}>
This text should be black.
</div>
<br />
<Link href="/red" prefetch={false}>
<a id="link-red">Red</a>
</Link>
<br />
<Link href="/blue" prefetch={false}>
<a id="link-blue">Blue</a>
</Link>
</>
)
}
import Link from 'next/link'
import { redText } from './red.module.css'
export default function Red() {
return (
<>
<div id="verify-red" className={redText}>
This text should be red.
</div>
<br />
<Link href="/blue" prefetch={false}>
<a id="link-blue">Blue</a>
</Link>
<br />
<Link href="/none" prefetch={false}>
<a id="link-none">None</a>
</Link>
</>
)
}
const parent = require('../next.config') const parent = require('../next.config')
module.exports = { module.exports = { ...parent }
...parent,
experimental: {
...parent.experimental,
modern: false,
},
}
module.exports = {
experimental: {
modern: true,
},
}
...@@ -729,14 +729,11 @@ function runTests(dev) { ...@@ -729,14 +729,11 @@ function runTests(dev) {
for (const el of Array.from($('link[rel="preload"]'))) { for (const el of Array.from($('link[rel="preload"]'))) {
const { href } = el.attribs const { href } = el.attribs
if ( if (href.includes('_buildManifest')) {
href.includes('_buildManifest.js') ||
href.includes('_buildManifest.module.js')
) {
found++ found++
} }
} }
expect(found).toBe(dev ? 2 : 1) expect(found).toBe(1)
}) })
it('should not preload buildManifest for non-auto export dynamic pages', async () => { it('should not preload buildManifest for non-auto export dynamic pages', async () => {
...@@ -746,10 +743,7 @@ function runTests(dev) { ...@@ -746,10 +743,7 @@ function runTests(dev) {
for (const el of Array.from($('link[rel="preload"]'))) { for (const el of Array.from($('link[rel="preload"]'))) {
const { href } = el.attribs const { href } = el.attribs
if ( if (href.includes('_buildManifest')) {
href.includes('_buildManifest.js') ||
href.includes('_buildManifest.module.js')
) {
found++ found++
} }
} }
...@@ -823,17 +817,6 @@ function runTests(dev) { ...@@ -823,17 +817,6 @@ function runTests(dev) {
} }
}) })
} else { } else {
// TODO: Make webpack 5 work with nest-esm-plugin
it.skip('should output modern bundles with dynamic route correctly', async () => {
const buildManifest = require(join('../.next', 'build-manifest.json'))
const files = buildManifest.pages[
'/blog/[name]/comment/[id]'
].filter((filename) => filename.includes('/blog/[name]/comment/[id]'))
expect(files.length).toBe(2)
})
it('should output a routes-manifest correctly', async () => { it('should output a routes-manifest correctly', async () => {
const manifest = await fs.readJson( const manifest = await fs.readJson(
join(appDir, '.next/routes-manifest.json') join(appDir, '.next/routes-manifest.json')
...@@ -1072,6 +1055,8 @@ const nextConfig = join(appDir, 'next.config.js') ...@@ -1072,6 +1055,8 @@ const nextConfig = join(appDir, 'next.config.js')
describe('Dynamic Routing', () => { describe('Dynamic Routing', () => {
describe('dev mode', () => { describe('dev mode', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(nextConfig)
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
buildId = 'development' buildId = 'development'
...@@ -1083,20 +1068,8 @@ describe('Dynamic Routing', () => { ...@@ -1083,20 +1068,8 @@ describe('Dynamic Routing', () => {
describe('production mode', () => { describe('production mode', () => {
beforeAll(async () => { beforeAll(async () => {
const curConfig = await fs.readFile(nextConfig, 'utf8') await fs.remove(nextConfig)
if (curConfig.includes('target')) {
await fs.writeFile(
nextConfig,
`
module.exports = {
experimental: {
modern: true
}
}
`
)
}
await nextBuild(appDir) await nextBuild(appDir)
buildId = await fs.readFile(buildIdPath, 'utf8') buildId = await fs.readFile(buildIdPath, 'utf8')
...@@ -1109,20 +1082,10 @@ describe('Dynamic Routing', () => { ...@@ -1109,20 +1082,10 @@ describe('Dynamic Routing', () => {
}) })
describe('serverless mode', () => { describe('serverless mode', () => {
let origNextConfig
beforeAll(async () => { beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
` `module.exports = { target: 'serverless' }`
module.exports = {
target: 'serverless',
experimental: {
modern: true
}
}
`
) )
await nextBuild(appDir) await nextBuild(appDir)
...@@ -1132,7 +1095,6 @@ describe('Dynamic Routing', () => { ...@@ -1132,7 +1095,6 @@ describe('Dynamic Routing', () => {
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
}) })
afterAll(async () => { afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app) await killApp(app)
}) })
runTests() runTests()
......
module.exports = {
experimental: { modern: true },
}
export default () => <div>Hello World</div>
/* eslint-env jest */
import { join } from 'path'
import rimraf from 'rimraf'
import { promisify } from 'util'
import {
renderViaHTTP,
nextServer,
runNextCommand,
startApp,
stopApp,
} from 'next-test-utils'
import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 5)
const rimrafPromise = promisify(rimraf)
let appDir = join(__dirname, '..')
let server
let appPort
// TODO: Make webpack 5 work with nest-esm-plugin
describe.skip('Modern Mode', () => {
beforeAll(async () => {
await runNextCommand(['build'], {
cwd: appDir,
stdout: true,
stderr: true,
})
const app = nextServer({
dir: appDir,
dev: false,
quiet: true,
experimental: {
modern: true,
},
})
server = await startApp(app)
appPort = server.address().port
})
afterAll(async () => {
stopApp(server)
rimrafPromise(join(appDir, '.next'))
})
it('should generate client side modern and legacy build files', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
const moduleScripts = $('script[src][type=module]').toArray()
const nomoduleScripts = $('script[src][nomodule]').toArray()
const moduleIndex = moduleScripts.find((script) =>
script.attribs.src.includes('pages/index')
)
expect(moduleIndex).toBeDefined()
const nomoduleIndex = nomoduleScripts.find((script) =>
script.attribs.src.includes('pages/index')
)
expect(nomoduleIndex).toBeDefined()
})
})
...@@ -14,7 +14,4 @@ module.exports = { ...@@ -14,7 +14,4 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60, maxInactiveAge: 1000 * 60 * 60,
}, },
experimental: {
modern: true,
},
} }
...@@ -68,9 +68,7 @@ describe('Production response size', () => { ...@@ -68,9 +68,7 @@ describe('Production response size', () => {
it('should not increase the overall response size of default build', async () => { it('should not increase the overall response size of default build', async () => {
const responseSizes = [ const responseSizes = [
baseResponseSize, baseResponseSize,
...(await getResponseSizes( ...(await getResponseSizes(scriptsUrls)),
scriptsUrls.filter((path) => !path.endsWith('.module.js'))
)),
] ]
const responseSizesBytes = getResponseSizesBytes(responseSizes) const responseSizesBytes = getResponseSizesBytes(responseSizes)
console.log( console.log(
...@@ -80,28 +78,9 @@ describe('Production response size', () => { ...@@ -80,28 +78,9 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 283 * 1024 const delta = responseSizesBytes / 1024
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
})
it('should not increase the overall response size of modern build', async () => {
const responseSizes = [
baseResponseSize,
...(await getResponseSizes(
scriptsUrls.filter((path) => path.endsWith('.module.js'))
)),
]
const responseSizesBytes = getResponseSizesBytes(responseSizes)
console.log(
`Response Sizes for modern:\n${responseSizes
.map((obj) => ` ${obj.url}: ${obj.bytes} (bytes)`)
.join('\n')} \nOverall: ${responseSizesBytes} bytes`
)
// These numbers are without gzip compression! // Expected difference: < 0.5
const delta = responseSizesBytes - 173 * 1024 expect(delta).toBeCloseTo(281.4, 0)
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
}) })
}) })
module.exports = { module.exports = { target: 'serverless' }
target: 'serverless',
experimental: {
modern: true,
},
}
...@@ -47,14 +47,7 @@ describe('Dynamic Routing', () => { ...@@ -47,14 +47,7 @@ describe('Dynamic Routing', () => {
const curConfig = await fs.readFile(nextConfig, 'utf8') const curConfig = await fs.readFile(nextConfig, 'utf8')
if (curConfig.includes('target')) { if (curConfig.includes('target')) {
await fs.writeFile( await fs.remove(nextConfig)
nextConfig,
`
module.exports = {
experimental: { modern: true }
}
`
)
} }
await nextBuild(appDir) await nextBuild(appDir)
...@@ -66,18 +59,11 @@ describe('Dynamic Routing', () => { ...@@ -66,18 +59,11 @@ describe('Dynamic Routing', () => {
runTests() runTests()
}) })
describe('SSR production mode', () => { describe('serverless production mode', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
` `module.exports = { target: 'serverless' }`
module.exports = {
target: 'serverless',
experimental: {
modern: true
}
}
`
) )
await nextBuild(appDir) await nextBuild(appDir)
......
module.exports = { module.exports = {}
experimental: {
modern: true,
},
}
...@@ -14,12 +14,7 @@ const dir = path.resolve(os.tmpdir()) ...@@ -14,12 +14,7 @@ const dir = path.resolve(os.tmpdir())
const babel = async ( const babel = async (
code, code,
{ { isServer = false, resourcePath = 'index.js', development = false } = {}
isServer = false,
resourcePath = 'index.js',
hasModern = false,
development = false,
} = {}
) => { ) => {
let isAsync = false let isAsync = false
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
...@@ -56,7 +51,6 @@ const babel = async ( ...@@ -56,7 +51,6 @@ const babel = async (
pagesDir: path.resolve(dir, 'pages'), pagesDir: path.resolve(dir, 'pages'),
cache: false, cache: false,
babelPresetPlugins: [], babelPresetPlugins: [],
hasModern,
development, development,
hasReactRefresh: Boolean(!isServer && development), hasReactRefresh: Boolean(!isServer && development),
}, },
......
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