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 } = {
asyncToPromises: false,
documentMiddleware: false,
publicDirectory: false,
modern: false,
},
serverRuntimeConfig: {},
publicRuntimeConfig: {},
......
......@@ -122,6 +122,19 @@ export default function nextPageConfig({
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 {
getSpecifiedPages,
printTreeView,
PageInfo,
isPageStatic,
hasCustomAppGetInitialProps,
} from './utils'
import getBaseWebpackConfig from './webpack-config'
......
......@@ -32,6 +32,7 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin'
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
......@@ -175,6 +176,11 @@ export default async function getBaseWebpackConfig(
const devtool = dev ? 'cheap-module-source-map' : false
const crossOrigin =
!config.crossOrigin && config.experimental.modern
? 'anonymous'
: config.crossOrigin
let webpackConfig: webpack.Configuration = {
devtool,
mode: webpackMode,
......@@ -365,7 +371,7 @@ export default async function getBaseWebpackConfig(
? `${dev ? '[name]' : '[name].[contenthash]'}.js`
: `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
strictModuleExceptionHandling: true,
crossOriginLoading: config.crossOrigin,
crossOriginLoading: crossOrigin,
futureEmitAssets: !dev,
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
},
......@@ -444,7 +450,7 @@ export default async function getBaseWebpackConfig(
}
}, {}),
'process.env.NODE_ENV': JSON.stringify(webpackMode),
'process.crossOrigin': JSON.stringify(config.crossOrigin),
'process.crossOrigin': JSON.stringify(crossOrigin),
'process.browser': JSON.stringify(!isServer),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...(dev && !isServer
......@@ -455,6 +461,7 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
config.exportTrailingSlash
),
'process.env.__NEXT_MODERN_BUILD': config.experimental.modern && !dev,
...(isServer
? {
// Allow browser-only code to be eliminated
......@@ -568,6 +575,23 @@ export default async function getBaseWebpackConfig(
silent: true,
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),
}
......
......@@ -4,9 +4,38 @@ import babelLoader from 'babel-loader'
// increment 'c' to invalidate cache
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 => {
const presetItem = babel.createConfigItem(require('../../babel/preset'), {
const presetItem = babel.createConfigItem(nextBabelPreset, {
type: 'preset'
})
const applyCommonJs = babel.createConfigItem(
......@@ -24,7 +53,8 @@ module.exports = babelLoader.custom(babel => {
customOptions (opts) {
const custom = {
isServer: opts.isServer,
asyncToPromises: opts.asyncToPromises
asyncToPromises: opts.asyncToPromises,
isModern: opts.isModern
}
const filename = join(opts.cwd, 'noop.js')
const loader = Object.assign(
......@@ -35,6 +65,7 @@ module.exports = babelLoader.custom(babel => {
cacheIdentifier:
cacheKey +
(opts.isServer ? '-server' : '') +
(opts.isModern ? '-modern' : '') +
JSON.stringify(
babel.loadPartialConfig({
filename,
......@@ -53,13 +84,14 @@ module.exports = babelLoader.custom(babel => {
delete loader.asyncToPromises
delete loader.cache
delete loader.distDir
delete loader.isModern
return { loader, custom }
},
config (
cfg,
{
source,
customOptions: { isServer, asyncToPromises }
customOptions: { isServer, asyncToPromises, isModern }
}
) {
const { cwd } = cfg.options
......@@ -104,7 +136,26 @@ module.exports = babelLoader.custom(babel => {
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(
[
'babel-plugin-transform-async-to-promises',
......@@ -128,13 +179,13 @@ module.exports = babelLoader.custom(babel => {
return preset[0] === require('@babel/preset-env').default
})
if (babelPresetEnv) {
babelPresetEnv[1].exclude = (options.presets[0][1].exclude || [])
.concat([
'transform-typeof-symbol',
'transform-regenerator',
'transform-async-to-generator'
])
.filter('transform-typeof-symbol')
babelPresetEnv[1].exclude = (
options.presets[0][1].exclude || []
).concat([
'transform-typeof-symbol',
'transform-regenerator',
'transform-async-to-generator'
])
}
}
......
......@@ -19,8 +19,13 @@ export class DropClientPage implements Plugin {
const page = '/' + cleanAssetKey.split('pages/')[1]
const pageNoExt = page.split(extname(page))[0]
this.ampPages.add(pageNoExt.replace(/\/index$/, '') || '/')
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 {
await this.promisedBuildId
route = this.normalizeRoute(route)
const scriptRoute = route === '/' ? '/index.js' : `${route}.js`
let scriptRoute = route === '/' ? '/index.js' : `${route}.js`
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(
this.buildId
)}/pages${scriptRoute}`
......@@ -165,7 +171,14 @@ export default class PageLoader {
async prefetch (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 (
this.prefetchCache.has(scriptRoute) ||
......
......@@ -105,7 +105,8 @@ export default async function (dir, options, configuration) {
dev: false,
staticMarkup: false,
hotReloader: null,
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || ''
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '',
isModern: nextConfig.experimental.modern
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
......@@ -133,19 +133,24 @@ process.on(
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
const bundlePath = join(
distDir,
'static',
buildId,
'pages',
(path === '/' ? 'index' : path) + '.js'
)
for (const bundleExt of [
'.js',
renderOpts.isModern && '.module.js'
].filter(Boolean)) {
const bundlePath = join(
distDir,
'static',
buildId,
'pages',
(path === '/' ? 'index' : path) + bundleExt
)
const bundleContent = await readFileP(bundlePath, 'utf8')
await writeFileP(
bundlePath,
bundleContent.replace(inlineGipIdentifier, dataStr)
)
const bundleContent = await readFileP(bundlePath, 'utf8')
await writeFileP(
bundlePath,
bundleContent.replace(inlineGipIdentifier, dataStr)
)
}
}
const validateAmp = async (html, page) => {
......
......@@ -40,6 +40,13 @@ function dedupe(bundles: any[]): any[] {
return kept
}
function getOptionalModernScriptVariant(path: string) {
if (process.env.__NEXT_MODERN_BUILD) {
return path.replace(/\.js$/, '.module.js')
}
return path
}
/**
* `Document` component handles the initial `document` markup and renders only on the server side.
* Commonly used for implementing server side rendering for `css-in-js` libraries.
......@@ -157,20 +164,32 @@ export class Head extends Component<
const { dynamicImports, assetPrefix } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
return dedupe(dynamicImports).map((bundle: any) => {
return (
<link
rel="preload"
key={bundle.file}
href={`${assetPrefix}/_next/${
bundle.file
}${_devOnlyInvalidateCacheQueryString}`}
as="script"
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
)
})
return (
dedupe(dynamicImports)
.map((bundle: any) => {
// `dynamicImports` will contain both `.js` and `.modern.js` when the
// feature is enabled. This clause will filter down to the modern
// variants only.
if (!bundle.file.endsWith(getOptionalModernScriptVariant('.js'))) {
return null
}
return (
<link
rel="preload"
key={bundle.file}
href={`${assetPrefix}/_next/${
bundle.file
}${_devOnlyInvalidateCacheQueryString}`}
as="script"
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
)
})
// Filter out nulled scripts
.filter(Boolean)
)
}
getPreloadMainLinks() {
......@@ -180,23 +199,28 @@ export class Head extends Component<
}
const { _devOnlyInvalidateCacheQueryString } = this.context
return files.map((file: string) => {
// Only render .js files here
if (!/\.js$/.exec(file)) {
return null
}
return files
.map((file: string) => {
// `dynamicImports` will contain both `.js` and `.modern.js` when the
// feature is enabled. This clause will filter down to the modern
// variants only.
// This also filters out non-JS assets.
if (!file.endsWith(getOptionalModernScriptVariant('.js'))) {
return null
}
return (
<link
key={file}
nonce={this.props.nonce}
rel="preload"
href={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
as="script"
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
)
})
return (
<link
key={file}
nonce={this.props.nonce}
rel="preload"
href={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
as="script"
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
)
})
.filter(Boolean)
}
render() {
......@@ -366,9 +390,14 @@ export class Head extends Component<
rel="preload"
href={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages${getPageFile(page, buildId)}`
: `/_next/static/${buildId}/pages${getPageFile(page)}`) +
getOptionalModernScriptVariant(
dynamicBuildId
? `/_next/static/client/pages${getPageFile(
page,
buildId
)}`
: `/_next/static/${buildId}/pages${getPageFile(page)}`
) +
_devOnlyInvalidateCacheQueryString
}
as="script"
......@@ -380,9 +409,11 @@ export class Head extends Component<
rel="preload"
href={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages/_app.${buildId}.js`
: `/_next/static/${buildId}/pages/_app.js`) +
getOptionalModernScriptVariant(
dynamicBuildId
? `/_next/static/client/pages/_app.${buildId}.js`
: `/_next/static/${buildId}/pages/_app.js`
) +
_devOnlyInvalidateCacheQueryString
}
as="script"
......@@ -428,11 +459,22 @@ export class NextScript extends Component<OriginProps> {
context!: DocumentComponentContext
// Source: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
static safariNomoduleFix =
'!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();'
getDynamicChunks() {
const { dynamicImports, assetPrefix } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
return dedupe(dynamicImports).map((bundle: any) => {
let modernProps = {}
if (process.env.__NEXT_MODERN_BUILD) {
modernProps = /\.module\.js$/.test(bundle.file)
? { type: 'module' }
: { noModule: true }
}
return (
<script
async
......@@ -442,6 +484,7 @@ export class NextScript extends Component<OriginProps> {
}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
{...modernProps}
/>
)
})
......@@ -460,6 +503,13 @@ export class NextScript extends Component<OriginProps> {
return null
}
let modernProps = {}
if (process.env.__NEXT_MODERN_BUILD) {
modernProps = /\.module\.js$/.test(file)
? { type: 'module' }
: { noModule: true }
}
return (
<script
key={file}
......@@ -467,6 +517,7 @@ export class NextScript extends Component<OriginProps> {
nonce={this.props.nonce}
async
crossOrigin={this.props.crossOrigin || process.crossOrigin}
{...modernProps}
/>
)
})
......@@ -549,6 +600,74 @@ export class NextScript extends Component<OriginProps> {
)
}
const pageScript = [
<script
async
id={`__NEXT_PAGE__${page}`}
src={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages${getPageFile(page, buildId)}`
: `/_next/static/${buildId}/pages${getPageFile(page)}`) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
{...(process.env.__NEXT_MODERN_BUILD ? { noModule: true } : {})}
/>,
process.env.__NEXT_MODERN_BUILD && (
<script
async
id={`__NEXT_PAGE__${page}`}
src={
assetPrefix +
getOptionalModernScriptVariant(
dynamicBuildId
? `/_next/static/client/pages${getPageFile(page, buildId)}`
: `/_next/static/${buildId}/pages${getPageFile(page)}`
) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
type="module"
/>
),
]
const appScript = [
<script
async
id={`__NEXT_PAGE__/_app`}
src={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages/_app.${buildId}.js`
: `/_next/static/${buildId}/pages/_app.js`) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
{...(process.env.__NEXT_MODERN_BUILD ? { noModule: true } : {})}
/>,
process.env.__NEXT_MODERN_BUILD && (
<script
async
id={`__NEXT_PAGE__/_app`}
src={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages/_app.${buildId}.modern.js`
: `/_next/static/${buildId}/pages/_app.modern.js`) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
type="module"
/>
),
]
return (
<>
{devFiles
......@@ -577,34 +696,18 @@ export class NextScript extends Component<OriginProps> {
}}
/>
)}
{page !== '/_error' && (
{process.env.__NEXT_MODERN_BUILD ? (
<script
async
id={`__NEXT_PAGE__${page}`}
src={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages${getPageFile(page, buildId)}`
: `/_next/static/${buildId}/pages${getPageFile(page)}`) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
noModule={true}
dangerouslySetInnerHTML={{
__html: NextScript.safariNomoduleFix,
}}
/>
)}
<script
async
id={`__NEXT_PAGE__/_app`}
src={
assetPrefix +
(dynamicBuildId
? `/_next/static/client/pages/_app.${buildId}.js`
: `/_next/static/${buildId}/pages/_app.js`) +
_devOnlyInvalidateCacheQueryString
}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
) : null}
{page !== '/_error' && pageScript}
{appScript}
{staticMarkup ? null : this.getDynamicChunks()}
{staticMarkup ? null : this.getScripts()}
</>
......
......@@ -1121,6 +1121,11 @@ declare module 'webpack' {
query?: any
}
): string
createChildCompiler(
name: string,
outputOptions: Output,
plugins?: Plugin[]
): Compiler
/**
* @deprecated Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead
*/
......@@ -1171,6 +1176,11 @@ declare module 'webpack' {
namespace ICompiler {
type Handler = (err: Error, stats: Stats) => void
type ChildHandler = (
err: Error,
entries: any[],
childCompilation: compilation.Compilation
) => void
interface WatchOptions {
/**
......@@ -1256,11 +1266,13 @@ declare module 'webpack' {
name: string
options: Configuration
context: string
inputFileSystem: InputFileSystem
outputFileSystem: OutputFileSystem
fileTimestamps: Map<string, number>
contextTimestamps: Map<string, number>
run(handler: Compiler.Handler): void
runAsChild(handler: Compiler.ChildHandler): void
watch(
watchOptions: Compiler.WatchOptions,
handler: Compiler.Handler
......@@ -1269,6 +1281,7 @@ declare module 'webpack' {
namespace Compiler {
type Handler = ICompiler.Handler
type ChildHandler = ICompiler.ChildHandler
type WatchOptions = ICompiler.WatchOptions
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', () => {
context.server = await launchApp(join(__dirname, '../'), context.appPort)
})
afterAll(() => {
context.ws.close()
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 = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
experimental: {
modern: true
}
}
......@@ -7,7 +7,29 @@ import fetch from 'node-fetch'
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', () => {
beforeAll(async () => {
......@@ -17,7 +39,7 @@ describe('Production response size', () => {
await nextBuild(dir)
// Start next app
const server = await startApp(
server = await startApp(
nextServer({
dir,
dev: false,
......@@ -26,49 +48,57 @@ describe('Production response size', () => {
)
// Get the html document
const baseUrl = `http://localhost:${server.address().port}`
let baseUrl = `http://localhost:${server.address().port}`
const htmlResponse = await fetch(baseUrl)
// Find all script urls
const html = await htmlResponse.text()
baseResponseSize = { url: baseUrl, bytes: html.length }
const $ = cheerio.load(html)
const scriptsUrls = $('script[src]')
scriptsUrls = $('script[src]')
.map((i, el) => $(el).attr('src'))
.get()
.map(path => `${baseUrl}${path}`)
})
// Measure the html document and all scripts
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
}
})
)
afterAll(async () => {
// Clean up
await stopApp(server)
})
it('should not increase the overall response size', async () => {
const responseSizeBytes = responseSizes.reduce(
(accumulator, responseSizeObj) => accumulator + responseSizeObj.bytes,
0
it('should not increase the overall response size of default build', async () => {
const responseSizes = [
baseResponseSize,
...(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(
`Response Sizes:\n${responseSizes
`Response Sizes for modern:\n${responseSizes
.map(obj => ` ${obj.url}: ${obj.bytes} (bytes)`)
.join('\n')} \nOverall: ${responseSizeKilobytes} KB`
)
// 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