Commit f4e6149d authored by Janicklas Ralph's avatar Janicklas Ralph Committed by Joe Haddad

Experimental module/nomodule support (#7704)

* Module/nomodule implementation based on RFC 7563

* Remove comment

* Fixing issue with building amp pages

* Fixing test cases for serverless mode

* Adding safari 10 nomodule fix. Preloading modern js by default

* Fixing size-limit integration test

* Bug fix

* Adding testcase for modern build

* Trigger rebuild

* Setting default crossOrigin value

* Moving modern config option inside experimental flag

* Adding nomodule attribute to safari-fix script

* Changing safari10NomoduleFix default value to true

* Removing safari-fix flag

* Changing .es6 to .module

* Disable modern default

* Removing default crossOrigin value. Setting modern flag to false by default. Fixed test cases

* Remove confusing defaults and mark required instead

* Adjust blacklist

* Move behavior of page marking

* Fixing childCompiler errors not being captured

* Tweak names

* Revert

* whoops

* Fixing bug with page-loader.js

* Changing modern babel cache name

* Rename helper

* Iterate over both bundles

* Correctly clamp bundle sizes

* Revert test

* Add modern mode tests

* Fix test

* test

* test2
parent 31385feb
...@@ -39,6 +39,7 @@ const defaultConfig: { [key: string]: any } = { ...@@ -39,6 +39,7 @@ const defaultConfig: { [key: string]: any } = {
asyncToPromises: false, asyncToPromises: false,
documentMiddleware: false, documentMiddleware: false,
publicDirectory: false, publicDirectory: false,
modern: false,
}, },
serverRuntimeConfig: {}, serverRuntimeConfig: {},
publicRuntimeConfig: {}, publicRuntimeConfig: {},
......
...@@ -122,6 +122,19 @@ export default function nextPageConfig({ ...@@ -122,6 +122,19 @@ export default function nextPageConfig({
t.returnStatement(t.stringLiteral(inlineGipIdentifier)), t.returnStatement(t.stringLiteral(inlineGipIdentifier)),
]) ])
}, },
// handles class { static async getInitialProps() {} }
ClassMethod(path, state: ConfigState) {
if (!state.setupInlining) return
if (
(path.node.key && (path.node.key as BabelTypes.Identifier).name) !==
'getInitialProps'
)
return
path.node.body = t.blockStatement([
t.returnStatement(t.stringLiteral(inlineGipIdentifier)),
])
},
}, },
} }
} }
...@@ -27,7 +27,6 @@ import { ...@@ -27,7 +27,6 @@ import {
getSpecifiedPages, getSpecifiedPages,
printTreeView, printTreeView,
PageInfo, PageInfo,
isPageStatic,
hasCustomAppGetInitialProps, hasCustomAppGetInitialProps,
} from './utils' } from './utils'
import getBaseWebpackConfig from './webpack-config' import getBaseWebpackConfig from './webpack-config'
......
...@@ -32,6 +32,7 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' ...@@ -32,6 +32,7 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin' import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index' import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -175,6 +176,11 @@ export default async function getBaseWebpackConfig( ...@@ -175,6 +176,11 @@ export default async function getBaseWebpackConfig(
const devtool = dev ? 'cheap-module-source-map' : false const devtool = dev ? 'cheap-module-source-map' : false
const crossOrigin =
!config.crossOrigin && config.experimental.modern
? 'anonymous'
: config.crossOrigin
let webpackConfig: webpack.Configuration = { let webpackConfig: webpack.Configuration = {
devtool, devtool,
mode: webpackMode, mode: webpackMode,
...@@ -365,7 +371,7 @@ export default async function getBaseWebpackConfig( ...@@ -365,7 +371,7 @@ export default async function getBaseWebpackConfig(
? `${dev ? '[name]' : '[name].[contenthash]'}.js` ? `${dev ? '[name]' : '[name].[contenthash]'}.js`
: `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`, : `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
strictModuleExceptionHandling: true, strictModuleExceptionHandling: true,
crossOriginLoading: config.crossOrigin, crossOriginLoading: crossOrigin,
futureEmitAssets: !dev, futureEmitAssets: !dev,
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm', webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
}, },
...@@ -444,7 +450,7 @@ export default async function getBaseWebpackConfig( ...@@ -444,7 +450,7 @@ export default async function getBaseWebpackConfig(
} }
}, {}), }, {}),
'process.env.NODE_ENV': JSON.stringify(webpackMode), 'process.env.NODE_ENV': JSON.stringify(webpackMode),
'process.crossOrigin': JSON.stringify(config.crossOrigin), 'process.crossOrigin': JSON.stringify(crossOrigin),
'process.browser': JSON.stringify(!isServer), 'process.browser': JSON.stringify(!isServer),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...(dev && !isServer ...(dev && !isServer
...@@ -455,6 +461,7 @@ export default async function getBaseWebpackConfig( ...@@ -455,6 +461,7 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify( 'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
config.exportTrailingSlash config.exportTrailingSlash
), ),
'process.env.__NEXT_MODERN_BUILD': config.experimental.modern && !dev,
...(isServer ...(isServer
? { ? {
// Allow browser-only code to be eliminated // Allow browser-only code to be eliminated
...@@ -568,6 +575,23 @@ export default async function getBaseWebpackConfig( ...@@ -568,6 +575,23 @@ export default async function getBaseWebpackConfig(
silent: true, silent: true,
formatter: 'codeframe', formatter: 'codeframe',
}), }),
config.experimental.modern &&
!isServer &&
!dev &&
new NextEsmPlugin({
filename: (getFileName: Function | string) => (...args: any[]) => {
const name =
typeof getFileName === 'function'
? getFileName(...args)
: getFileName
return name.includes('.js')
? name.replace(/\.js$/, '.module.js')
: args[0].chunk.name.replace(/\.js$/, '.module.js')
},
chunkFilename: (inputChunkName: string) =>
inputChunkName.replace(/\.js$/, '.module.js'),
}),
].filter((Boolean as any) as ExcludesFalse), ].filter((Boolean as any) as ExcludesFalse),
} }
......
...@@ -4,9 +4,38 @@ import babelLoader from 'babel-loader' ...@@ -4,9 +4,38 @@ import babelLoader from 'babel-loader'
// increment 'c' to invalidate cache // increment 'c' to invalidate cache
const cacheKey = 'babel-cache-' + 'c' + '-' const cacheKey = 'babel-cache-' + 'c' + '-'
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 || []),
// Blacklist 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(require('../../babel/preset'), { const presetItem = babel.createConfigItem(nextBabelPreset, {
type: 'preset' type: 'preset'
}) })
const applyCommonJs = babel.createConfigItem( const applyCommonJs = babel.createConfigItem(
...@@ -24,7 +53,8 @@ module.exports = babelLoader.custom(babel => { ...@@ -24,7 +53,8 @@ module.exports = babelLoader.custom(babel => {
customOptions (opts) { customOptions (opts) {
const custom = { const custom = {
isServer: opts.isServer, isServer: opts.isServer,
asyncToPromises: opts.asyncToPromises asyncToPromises: opts.asyncToPromises,
isModern: opts.isModern
} }
const filename = join(opts.cwd, 'noop.js') const filename = join(opts.cwd, 'noop.js')
const loader = Object.assign( const loader = Object.assign(
...@@ -35,6 +65,7 @@ module.exports = babelLoader.custom(babel => { ...@@ -35,6 +65,7 @@ module.exports = babelLoader.custom(babel => {
cacheIdentifier: cacheIdentifier:
cacheKey + cacheKey +
(opts.isServer ? '-server' : '') + (opts.isServer ? '-server' : '') +
(opts.isModern ? '-modern' : '') +
JSON.stringify( JSON.stringify(
babel.loadPartialConfig({ babel.loadPartialConfig({
filename, filename,
...@@ -53,13 +84,14 @@ module.exports = babelLoader.custom(babel => { ...@@ -53,13 +84,14 @@ module.exports = babelLoader.custom(babel => {
delete loader.asyncToPromises delete loader.asyncToPromises
delete loader.cache delete loader.cache
delete loader.distDir delete loader.distDir
delete loader.isModern
return { loader, custom } return { loader, custom }
}, },
config ( config (
cfg, cfg,
{ {
source, source,
customOptions: { isServer, asyncToPromises } customOptions: { isServer, asyncToPromises, isModern }
} }
) { ) {
const { cwd } = cfg.options const { cwd } = cfg.options
...@@ -104,7 +136,26 @@ module.exports = babelLoader.custom(babel => { ...@@ -104,7 +136,26 @@ module.exports = babelLoader.custom(babel => {
options.plugins.push(nextDataPlugin) options.plugins.push(nextDataPlugin)
} }
if (asyncToPromises) { 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 (!isModern && asyncToPromises) {
const asyncToPromisesPlugin = babel.createConfigItem( const asyncToPromisesPlugin = babel.createConfigItem(
[ [
'babel-plugin-transform-async-to-promises', 'babel-plugin-transform-async-to-promises',
...@@ -128,13 +179,13 @@ module.exports = babelLoader.custom(babel => { ...@@ -128,13 +179,13 @@ module.exports = babelLoader.custom(babel => {
return preset[0] === require('@babel/preset-env').default return preset[0] === require('@babel/preset-env').default
}) })
if (babelPresetEnv) { if (babelPresetEnv) {
babelPresetEnv[1].exclude = (options.presets[0][1].exclude || []) babelPresetEnv[1].exclude = (
.concat([ options.presets[0][1].exclude || []
'transform-typeof-symbol', ).concat([
'transform-regenerator', 'transform-typeof-symbol',
'transform-async-to-generator' 'transform-regenerator',
]) 'transform-async-to-generator'
.filter('transform-typeof-symbol') ])
} }
} }
......
...@@ -19,8 +19,13 @@ export class DropClientPage implements Plugin { ...@@ -19,8 +19,13 @@ export class DropClientPage implements Plugin {
const page = '/' + cleanAssetKey.split('pages/')[1] const page = '/' + cleanAssetKey.split('pages/')[1]
const pageNoExt = page.split(extname(page))[0] const pageNoExt = page.split(extname(page))[0]
this.ampPages.add(pageNoExt.replace(/\/index$/, '') || '/')
delete compilation.assets[assetKey] delete compilation.assets[assetKey]
// Detect being re-ran through a child compiler and don't re-mark the
// page as AMP
if (!pageNoExt.endsWith('.module')) {
this.ampPages.add(pageNoExt.replace(/\/index$/, '') || '/')
}
} }
}) })
}) })
......
/**
* MIT License
*
* Copyright (c) 2018 Prateek Bhatnagar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Webpack plugin for NextJs that runs a child compiler to generate a second (modern) JS bundle
*
* @author: Janicklas Ralph (https://github.com/janickals-ralph)
*
* Original source from which this was built upon - https://github.com/prateekbh/babel-esm-plugin
*/
import {
Compiler,
compilation,
Plugin,
RuleSetRule,
RuleSetLoader,
Output,
} from 'webpack'
const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin')
const MultiEntryPlugin = require('webpack/lib/MultiEntryPlugin')
const JsonpTemplatePlugin = require('webpack/lib/web/JsonpTemplatePlugin')
const SplitChunksPlugin = require('webpack/lib/optimize/SplitChunksPlugin')
const RuntimeChunkPlugin = require('webpack/lib/optimize/RuntimeChunkPlugin')
const PLUGIN_NAME = 'NextEsmPlugin'
export default class NextEsmPlugin implements Plugin {
options: {
filename: any
chunkFilename: any
excludedPlugins: string[]
additionalPlugins: Plugin[]
}
constructor(options: {
filename: any
chunkFilename: any
excludedPlugins?: string[]
additionalPlugins?: any
}) {
this.options = Object.assign(
{
excludedPlugins: [PLUGIN_NAME],
additionalPlugins: [],
},
options
)
}
apply(compiler: Compiler) {
compiler.hooks.make.tapAsync(
PLUGIN_NAME,
(compilation: compilation.Compilation, callback) => {
this.runBuild(compiler, compilation).then(callback)
}
)
}
getBabelLoader(rules: RuleSetRule[]) {
for (let rule of rules) {
if (!rule.use) continue
if (Array.isArray(rule.use)) {
return (rule.use as RuleSetLoader[]).find(
r => r.loader && r.loader.includes('next-babel-loader')
)
}
const ruleUse = rule.use as RuleSetLoader
const ruleLoader = rule.loader as string
if (
(ruleUse.loader && ruleUse.loader.includes('next-babel-loader')) ||
(ruleLoader && ruleLoader.includes('next-babel-loader'))
) {
return ruleUse || rule
}
}
}
updateOptions(childCompiler: Compiler) {
if (!childCompiler.options.module) {
throw new Error('Webpack.options.module not found!')
}
let babelLoader = this.getBabelLoader(childCompiler.options.module.rules)
if (!babelLoader) {
throw new Error('Babel-loader config not found!')
}
babelLoader.options = Object.assign({}, babelLoader.options, {
isModern: true,
})
}
updateAssets(
compilation: compilation.Compilation,
childCompilation: compilation.Compilation
) {
compilation.assets = Object.assign(
childCompilation.assets,
compilation.assets
)
compilation.namedChunkGroups = Object.assign(
childCompilation.namedChunkGroups,
compilation.namedChunkGroups
)
const childChunkFileMap = childCompilation.chunks.reduce(
(chunkMap: { [key: string]: any[] }, chunk: compilation.Chunk) => {
chunkMap[chunk.name] = chunk.files
return chunkMap
},
{}
)
compilation.chunks.forEach((chunk: compilation.Chunk) => {
const childChunkFiles = childChunkFileMap[chunk.name]
if (childChunkFiles) {
chunk.files.push(
...childChunkFiles.filter((v: any) => !chunk.files.includes(v))
)
}
})
}
async runBuild(compiler: Compiler, compilation: compilation.Compilation) {
const outputOptions: Output = { ...compiler.options.output }
if (typeof this.options.filename === 'function') {
outputOptions.filename = this.options.filename(outputOptions.filename)
} else {
outputOptions.filename = this.options.filename
}
if (typeof this.options.chunkFilename === 'function') {
outputOptions.chunkFilename = this.options.chunkFilename(
outputOptions.chunkFilename
)
} else {
outputOptions.chunkFilename = this.options.chunkFilename
}
let plugins = (compiler.options.plugins || []).filter(
c => !this.options.excludedPlugins.includes(c.constructor.name)
)
// Add the additionalPlugins
plugins = plugins.concat(this.options.additionalPlugins)
/**
* We are deliberatly not passing plugins in createChildCompiler.
* All webpack does with plugins is to call `apply` method on them
* with the childCompiler.
* But by then we haven't given childCompiler a fileSystem or other options
* which a few plugins might expect while execution the apply method.
* We do call the `apply` method of all plugins by ourselves later in the code
*/
const childCompiler = compilation.createChildCompiler(
PLUGIN_NAME,
outputOptions
)
childCompiler.context = compiler.context
childCompiler.inputFileSystem = compiler.inputFileSystem
childCompiler.outputFileSystem = compiler.outputFileSystem
// Call the `apply` method of all plugins by ourselves.
if (Array.isArray(plugins)) {
for (const plugin of plugins) {
plugin.apply(childCompiler)
}
}
let compilerEntries: any = compiler.options.entry
if (typeof compilerEntries === 'function') {
compilerEntries = await compilerEntries()
}
if (typeof compilerEntries === 'string') {
compilerEntries = { index: compilerEntries }
}
Object.keys(compilerEntries).forEach(entry => {
const entryFiles = compilerEntries[entry]
if (Array.isArray(entryFiles)) {
new MultiEntryPlugin(compiler.context, entryFiles, entry).apply(
childCompiler
)
} else {
new SingleEntryPlugin(compiler.context, entryFiles, entry).apply(
childCompiler
)
}
})
// Convert entry chunk to entry file
new JsonpTemplatePlugin().apply(childCompiler)
const optimization = compiler.options.optimization
if (optimization) {
if (optimization.splitChunks) {
new SplitChunksPlugin(
Object.assign({}, optimization.splitChunks)
).apply(childCompiler)
}
if (optimization.runtimeChunk) {
new RuntimeChunkPlugin(
Object.assign({}, optimization.runtimeChunk)
).apply(childCompiler)
}
}
compilation.hooks.additionalAssets.tapAsync(
PLUGIN_NAME,
childProcessDone => {
this.updateOptions(childCompiler)
childCompiler.runAsChild((err, entries, childCompilation) => {
if (err) {
return childProcessDone(err)
}
if (childCompilation.errors.length > 0) {
return childProcessDone(childCompilation.errors[0])
}
this.updateAssets(compilation, childCompilation)
childProcessDone()
})
}
)
}
}
...@@ -111,9 +111,15 @@ export default class PageLoader { ...@@ -111,9 +111,15 @@ export default class PageLoader {
await this.promisedBuildId await this.promisedBuildId
route = this.normalizeRoute(route) route = this.normalizeRoute(route)
const scriptRoute = route === '/' ? '/index.js' : `${route}.js` let scriptRoute = route === '/' ? '/index.js' : `${route}.js`
const script = document.createElement('script') const script = document.createElement('script')
if (process.env.__NEXT_MODERN_BUILD && 'noModule' in script) {
script.type = 'module'
scriptRoute = scriptRoute.replace(/\.js$/, '.module.js')
}
const url = `${this.assetPrefix}/_next/static/${encodeURIComponent( const url = `${this.assetPrefix}/_next/static/${encodeURIComponent(
this.buildId this.buildId
)}/pages${scriptRoute}` )}/pages${scriptRoute}`
...@@ -165,7 +171,14 @@ export default class PageLoader { ...@@ -165,7 +171,14 @@ export default class PageLoader {
async prefetch (route) { async prefetch (route) {
route = this.normalizeRoute(route) route = this.normalizeRoute(route)
const scriptRoute = `${route === '/' ? '/index' : route}.js` let scriptRoute = `${route === '/' ? '/index' : route}.js`
if (
process.env.__NEXT_MODERN_BUILD &&
'noModule' in document.createElement('script')
) {
scriptRoute = scriptRoute.replace(/\.js$/, '.module.js')
}
if ( if (
this.prefetchCache.has(scriptRoute) || this.prefetchCache.has(scriptRoute) ||
......
...@@ -105,7 +105,8 @@ export default async function (dir, options, configuration) { ...@@ -105,7 +105,8 @@ export default async function (dir, options, configuration) {
dev: false, dev: false,
staticMarkup: false, staticMarkup: false,
hotReloader: null, hotReloader: null,
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '' canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '',
isModern: nextConfig.experimental.modern
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
...@@ -133,19 +133,24 @@ process.on( ...@@ -133,19 +133,24 @@ process.on(
.replace(/"/g, '\\"') .replace(/"/g, '\\"')
.replace(/'/g, "\\'") .replace(/'/g, "\\'")
const bundlePath = join( for (const bundleExt of [
distDir, '.js',
'static', renderOpts.isModern && '.module.js'
buildId, ].filter(Boolean)) {
'pages', const bundlePath = join(
(path === '/' ? 'index' : path) + '.js' distDir,
) 'static',
buildId,
'pages',
(path === '/' ? 'index' : path) + bundleExt
)
const bundleContent = await readFileP(bundlePath, 'utf8') const bundleContent = await readFileP(bundlePath, 'utf8')
await writeFileP( await writeFileP(
bundlePath, bundlePath,
bundleContent.replace(inlineGipIdentifier, dataStr) bundleContent.replace(inlineGipIdentifier, dataStr)
) )
}
} }
const validateAmp = async (html, page) => { const validateAmp = async (html, page) => {
......
This diff is collapsed.
...@@ -1121,6 +1121,11 @@ declare module 'webpack' { ...@@ -1121,6 +1121,11 @@ declare module 'webpack' {
query?: any query?: any
} }
): string ): string
createChildCompiler(
name: string,
outputOptions: Output,
plugins?: Plugin[]
): Compiler
/** /**
* @deprecated Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead * @deprecated Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead
*/ */
...@@ -1171,6 +1176,11 @@ declare module 'webpack' { ...@@ -1171,6 +1176,11 @@ declare module 'webpack' {
namespace ICompiler { namespace ICompiler {
type Handler = (err: Error, stats: Stats) => void type Handler = (err: Error, stats: Stats) => void
type ChildHandler = (
err: Error,
entries: any[],
childCompilation: compilation.Compilation
) => void
interface WatchOptions { interface WatchOptions {
/** /**
...@@ -1256,11 +1266,13 @@ declare module 'webpack' { ...@@ -1256,11 +1266,13 @@ declare module 'webpack' {
name: string name: string
options: Configuration options: Configuration
context: string
inputFileSystem: InputFileSystem inputFileSystem: InputFileSystem
outputFileSystem: OutputFileSystem outputFileSystem: OutputFileSystem
fileTimestamps: Map<string, number> fileTimestamps: Map<string, number>
contextTimestamps: Map<string, number> contextTimestamps: Map<string, number>
run(handler: Compiler.Handler): void run(handler: Compiler.Handler): void
runAsChild(handler: Compiler.ChildHandler): void
watch( watch(
watchOptions: Compiler.WatchOptions, watchOptions: Compiler.WatchOptions,
handler: Compiler.Handler handler: Compiler.Handler
...@@ -1269,6 +1281,7 @@ declare module 'webpack' { ...@@ -1269,6 +1281,7 @@ declare module 'webpack' {
namespace Compiler { namespace Compiler {
type Handler = ICompiler.Handler type Handler = ICompiler.Handler
type ChildHandler = ICompiler.ChildHandler
type WatchOptions = ICompiler.WatchOptions type WatchOptions = ICompiler.WatchOptions
class Watching implements Watching { class Watching implements Watching {
......
module.exports = {
experimental: { modern: true }
}
export default () => <div>Hello World</div>
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import { readFileSync, readdirSync } from 'fs'
import rimraf from 'rimraf'
import { promisify } from 'util'
import { nextServer, runNextCommand, startApp, stopApp } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
const rimrafPromise = promisify(rimraf)
let appDir = join(__dirname, '..')
let server
// let appPort
describe('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 buildId = readFileSync(join(appDir, '.next/BUILD_ID'), 'utf8')
const expectedFiles = [
'index',
'_app',
'_error',
'main',
'webpack',
'commons'
]
const buildFiles = [
...readdirSync(join(appDir, '.next/static', buildId, 'pages')),
...readdirSync(join(appDir, '.next/static/runtime')).map(
file => file.replace(/-\w+\./, '.') // remove hash
),
...readdirSync(join(appDir, '.next/static/chunks')).map(
file => file.replace(/\.\w+\./, '.') // remove hash
)
]
console.log(`Client files: ${buildFiles.join(', ')}`)
expectedFiles.forEach(file => {
expect(buildFiles).toContain(`${file}.js`)
expect(buildFiles).toContain(`${file}.module.js`)
})
})
})
...@@ -46,7 +46,6 @@ describe('On Demand Entries', () => { ...@@ -46,7 +46,6 @@ describe('On Demand Entries', () => {
context.server = await launchApp(join(__dirname, '../'), context.appPort) context.server = await launchApp(join(__dirname, '../'), context.appPort)
}) })
afterAll(() => { afterAll(() => {
context.ws.close()
killApp(context.server) killApp(context.server)
}) })
......
export default () => 'hi'
export const config = { amp: 'hybrid' }
export default () => 'hi'
export const config = { amp: true }
...@@ -13,5 +13,8 @@ module.exports = { ...@@ -13,5 +13,8 @@ module.exports = {
onDemandEntries: { onDemandEntries: {
// 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
} }
} }
...@@ -7,7 +7,29 @@ import fetch from 'node-fetch' ...@@ -7,7 +7,29 @@ import fetch from 'node-fetch'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
let responseSizes let server
let scriptsUrls
let baseResponseSize
function getResponseSizes (resourceUrls) {
return Promise.all(
resourceUrls.map(async url => {
const context = await fetch(url).then(res => res.text())
return {
url,
bytes: context.length
}
})
)
}
function getResponseSizesKB (responseSizes) {
const responseSizeBytes = responseSizes.reduce(
(accumulator, responseSizeObj) => accumulator + responseSizeObj.bytes,
0
)
return Math.ceil(responseSizeBytes / 1024)
}
describe('Production response size', () => { describe('Production response size', () => {
beforeAll(async () => { beforeAll(async () => {
...@@ -17,7 +39,7 @@ describe('Production response size', () => { ...@@ -17,7 +39,7 @@ describe('Production response size', () => {
await nextBuild(dir) await nextBuild(dir)
// Start next app // Start next app
const server = await startApp( server = await startApp(
nextServer({ nextServer({
dir, dir,
dev: false, dev: false,
...@@ -26,49 +48,57 @@ describe('Production response size', () => { ...@@ -26,49 +48,57 @@ describe('Production response size', () => {
) )
// Get the html document // Get the html document
const baseUrl = `http://localhost:${server.address().port}` let baseUrl = `http://localhost:${server.address().port}`
const htmlResponse = await fetch(baseUrl) const htmlResponse = await fetch(baseUrl)
// Find all script urls // Find all script urls
const html = await htmlResponse.text() const html = await htmlResponse.text()
baseResponseSize = { url: baseUrl, bytes: html.length }
const $ = cheerio.load(html) const $ = cheerio.load(html)
const scriptsUrls = $('script[src]') scriptsUrls = $('script[src]')
.map((i, el) => $(el).attr('src')) .map((i, el) => $(el).attr('src'))
.get() .get()
.map(path => `${baseUrl}${path}`) .map(path => `${baseUrl}${path}`)
})
// Measure the html document and all scripts afterAll(async () => {
const resourceUrls = [baseUrl, ...scriptsUrls]
// Fetch all resources and get their size (bytes)
responseSizes = await Promise.all(
resourceUrls.map(async url => {
const context = await fetch(url).then(res => res.text())
return {
url,
bytes: context.length
}
})
)
// Clean up // Clean up
await stopApp(server) await stopApp(server)
}) })
it('should not increase the overall response size', async () => { it('should not increase the overall response size of default build', async () => {
const responseSizeBytes = responseSizes.reduce( const responseSizes = [
(accumulator, responseSizeObj) => accumulator + responseSizeObj.bytes, baseResponseSize,
0 ...(await getResponseSizes(
scriptsUrls.filter(path => !path.endsWith('.module.js'))
))
]
const responseSizeKilobytes = getResponseSizesKB(responseSizes)
console.log(
`Response Sizes for default:\n${responseSizes
.map(obj => ` ${obj.url}: ${obj.bytes} (bytes)`)
.join('\n')} \nOverall: ${responseSizeKilobytes} KB`
) )
const responseSizeKilobytes = Math.ceil(responseSizeBytes / 1024)
// These numbers are without gzip compression!
expect(responseSizeKilobytes).toBeLessThanOrEqual(213) // Kilobytes
})
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 responseSizeKilobytes = getResponseSizesKB(responseSizes)
console.log( console.log(
`Response Sizes:\n${responseSizes `Response Sizes for modern:\n${responseSizes
.map(obj => ` ${obj.url}: ${obj.bytes} (bytes)`) .map(obj => ` ${obj.url}: ${obj.bytes} (bytes)`)
.join('\n')} \nOverall: ${responseSizeKilobytes} KB` .join('\n')} \nOverall: ${responseSizeKilobytes} KB`
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
expect(responseSizeKilobytes).toBeLessThanOrEqual(216) // Kilobytes expect(responseSizeKilobytes).toBeLessThanOrEqual(186) // Kilobytes
}) })
}) })
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