Unverified Commit ee220730 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fixes to allow lazy compilation for import() (#32441)

parent 67545bd6
...@@ -12,6 +12,7 @@ examples/with-jest/** ...@@ -12,6 +12,7 @@ examples/with-jest/**
examples/with-mobx-state-tree/** examples/with-mobx-state-tree/**
examples/with-mobx/** examples/with-mobx/**
packages/next/bundles/webpack/packages/*.runtime.js packages/next/bundles/webpack/packages/*.runtime.js
packages/next/bundles/webpack/packages/lazy-compilation-*.js
packages/next/compiled/**/* packages/next/compiled/**/*
packages/react-refresh-utils/**/*.js packages/react-refresh-utils/**/*.js
packages/react-dev-overlay/lib/** packages/react-dev-overlay/lib/**
......
...@@ -3,6 +3,7 @@ node_modules ...@@ -3,6 +3,7 @@ node_modules
**/_next/** **/_next/**
**/dist/** **/dist/**
packages/next/bundles/webpack/packages/*.runtime.js packages/next/bundles/webpack/packages/*.runtime.js
packages/next/bundles/webpack/packages/lazy-compilation-*.js
packages/next/compiled/** packages/next/compiled/**
packages/react-refresh-utils/**/*.js packages/react-refresh-utils/**/*.js
packages/react-refresh-utils/**/*.d.ts packages/react-refresh-utils/**/*.d.ts
......
...@@ -79,6 +79,9 @@ pub struct TransformOptions { ...@@ -79,6 +79,9 @@ pub struct TransformOptions {
#[serde(default)] #[serde(default)]
pub is_development: bool, pub is_development: bool,
#[serde(default)]
pub is_server: bool,
#[serde(default)] #[serde(default)]
pub styled_components: Option<styled_components::Config>, pub styled_components: Option<styled_components::Config>,
...@@ -113,7 +116,12 @@ pub fn custom_before_pass(file: Arc<SourceFile>, opts: &TransformOptions) -> imp ...@@ -113,7 +116,12 @@ pub fn custom_before_pass(file: Arc<SourceFile>, opts: &TransformOptions) -> imp
}, },
Optional::new(next_ssg::next_ssg(), !opts.disable_next_ssg), Optional::new(next_ssg::next_ssg(), !opts.disable_next_ssg),
amp_attributes::amp_attributes(), amp_attributes::amp_attributes(),
next_dynamic::next_dynamic(file.name.clone(), opts.pages_dir.clone()), next_dynamic::next_dynamic(
opts.is_development,
opts.is_server,
file.name.clone(),
opts.pages_dir.clone()
),
Optional::new( Optional::new(
page_config::page_config(opts.is_development, opts.is_page_file), page_config::page_config(opts.is_development, opts.is_page_file),
!opts.disable_page_config !opts.disable_page_config
......
...@@ -32,6 +32,8 @@ fn next_dynamic_errors(input: PathBuf) { ...@@ -32,6 +32,8 @@ fn next_dynamic_errors(input: PathBuf) {
syntax(), syntax(),
&|_tr| { &|_tr| {
next_dynamic( next_dynamic(
true,
false,
FileName::Real(PathBuf::from("/some-project/src/some-file.js")), FileName::Real(PathBuf::from("/some-project/src/some-file.js")),
Some("/some-project/src".into()), Some("/some-project/src".into()),
) )
......
...@@ -33,17 +33,33 @@ fn amp_attributes_fixture(input: PathBuf) { ...@@ -33,17 +33,33 @@ fn amp_attributes_fixture(input: PathBuf) {
#[fixture("tests/fixture/next-dynamic/**/input.js")] #[fixture("tests/fixture/next-dynamic/**/input.js")]
fn next_dynamic_fixture(input: PathBuf) { fn next_dynamic_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output_dev = input.parent().unwrap().join("output-dev.js");
let output_prod = input.parent().unwrap().join("output-prod.js");
test_fixture( test_fixture(
syntax(), syntax(),
&|_tr| { &|_tr| {
next_dynamic( next_dynamic(
true,
false,
FileName::Real(PathBuf::from("/some-project/src/some-file.js")), FileName::Real(PathBuf::from("/some-project/src/some-file.js")),
Some("/some-project/src".into()), Some("/some-project/src".into()),
) )
}, },
&input, &input,
&output, &output_dev,
);
test_fixture(
syntax(),
&|_tr| {
next_dynamic(
false,
false,
FileName::Real(PathBuf::from("/some-project/src/some-file.js")),
Some("/some-project/src".into()),
)
},
&input,
&output_prod,
); );
} }
......
import dynamic1 from 'next/dynamic'
import dynamic2 from 'next/dynamic'
const DynamicComponent1 = dynamic1(() => import('../components/hello1'), {
loadableGenerated: {
modules: ['some-file.js -> ' + '../components/hello1'],
},
})
const DynamicComponent2 = dynamic2(() => import('../components/hello2'), {
loadableGenerated: {
modules: ['some-file.js -> ' + '../components/hello2'],
},
})
...@@ -3,12 +3,10 @@ import dynamic2 from 'next/dynamic' ...@@ -3,12 +3,10 @@ import dynamic2 from 'next/dynamic'
const DynamicComponent1 = dynamic1(() => import('../components/hello1'), { const DynamicComponent1 = dynamic1(() => import('../components/hello1'), {
loadableGenerated: { loadableGenerated: {
webpack: () => [require.resolveWeak('../components/hello1')], webpack: () => [require.resolveWeak('../components/hello1')],
modules: ['some-file.js -> ' + '../components/hello1'],
}, },
}) })
const DynamicComponent2 = dynamic2(() => import('../components/hello2'), { const DynamicComponent2 = dynamic2(() => import('../components/hello2'), {
loadableGenerated: { loadableGenerated: {
webpack: () => [require.resolveWeak('../components/hello2')], webpack: () => [require.resolveWeak('../components/hello2')],
modules: ['some-file.js -> ' + '../components/hello2'],
}, },
}) })
import dynamic from 'next/dynamic'
import somethingElse from 'something-else'
const DynamicComponent = dynamic(() => import('../components/hello'), {
loadableGenerated: {
modules: ['some-file.js -> ' + '../components/hello'],
},
})
somethingElse.dynamic('should not be transformed')
...@@ -3,7 +3,6 @@ import somethingElse from 'something-else' ...@@ -3,7 +3,6 @@ import somethingElse from 'something-else'
const DynamicComponent = dynamic(() => import('../components/hello'), { const DynamicComponent = dynamic(() => import('../components/hello'), {
loadableGenerated: { loadableGenerated: {
webpack: () => [require.resolveWeak('../components/hello')], webpack: () => [require.resolveWeak('../components/hello')],
modules: ['some-file.js -> ' + '../components/hello'],
}, },
}) })
somethingElse.dynamic('should not be transformed') somethingElse.dynamic('should not be transformed')
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/hello'), {
loadableGenerated: {
modules: ['some-file.js -> ' + '../components/hello'],
},
})
...@@ -2,6 +2,5 @@ import dynamic from 'next/dynamic' ...@@ -2,6 +2,5 @@ import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/hello'), { const DynamicComponent = dynamic(() => import('../components/hello'), {
loadableGenerated: { loadableGenerated: {
webpack: () => [require.resolveWeak('../components/hello')], webpack: () => [require.resolveWeak('../components/hello')],
modules: ['some-file.js -> ' + '../components/hello'],
}, },
}) })
import dynamic from "next/dynamic";
const DynamicComponentWithCustomLoading = dynamic(()=>import("../components/hello")
, {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
]
},
loading: ()=><p >...</p>
});
...@@ -5,10 +5,6 @@ const DynamicComponentWithCustomLoading = dynamic(()=>import("../components/hell ...@@ -5,10 +5,6 @@ const DynamicComponentWithCustomLoading = dynamic(()=>import("../components/hell
webpack: ()=>[ webpack: ()=>[
require.resolveWeak("../components/hello") require.resolveWeak("../components/hello")
] ]
,
modules: [
"some-file.js -> " + "../components/hello"
]
}, },
loading: ()=><p >...</p> loading: ()=><p >...</p>
}); });
import dynamic from "next/dynamic";
const DynamicComponent = dynamic(()=>handleImport(import("./components/hello"))
, {
loadableGenerated: {
modules: [
"some-file.js -> " + "./components/hello"
]
},
loading: ()=>null
,
ssr: false
});
\ No newline at end of file
...@@ -5,10 +5,6 @@ const DynamicComponent = dynamic(()=>handleImport(import("./components/hello")) ...@@ -5,10 +5,6 @@ const DynamicComponent = dynamic(()=>handleImport(import("./components/hello"))
webpack: ()=>[ webpack: ()=>[
require.resolveWeak("./components/hello") require.resolveWeak("./components/hello")
] ]
,
modules: [
"some-file.js -> " + "./components/hello"
]
}, },
loading: ()=>null loading: ()=>null
, ,
......
...@@ -55,6 +55,7 @@ fn test(input: &Path, minify: bool) { ...@@ -55,6 +55,7 @@ fn test(input: &Path, minify: bool) {
pages_dir: None, pages_dir: None,
is_page_file: false, is_page_file: false,
is_development: true, is_development: true,
is_server: false,
styled_components: Some(assert_json("{}")), styled_components: Some(assert_json("{}")),
remove_console: None, remove_console: None,
react_remove_properties: None, react_remove_properties: None,
......
...@@ -168,29 +168,35 @@ export default function ({ ...@@ -168,29 +168,35 @@ export default function ({
options.node.properties.push( options.node.properties.push(
t.objectProperty( t.objectProperty(
t.identifier('loadableGenerated'), t.identifier('loadableGenerated'),
t.objectExpression([ t.objectExpression(
t.objectProperty( state.file.opts.caller?.isDev ||
t.identifier('webpack'), state.file.opts.caller?.isServer
t.arrowFunctionExpression( ? [
[], t.objectProperty(
t.arrayExpression( t.identifier('modules'),
dynamicImports.map((dynamicImport) => { t.arrayExpression(dynamicKeys)
return t.callExpression( ),
t.memberExpression( ]
t.identifier('require'), : [
t.identifier('resolveWeak') t.objectProperty(
), t.identifier('webpack'),
[dynamicImport] t.arrowFunctionExpression(
[],
t.arrayExpression(
dynamicImports.map((dynamicImport) => {
return t.callExpression(
t.memberExpression(
t.identifier('require'),
t.identifier('resolveWeak')
),
[dynamicImport]
)
})
)
) )
}) ),
) ]
) )
),
t.objectProperty(
t.identifier('modules'),
t.arrayExpression(dynamicKeys)
),
])
) )
) )
......
...@@ -141,6 +141,7 @@ export function getLoaderSWCOptions({ ...@@ -141,6 +141,7 @@ export function getLoaderSWCOptions({
disableNextSsg: true, disableNextSsg: true,
disablePageConfig: true, disablePageConfig: true,
isDevelopment: development, isDevelopment: development,
isServer,
pagesDir, pagesDir,
isPageFile, isPageFile,
env: { env: {
...@@ -165,6 +166,7 @@ export function getLoaderSWCOptions({ ...@@ -165,6 +166,7 @@ export function getLoaderSWCOptions({
: {}), : {}),
disableNextSsg: !isPageFile, disableNextSsg: !isPageFile,
isDevelopment: development, isDevelopment: development,
isServer,
pagesDir, pagesDir,
isPageFile, isPageFile,
} }
......
...@@ -1402,6 +1402,7 @@ export default async function getBaseWebpackConfig( ...@@ -1402,6 +1402,7 @@ export default async function getBaseWebpackConfig(
runtimeAsset: hasConcurrentFeatures runtimeAsset: hasConcurrentFeatures
? `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js` ? `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`
: undefined, : undefined,
dev,
}), }),
targetWeb && new DropClientPage(), targetWeb && new DropClientPage(),
config.outputFileTracing && config.outputFileTracing &&
...@@ -1733,6 +1734,21 @@ export default async function getBaseWebpackConfig( ...@@ -1733,6 +1734,21 @@ export default async function getBaseWebpackConfig(
devtoolRevertWarning(originalDevtool) devtoolRevertWarning(originalDevtool)
} }
// eslint-disable-next-line no-shadow
const webpack5Config = webpackConfig as webpack5.Configuration
// disable lazy compilation of entries as next.js has it's own method here
if (webpack5Config.experiments?.lazyCompilation === true) {
webpack5Config.experiments.lazyCompilation = {
entries: false,
}
} else if (
typeof webpack5Config.experiments?.lazyCompilation === 'object' &&
webpack5Config.experiments.lazyCompilation.entries !== false
) {
webpack5Config.experiments.lazyCompilation.entries = false
}
if (typeof (webpackConfig as any).then === 'function') { if (typeof (webpackConfig as any).then === 'function') {
console.warn( console.warn(
'> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config' '> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config'
......
...@@ -53,7 +53,8 @@ function getChunkGroupFromBlock( ...@@ -53,7 +53,8 @@ function getChunkGroupFromBlock(
function buildManifest( function buildManifest(
_compiler: webpack.Compiler, _compiler: webpack.Compiler,
compilation: webpack.compilation.Compilation, compilation: webpack.compilation.Compilation,
pagesDir: string pagesDir: string,
dev: boolean
) { ) {
let manifest: { [k: string]: { id: string | number; files: string[] } } = {} let manifest: { [k: string]: { id: string | number; files: string[] } } = {}
...@@ -125,7 +126,7 @@ function buildManifest( ...@@ -125,7 +126,7 @@ function buildManifest(
// next/dynamic so they are loaded by the same technique // next/dynamic so they are loaded by the same technique
// add the id and files to the manifest // add the id and files to the manifest
const id = getModuleId(compilation, module) const id = dev ? key : getModuleId(compilation, module)
manifest[key] = { id, files: Array.from(files) } manifest[key] = { id, files: Array.from(files) }
} }
} }
...@@ -146,19 +147,27 @@ export class ReactLoadablePlugin { ...@@ -146,19 +147,27 @@ export class ReactLoadablePlugin {
private filename: string private filename: string
private pagesDir: string private pagesDir: string
private runtimeAsset?: string private runtimeAsset?: string
private dev: boolean
constructor(opts: { constructor(opts: {
filename: string filename: string
pagesDir: string pagesDir: string
runtimeAsset?: string runtimeAsset?: string
dev: boolean
}) { }) {
this.filename = opts.filename this.filename = opts.filename
this.pagesDir = opts.pagesDir this.pagesDir = opts.pagesDir
this.runtimeAsset = opts.runtimeAsset this.runtimeAsset = opts.runtimeAsset
this.dev = opts.dev
} }
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
const manifest = buildManifest(compiler, compilation, this.pagesDir) const manifest = buildManifest(
compiler,
compilation,
this.pagesDir,
this.dev
)
// @ts-ignore: TODO: remove when webpack 5 is stable // @ts-ignore: TODO: remove when webpack 5 is stable
assets[this.filename] = new sources.RawSource( assets[this.filename] = new sources.RawSource(
JSON.stringify(manifest, null, 2) JSON.stringify(manifest, null, 2)
......
/* global __resourceQuery */
"use strict";
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
exports.keepAlive = function (options) {
var data = options.data;
var onError = options.onError;
var active = options.active;
var module = options.module;
var response;
var request = (
urlBase.startsWith("https") ? require("https") : require("http")
).request(
urlBase + data,
{
agent: false,
headers: { accept: "text/event-stream" }
},
function (res) {
response = res;
response.on("error", errorHandler);
if (!active && !module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
}
);
function errorHandler(err) {
err.message =
"Problem communicating active modules to the server: " + err.message;
onError(err);
}
request.on("error", errorHandler);
request.end();
return function () {
response.destroy();
};
};
/* global __resourceQuery */
"use strict";
if (typeof EventSource !== "function") {
throw new Error(
"Environment doesn't support lazy compilation (requires EventSource)"
);
}
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
var activeEventSource;
var activeKeys = new Map();
var errorHandlers = new Set();
var updateEventSource = function updateEventSource() {
if (activeEventSource) activeEventSource.close();
if (activeKeys.size) {
activeEventSource = new EventSource(
urlBase + Array.from(activeKeys.keys()).join("@")
);
activeEventSource.onerror = function (event) {
errorHandlers.forEach(function (onError) {
onError(
new Error(
"Problem communicating active modules to the server: " +
event.message +
" " +
event.filename +
":" +
event.lineno +
":" +
event.colno +
" " +
event.error
)
);
});
};
} else {
activeEventSource = undefined;
}
};
exports.keepAlive = function (options) {
var data = options.data;
var onError = options.onError;
var active = options.active;
var module = options.module;
errorHandlers.add(onError);
var value = activeKeys.get(data) || 0;
activeKeys.set(data, value + 1);
if (value === 0) {
updateEventSource();
}
if (!active && !module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
return function () {
errorHandlers.delete(onError);
setTimeout(function () {
var value = activeKeys.get(data);
if (value === 1) {
activeKeys.delete(data);
updateEventSource();
} else {
activeKeys.set(data, value - 1);
}
}, 1000);
};
};
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 685:
/***/ (function(module) {
module.exports = require("http");
/***/ }),
/***/ 687:
/***/ (function(module) {
module.exports = require("https");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
!function() {
var exports = __webpack_exports__;
var __resourceQuery = "";
/* global __resourceQuery */ /* global __resourceQuery */
"use strict";
var urlBase = decodeURIComponent(__resourceQuery.slice(1)); var urlBase = decodeURIComponent(__resourceQuery.slice(1));
exports.keepAlive = function (options) { exports.keepAlive = function (options) {
...@@ -71,7 +10,7 @@ exports.keepAlive = function (options) { ...@@ -71,7 +10,7 @@ exports.keepAlive = function (options) {
var module = options.module; var module = options.module;
var response; var response;
var request = ( var request = (
urlBase.startsWith("https") ? __nccwpck_require__(687) : __nccwpck_require__(685) urlBase.startsWith("https") ? require("https") : require("http")
).request( ).request(
urlBase + data, urlBase + data,
{ {
...@@ -99,8 +38,3 @@ exports.keepAlive = function (options) { ...@@ -99,8 +38,3 @@ exports.keepAlive = function (options) {
response.destroy(); response.destroy();
}; };
}; };
}();
module.exports = __webpack_exports__;
/******/ })()
;
\ No newline at end of file
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
!function() {
var exports = __webpack_exports__;
var __resourceQuery = "";
/* global __resourceQuery */ /* global __resourceQuery */
"use strict";
if (typeof EventSource !== "function") { if (typeof EventSource !== "function") {
throw new Error( throw new Error(
...@@ -84,8 +72,3 @@ exports.keepAlive = function (options) { ...@@ -84,8 +72,3 @@ exports.keepAlive = function (options) {
}, 1000); }, 1000);
}; };
}; };
}();
module.exports = __webpack_exports__;
/******/ })()
;
\ No newline at end of file
...@@ -95,21 +95,17 @@ function createLoadableComponent(loadFn, options) { ...@@ -95,21 +95,17 @@ function createLoadableComponent(loadFn, options) {
} }
// Client only // Client only
if ( if (!initialized && typeof window !== 'undefined' && !opts.suspense) {
!initialized && const moduleIds = opts.webpack ? opts.webpack() : opts.modules
typeof window !== 'undefined' && if (moduleIds) {
typeof opts.webpack === 'function' && READY_INITIALIZERS.push((ids) => {
typeof require.resolveWeak === 'function' && for (const moduleId of moduleIds) {
!opts.suspense if (ids.indexOf(moduleId) !== -1) {
) { return init()
const moduleIds = opts.webpack() }
READY_INITIALIZERS.push((ids) => {
for (const moduleId of moduleIds) {
if (ids.indexOf(moduleId) !== -1) {
return init()
} }
} })
}) }
} }
function LoadableImpl(props, ref) { function LoadableImpl(props, ref) {
......
...@@ -1007,7 +1007,6 @@ export async function ncc(task, opts) { ...@@ -1007,7 +1007,6 @@ export async function ncc(task, opts) {
'ncc_unistore', 'ncc_unistore',
'ncc_web_vitals', 'ncc_web_vitals',
'ncc_webpack_bundle5', 'ncc_webpack_bundle5',
'ncc_webpack_bundle_packages',
'ncc_webpack_sources1', 'ncc_webpack_sources1',
'ncc_webpack_sources3', 'ncc_webpack_sources3',
'ncc_ws', 'ncc_ws',
...@@ -1021,6 +1020,7 @@ export async function ncc(task, opts) { ...@@ -1021,6 +1020,7 @@ export async function ncc(task, opts) {
], ],
opts opts
) )
await task.parallel(['ncc_webpack_bundle_packages'], opts)
await task.parallel(['ncc_babel_bundle_packages'], opts) await task.parallel(['ncc_babel_bundle_packages'], opts)
await task.parallel(['copy_react_server_dom_webpack']) await task.parallel(['copy_react_server_dom_webpack'])
} }
......
copy node_modules\webpack5\lib\hmr\HotModuleReplacement.runtime.js packages\next\bundles\webpack\packages\
copy node_modules\webpack5\lib\hmr\JavascriptHotModuleReplacement.runtime.js packages\next\bundles\webpack\packages\
copy node_modules\webpack5\hot\lazy-compilation-node.js packages\next\bundles\webpack\packages\
copy node_modules\webpack5\hot\lazy-compilation-web.js packages\next\bundles\webpack\packages\
yarn --cwd packages/next ncc-compiled
rem Make sure to exit with 1 if there are changes after running ncc-compiled
rem step to ensure we get any changes committed
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
cp node_modules/webpack5/lib/hmr/HotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/ cp node_modules/webpack5/lib/hmr/HotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp node_modules/webpack5/lib/hmr/JavascriptHotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/ cp node_modules/webpack5/lib/hmr/JavascriptHotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp node_modules/webpack5/hot/lazy-compilation-node.js packages/next/bundles/webpack/packages/
cp node_modules/webpack5/hot/lazy-compilation-web.js packages/next/bundles/webpack/packages/
yarn --cwd packages/next ncc-compiled yarn --cwd packages/next ncc-compiled
# Make sure to exit with 1 if there are changes after running ncc-compiled # Make sure to exit with 1 if there are changes after running ncc-compiled
......
...@@ -32,7 +32,7 @@ describe('basic next/dynamic usage', () => { ...@@ -32,7 +32,7 @@ describe('basic next/dynamic usage', () => {
const $ = await get$('/docs/dynamic/ssr') const $ = await get$('/docs/dynamic/ssr')
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain( expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain(
'./components/hello1.js' 'dynamic/ssr.js -> ../../components/hello1'
) )
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
...@@ -41,7 +41,7 @@ describe('basic next/dynamic usage', () => { ...@@ -41,7 +41,7 @@ describe('basic next/dynamic usage', () => {
const $ = await get$('/docs/dynamic/function') const $ = await get$('/docs/dynamic/function')
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain( expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain(
'./components/hello1.js' 'dynamic/function.js -> ../../components/hello1'
) )
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
......
...@@ -29,7 +29,7 @@ describe('basic next/dynamic usage', () => { ...@@ -29,7 +29,7 @@ describe('basic next/dynamic usage', () => {
const $ = await get$('/dynamic/ssr') const $ = await get$('/dynamic/ssr')
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain( expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain(
'./components/hello1.js' 'dynamic/ssr.js -> ../../components/hello1'
) )
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
...@@ -38,7 +38,7 @@ describe('basic next/dynamic usage', () => { ...@@ -38,7 +38,7 @@ describe('basic next/dynamic usage', () => {
const $ = await get$('/dynamic/function') const $ = await get$('/dynamic/function')
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain( expect(JSON.parse($('#__NEXT_DATA__').html()).dynamicIds).toContain(
'./components/hello1.js' 'dynamic/function.js -> ../../components/hello1'
) )
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
......
...@@ -7,7 +7,6 @@ import { killApp, findPort, launchApp, check } from 'next-test-utils' ...@@ -7,7 +7,6 @@ import { killApp, findPort, launchApp, check } from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const appPage = join(appDir, 'pages/_app.js') const appPage = join(appDir, 'pages/_app.js')
const indexPage = join(appDir, 'pages/index.js')
const documentPage = join(appDir, 'pages/_document.js') const documentPage = join(appDir, 'pages/_document.js')
let appPort let appPort
...@@ -21,10 +20,8 @@ describe('_app/_document add HMR', () => { ...@@ -21,10 +20,8 @@ describe('_app/_document add HMR', () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
it('should HMR when _app is added', async () => { it('should HMR when _app is added', async () => {
let indexContent = await fs.readFile(indexPage) const browser = await webdriver(appPort, '/')
try { try {
const browser = await webdriver(appPort, '/')
const html = await browser.eval('document.documentElement.innerHTML') const html = await browser.eval('document.documentElement.innerHTML')
expect(html).not.toContain('custom _app') expect(html).not.toContain('custom _app')
expect(html).toContain('index page') expect(html).toContain('index page')
...@@ -50,16 +47,19 @@ describe('_app/_document add HMR', () => { ...@@ -50,16 +47,19 @@ describe('_app/_document add HMR', () => {
: html : html
}, 'success') }, 'success')
} finally { } finally {
await fs.writeFile(indexPage, indexContent)
await fs.remove(appPage) await fs.remove(appPage)
await check(async () => {
const html = await browser.eval('document.documentElement.innerHTML')
return !html.includes('custom _app') && html.includes('index page')
? 'restored'
: html
}, 'restored')
} }
}) })
it('should HMR when _document is added', async () => { it('should HMR when _document is added', async () => {
let indexContent = await fs.readFile(indexPage) const browser = await webdriver(appPort, '/')
try { try {
const browser = await webdriver(appPort, '/')
const html = await browser.eval('document.documentElement.innerHTML') const html = await browser.eval('document.documentElement.innerHTML')
expect(html).not.toContain('custom _document') expect(html).not.toContain('custom _document')
expect(html).toContain('index page') expect(html).toContain('index page')
...@@ -101,8 +101,13 @@ describe('_app/_document add HMR', () => { ...@@ -101,8 +101,13 @@ describe('_app/_document add HMR', () => {
: html : html
}, 'success') }, 'success')
} finally { } finally {
await fs.writeFile(indexPage, indexContent)
await fs.remove(documentPage) await fs.remove(documentPage)
await check(async () => {
const html = await browser.eval('document.documentElement.innerHTML')
return !html.includes('custom _document') && html.includes('index page')
? 'restored'
: html
}, 'restored')
} }
}) })
}) })
import something from '../apples'
export default () => {
// have to do something with module so it is not tree shaken
console.log(something)
return '1'
}
import something from '../apples'
export default () => {
// have to do something with module so it is not tree shaken
console.log(something)
return '2'
}
module.exports = {
webpack(config, { isServer, dev }) {
if (!isServer && dev) {
config.experiments.lazyCompilation = true
}
return config
},
}
import dynamic from 'next/dynamic'
import { useState, useEffect } from 'react'
import FourDirect from '../components/four'
const One = dynamic(() => import('../components/one'))
const Two = dynamic(() => import('../components/two'))
const Three = dynamic(() => import('../components/three'))
const Four = dynamic(() => import('../components/four'))
if (typeof window !== 'undefined') {
window.caughtErrors = ''
const origError = console.error
console.error = function (...args) {
window.caughtErrors += args.join(' ')
origError(...args)
}
}
const BEFORE_HYDRATION =
typeof document !== 'undefined' && document.getElementById('foo').innerHTML
const Index = () => {
const [firstRender, setFirstRender] = useState('the-server-value')
const [beforeHydration, setBeforeHydration] = useState(
'the-second-server-value'
)
useEffect(() => {
setFirstRender(document.getElementById('foo').innerHTML)
setBeforeHydration(BEFORE_HYDRATION)
}, [])
return (
<>
<div id="foo">
Index
<One />
<Two />
<Three />
<Four />
<FourDirect />
</div>
<div id="first-render">{firstRender}</div>
<div id="before-hydration">{beforeHydration}</div>
</>
)
}
export default Index
/* eslint-env jest */
import webdriver from 'next-webdriver'
import { join } from 'path'
import {
renderViaHTTP,
findPort,
launchApp,
killApp,
runNextCommand,
nextServer,
startApp,
stopApp,
} from 'next-test-utils'
let app
let appPort
let server
const appDir = join(__dirname, '../')
function runTests() {
it('should render server value', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/the-server-value/i)
expect(html).toMatch(/the-second-server-value/i)
})
it('should render dynamic server rendered values before hydration', async () => {
const browser = await webdriver(appPort, '/')
const text = await browser.elementByCss('#before-hydration').text()
expect(text).toBe('Index<!-- -->1<!-- -->2<!-- -->3<!-- -->4<!-- -->4')
expect(await browser.eval('window.caughtErrors')).toBe('')
})
it('should render dynamic server rendered values on client mount', async () => {
const browser = await webdriver(appPort, '/')
const text = await browser.elementByCss('#first-render').text()
expect(text).toBe('Index<!-- -->1<!-- -->2<!-- -->3<!-- -->4<!-- -->4')
expect(await browser.eval('window.caughtErrors')).toBe('')
})
}
describe('next/dynamic', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests(true)
})
describe('production mode', () => {
beforeAll(async () => {
await runNextCommand(['build', appDir])
app = nextServer({
dir: appDir,
dev: false,
quiet: true,
})
server = await startApp(app)
appPort = server.address().port
})
afterAll(() => stopApp(server))
runTests()
})
})
...@@ -193,7 +193,7 @@ describe('next-babel-loader', () => { ...@@ -193,7 +193,7 @@ describe('next-babel-loader', () => {
expect( expect(
code.replace(/modules: \[".*?"/, 'modules:["/path/to/page"') code.replace(/modules: \[".*?"/, 'modules:["/path/to/page"')
).toMatchInlineSnapshot( ).toMatchInlineSnapshot(
`"var _jsxFileName = \\"index.js\\";import React from \\"react\\";var __jsx = React.createElement;import dynamic from 'next/dynamic';const Comp = dynamic(() => import('comp'), { loadableGenerated: { webpack: () => [require.resolveWeak('comp')], modules:[\\"/path/to/page\\" + 'comp'] }});export default function Page(props) { return __jsx(Comp, { __self: this, __source: { fileName: _jsxFileName, lineNumber: 7, columnNumber: 18 } });}"` `"var _jsxFileName = \\"index.js\\";import React from \\"react\\";var __jsx = React.createElement;import dynamic from 'next/dynamic';const Comp = dynamic(() => import('comp'), { loadableGenerated: { webpack: () => [require.resolveWeak('comp')] }});export default function Page(props) { return __jsx(Comp, { __self: this, __source: { fileName: _jsxFileName, lineNumber: 7, columnNumber: 18 } });}"`
) )
}) })
......
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