Unverified Commit 08a7f7f3 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable SWC by default when there is no custom Babel config (#29811)

Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarjj@jjsweb.site <jj@jjsweb.site>
Co-authored-by: 's avatarMaia Teegarden <dev@padmaia.rocks>
Co-authored-by: 's avatarpadmaia <padmaia@users.noreply.github.com>
parent 79c25a4a
...@@ -482,6 +482,10 @@ ...@@ -482,6 +482,10 @@
{ {
"title": "invalid-project-dir-casing", "title": "invalid-project-dir-casing",
"path": "/errors/invalid-project-dir-casing.md" "path": "/errors/invalid-project-dir-casing.md"
},
{
"title": "swc-disabled",
"path": "/errors/swc-disabled.md"
} }
] ]
} }
......
# SWC disabled
#### Why This Message Occurred
Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScript/TypeScript. This new compiler is up to 17x faster than Babel when compiling individual files and up to 5x faster Fast Refresh.
Next.js provides full backwards compatibility with applications that have [custom Babel configuration](https://nextjs.org/docs/advanced-features/customizing-babel-config). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust.
When an application has custom Babel configuration Next.js will automatically opt-out of using SWC for compiling JavaScript/Typescript and will fall back to using Babel in the same way that it was used in Next.js 11.
Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to:
- Styled Components
- Emotion
- Relay
In order to prioritize transforms that will help you adopt SWC please provide your `.babelrc` on [the feedback thread](https://github.com/vercel/next.js/discussions/30174).
...@@ -127,7 +127,6 @@ ...@@ -127,7 +127,6 @@
"nprogress": "0.2.0", "nprogress": "0.2.0",
"pixrem": "5.0.0", "pixrem": "5.0.0",
"playwright-chromium": "1.14.1", "playwright-chromium": "1.14.1",
"pnpm": "5.14.3",
"postcss-nested": "4.2.1", "postcss-nested": "4.2.1",
"postcss-pseudoelements": "5.0.0", "postcss-pseudoelements": "5.0.0",
"postcss-short-size": "4.0.0", "postcss-short-size": "4.0.0",
......
...@@ -67,6 +67,9 @@ pub struct TransformOptions { ...@@ -67,6 +67,9 @@ pub struct TransformOptions {
#[serde(default)] #[serde(default)]
pub pages_dir: Option<PathBuf>, pub pages_dir: Option<PathBuf>,
#[serde(default)]
pub is_page_file: bool,
#[serde(default)] #[serde(default)]
pub is_development: bool, pub is_development: bool,
} }
...@@ -79,7 +82,7 @@ pub fn custom_before_pass(name: &FileName, opts: &TransformOptions) -> impl Fold ...@@ -79,7 +82,7 @@ pub fn custom_before_pass(name: &FileName, opts: &TransformOptions) -> impl Fold
amp_attributes::amp_attributes(), amp_attributes::amp_attributes(),
next_dynamic::next_dynamic(name.clone(), opts.pages_dir.clone()), next_dynamic::next_dynamic(name.clone(), opts.pages_dir.clone()),
Optional::new( Optional::new(
page_config::page_config(opts.is_development), page_config::page_config(opts.is_development, opts.is_page_file),
!opts.disable_page_config !opts.disable_page_config
) )
) )
......
...@@ -4,18 +4,19 @@ use swc_ecmascript::ast::*; ...@@ -4,18 +4,19 @@ use swc_ecmascript::ast::*;
use swc_ecmascript::utils::HANDLER; use swc_ecmascript::utils::HANDLER;
use swc_ecmascript::visit::{Fold, FoldWith}; use swc_ecmascript::visit::{Fold, FoldWith};
pub fn page_config(is_development: bool) -> impl Fold { pub fn page_config(is_development: bool, is_page_file: bool) -> impl Fold {
PageConfig { PageConfig {
is_development, is_development,
is_page_file,
..Default::default() ..Default::default()
} }
} }
pub fn page_config_test() -> impl Fold { pub fn page_config_test() -> impl Fold {
PageConfig { PageConfig {
drop_bundle: false,
in_test: true, in_test: true,
is_development: false, is_page_file: true,
..Default::default()
} }
} }
...@@ -24,12 +25,7 @@ struct PageConfig { ...@@ -24,12 +25,7 @@ struct PageConfig {
drop_bundle: bool, drop_bundle: bool,
in_test: bool, in_test: bool,
is_development: bool, is_development: bool,
} is_page_file: bool,
fn handle_error(details: &str, span: Span) {
let message = format!("Invalid page config export found. {} \
See: https://nextjs.org/docs/messages/invalid-page-config", details);
HANDLER.with(|handler| handler.struct_span_err(span, &message).emit());
} }
const STRING_LITERAL_DROP_BUNDLE: &str = "__NEXT_DROP_CLIENT_FILE__"; const STRING_LITERAL_DROP_BUNDLE: &str = "__NEXT_DROP_CLIENT_FILE__";
...@@ -95,32 +91,32 @@ impl Fold for PageConfig { ...@@ -95,32 +91,32 @@ impl Fold for PageConfig {
PropName::Ident(ident) => { PropName::Ident(ident) => {
if &ident.sym == "amp" { if &ident.sym == "amp" {
if let Expr::Lit(Lit::Bool(Bool { value, .. })) = &*kv.value { if let Expr::Lit(Lit::Bool(Bool { value, .. })) = &*kv.value {
if *value { if *value && self.is_page_file {
self.drop_bundle = true; self.drop_bundle = true;
} }
} else if let Expr::Lit(Lit::Str(_)) = &*kv.value { } else if let Expr::Lit(Lit::Str(_)) = &*kv.value {
// Do not replace bundle // Do not replace bundle
} else { } else {
handle_error("Invalid value found.", export.span); self.handle_error("Invalid value found.", export.span);
} }
} }
} }
_ => { _ => {
handle_error("Invalid property found.", export.span); self.handle_error("Invalid property found.", export.span);
} }
} }
} else { } else {
handle_error("Invalid property or value.", export.span); self.handle_error("Invalid property or value.", export.span);
} }
} else { } else {
handle_error("Property spread is not allowed.", export.span); self.handle_error("Property spread is not allowed.", export.span);
} }
} }
} else { } else {
handle_error("Expected config to be an object.", export.span); self.handle_error("Expected config to be an object.", export.span);
} }
} else { } else {
handle_error("Expected config to be an object.", export.span); self.handle_error("Expected config to be an object.", export.span);
} }
} }
} }
...@@ -137,15 +133,25 @@ impl Fold for PageConfig { ...@@ -137,15 +133,25 @@ impl Fold for PageConfig {
match &specifier.exported { match &specifier.exported {
Some(ident) => { Some(ident) => {
if &ident.sym == CONFIG_KEY { if &ident.sym == CONFIG_KEY {
handle_error("Config cannot be re-exported.", specifier.span) self.handle_error("Config cannot be re-exported.", specifier.span)
} }
} }
None => { None => {
if &specifier.orig.sym == CONFIG_KEY { if &specifier.orig.sym == CONFIG_KEY {
handle_error("Config cannot be re-exported.", specifier.span) self.handle_error("Config cannot be re-exported.", specifier.span)
} }
} }
} }
specifier specifier
} }
} }
impl PageConfig {
fn handle_error(&mut self, details: &str, span: Span) {
if self.is_page_file {
let message = format!("Invalid page config export found. {} \
See: https://nextjs.org/docs/messages/invalid-page-config", details);
HANDLER.with(|handler| handler.struct_span_err(span, &message).emit());
}
}
}
...@@ -65,6 +65,8 @@ const devtoolRevertWarning = execOnce( ...@@ -65,6 +65,8 @@ const devtoolRevertWarning = execOnce(
} }
) )
let loggedSwcDisabled = false
function parseJsonFile(filePath: string) { function parseJsonFile(filePath: string) {
const JSON5 = require('next/dist/compiled/json5') const JSON5 = require('next/dist/compiled/json5')
const contents = readFileSync(filePath, 'utf8') const contents = readFileSync(filePath, 'utf8')
...@@ -297,11 +299,15 @@ export default async function getBaseWebpackConfig( ...@@ -297,11 +299,15 @@ export default async function getBaseWebpackConfig(
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
const useSWCLoader = config.experimental.swcLoader const useSWCLoader = config.experimental.swcLoader && !babelConfigFile
if (useSWCLoader && babelConfigFile) { if (!loggedSwcDisabled && !useSWCLoader && babelConfigFile) {
Log.warn( Log.warn(
`experimental.swcLoader enabled. The custom Babel configuration will not be used.` `Disabled SWC because of custom Babel configuration "${path.relative(
dir,
babelConfigFile
)}" https://nextjs.org/docs/messages/swc-disabled`
) )
loggedSwcDisabled = true
} }
const defaultLoaders = { const defaultLoaders = {
babel: useSWCLoader babel: useSWCLoader
......
...@@ -58,6 +58,14 @@ function getSWCOptions({ ...@@ -58,6 +58,14 @@ function getSWCOptions({
useBuiltins: true, useBuiltins: true,
refresh: development && !isServer, refresh: development && !isServer,
}, },
optimizer: {
simplify: false,
globals: {
typeofs: {
window: isServer ? 'undefined' : 'object',
},
},
},
}, },
} }
...@@ -77,6 +85,7 @@ function getSWCOptions({ ...@@ -77,6 +85,7 @@ function getSWCOptions({
disablePageConfig: true, disablePageConfig: true,
isDevelopment: development, isDevelopment: development,
pagesDir, pagesDir,
isPageFile,
env: { env: {
targets: { targets: {
// Targets the current version of Node.js // Targets the current version of Node.js
...@@ -99,6 +108,7 @@ function getSWCOptions({ ...@@ -99,6 +108,7 @@ function getSWCOptions({
disableNextSsg: !isPageFile, disableNextSsg: !isPageFile,
isDevelopment: development, isDevelopment: development,
pagesDir, pagesDir,
isPageFile,
jsc, jsc,
} }
} }
......
...@@ -101,6 +101,7 @@ ...@@ -101,6 +101,7 @@
"raw-body": "2.4.1", "raw-body": "2.4.1",
"react-is": "17.0.2", "react-is": "17.0.2",
"react-refresh": "0.8.3", "react-refresh": "0.8.3",
"regenerator-runtime": "0.13.4",
"stream-browserify": "3.0.0", "stream-browserify": "3.0.0",
"stream-http": "3.1.1", "stream-http": "3.1.1",
"string_decoder": "1.3.0", "string_decoder": "1.3.0",
......
...@@ -203,7 +203,7 @@ export const defaultConfig: NextConfig = { ...@@ -203,7 +203,7 @@ export const defaultConfig: NextConfig = {
}, },
staticPageGenerationTimeout: 60, staticPageGenerationTimeout: 60,
experimental: { experimental: {
swcLoader: false, swcLoader: true,
swcMinify: false, swcMinify: false,
cpus: Math.max( cpus: Math.max(
1, 1,
......
...@@ -29,6 +29,14 @@ do ...@@ -29,6 +29,14 @@ do
cp -r "./examples/$testCase/." "./e2e-tests/$testCase" cp -r "./examples/$testCase/." "./e2e-tests/$testCase"
cd "./e2e-tests/$testCase" cd "./e2e-tests/$testCase"
# TODO: remove after able to load bindings with YarnPnP
if [ -f "next.config.js" ]; then
mv next.config.js next.config.bak.js
echo 'module.exports = { ...require("./next.config.bak.js"), experimental: { swcLoader: false } }' > next.config.js
else
echo 'module.exports = { experimental: { swcLoader: false } }' > next.config.js
fi
touch yarn.lock touch yarn.lock
yarn set version berry yarn set version berry
......
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ReactRefreshLogBox _app syntax error shows logbox 1`] = ` exports[`ReactRefreshLogBox _app syntax error shows logbox 1`] = `
"./pages/_app.js:3:22 "./pages/_app.js
Syntax error: Unexpected token Error: error: Expression expected
|
3 | return <<Component {...pageProps} />;
| ^
1 | error: Unexpected token \`jsx name (Component)\`. Expected this, import, async, function, [ for array literal, { for object literal, @ for decorator, function, class, null, true, false, number, bigint, string, regexp, \` for template literal, (, or an identifier
2 | function MyApp({ Component, pageProps }) {
> 3 | return <<Component {...pageProps} />; |
| ^ 3 | return <<Component {...pageProps} />;
4 | } | ^^^^^^^^^
5 | export default MyApp
6 |" Caused by:
0: failed to process js file
1: Syntax Error"
`; `;
exports[`ReactRefreshLogBox _document syntax error shows logbox 1`] = ` exports[`ReactRefreshLogBox _document syntax error shows logbox 1`] = `
"./pages/_document.js:4:47 "./pages/_document.js
Syntax error: Unexpected token Error: error: Unexpected token \`{\`. Expected identifier, string literal, numeric literal or [ for the computed key
|
4 | class MyDocument extends Document {{
| ^
2 | import Document, { Html, Head, Main, NextScript } from 'next/document' Caused by:
3 | 0: failed to process js file
> 4 | class MyDocument extends Document {{ 1: Syntax Error"
| ^
5 | static async getInitialProps(ctx) {
6 | const initialProps = await Document.getInitialProps(ctx)
7 | return { ...initialProps }"
`; `;
...@@ -67,11 +67,16 @@ exports[`ReactRefreshLogBox logbox: can recover from a event handler error 1`] = ...@@ -67,11 +67,16 @@ exports[`ReactRefreshLogBox logbox: can recover from a event handler error 1`] =
`; `;
exports[`ReactRefreshLogBox logbox: can recover from a syntax error without losing state 1`] = ` exports[`ReactRefreshLogBox logbox: can recover from a syntax error without losing state 1`] = `
"./index.js:1:26 "./index.js
Syntax error: Unexpected token, expected \\"jsxTagEnd\\" Error: error: Unexpected eof
> 1 | export default () => <div/ |
| ^" 1 | export default () => <div/
| ^
Caused by:
0: failed to process js file
1: Syntax Error"
`; `;
exports[`ReactRefreshLogBox module init error not shown 1`] = ` exports[`ReactRefreshLogBox module init error not shown 1`] = `
...@@ -122,34 +127,40 @@ exports[`ReactRefreshLogBox syntax > runtime error 1`] = ` ...@@ -122,34 +127,40 @@ exports[`ReactRefreshLogBox syntax > runtime error 1`] = `
`; `;
exports[`ReactRefreshLogBox syntax > runtime error 2`] = ` exports[`ReactRefreshLogBox syntax > runtime error 2`] = `
"./index.js:8:49 "./index.js
Syntax error: Unexpected token Error: error: Unexpected eof
6 | throw Error('no ' + i) |
7 | }, 1000) 8 | export default function FunctionNamed() {
> 8 | export default function FunctionNamed() { | ^
| ^"
Caused by:
0: failed to process js file
1: Syntax Error"
`; `;
exports[`ReactRefreshLogBox syntax > runtime error 3`] = ` exports[`ReactRefreshLogBox syntax > runtime error 3`] = `
"./index.js:8:49 "./index.js
Syntax error: Unexpected token Error: error: Unexpected eof
6 | throw Error('no ' + i) |
7 | }, 1000) 8 | export default function FunctionNamed() {
> 8 | export default function FunctionNamed() { | ^
| ^"
Caused by:
0: failed to process js file
1: Syntax Error"
`; `;
exports[`ReactRefreshLogBox unterminated JSX 1`] = ` exports[`ReactRefreshLogBox unterminated JSX 1`] = `
"./index.js:5:24 "./index.js
Syntax error: Unterminated JSX contents. Error: error: Unexpected eof
3 | return ( |
4 | <div> 9 |
> 5 | <p>lol</p> | ^
| ^
6 | div Caused by:
7 | ) 0: failed to process js file
8 | }" 1: Syntax Error"
`; `;
...@@ -264,8 +264,8 @@ describe('basic HMR', () => { ...@@ -264,8 +264,8 @@ describe('basic HMR', () => {
) )
expect(editedFontSize).toBe('200px') expect(editedFontSize).toBe('200px')
expect(browserHtml.includes('font-size:200px;')).toBe(true) expect(browserHtml.includes('font-size:200px')).toBe(true)
expect(browserHtml.includes('font-size:100px;')).toBe(false) expect(browserHtml.includes('font-size:100px')).toBe(false)
const editedHtml = await renderViaHTTP( const editedHtml = await renderViaHTTP(
next.appPort, next.appPort,
...@@ -341,9 +341,7 @@ describe('basic HMR', () => { ...@@ -341,9 +341,7 @@ describe('basic HMR', () => {
await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div')) await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div'))
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch( expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
/Unterminated JSX contents/
)
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
...@@ -380,9 +378,7 @@ describe('basic HMR', () => { ...@@ -380,9 +378,7 @@ describe('basic HMR', () => {
browser = await webdriver(next.appPort, '/docs/hmr/contact') browser = await webdriver(next.appPort, '/docs/hmr/contact')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch( expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
/Unterminated JSX contents/
)
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
......
...@@ -268,8 +268,8 @@ describe('basic HMR', () => { ...@@ -268,8 +268,8 @@ describe('basic HMR', () => {
) )
expect(editedFontSize).toBe('200px') expect(editedFontSize).toBe('200px')
expect(browserHtml.includes('font-size:200px;')).toBe(true) expect(browserHtml.includes('font-size:200px')).toBe(true)
expect(browserHtml.includes('font-size:100px;')).toBe(false) expect(browserHtml.includes('font-size:100px')).toBe(false)
const editedHtml = await renderViaHTTP( const editedHtml = await renderViaHTTP(
next.appPort, next.appPort,
...@@ -352,9 +352,7 @@ describe('basic HMR', () => { ...@@ -352,9 +352,7 @@ describe('basic HMR', () => {
await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div')) await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div'))
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch( expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
/Unterminated JSX contents/
)
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
...@@ -395,9 +393,7 @@ describe('basic HMR', () => { ...@@ -395,9 +393,7 @@ describe('basic HMR', () => {
browser = await webdriver(next.appPort, '/hmr/contact') browser = await webdriver(next.appPort, '/hmr/contact')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch( expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
/Unterminated JSX contents/
)
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
......
...@@ -352,8 +352,10 @@ describe('basePath', () => { ...@@ -352,8 +352,10 @@ describe('basePath', () => {
it('should update dynamic params after mount correctly', async () => { it('should update dynamic params after mount correctly', async () => {
const browser = await webdriver(next.url, `${basePath}/hello-dynamic`) const browser = await webdriver(next.url, `${basePath}/hello-dynamic`)
const text = await browser.elementByCss('#slug').text() await check(
expect(text).toContain('slug: hello-dynamic') () => browser.elementByCss('#slug').text(),
/slug: hello-dynamic/
)
}) })
it('should navigate to index page with getStaticProps', async () => { it('should navigate to index page with getStaticProps', async () => {
...@@ -682,6 +684,10 @@ describe('basePath', () => { ...@@ -682,6 +684,10 @@ describe('basePath', () => {
it('should use urls with basepath in router events', async () => { it('should use urls with basepath in router events', async () => {
const browser = await webdriver(next.url, `${basePath}/hello`) const browser = await webdriver(next.url, `${basePath}/hello`)
try { try {
await check(
() => browser.eval('window.next.router.isReady ? "ready" : "no"'),
'ready'
)
await browser.eval('window._clearEventLog()') await browser.eval('window._clearEventLog()')
await browser await browser
.elementByCss('#other-page-link') .elementByCss('#other-page-link')
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
findPort, findPort,
killApp, killApp,
launchApp, launchApp,
check,
} from 'next-test-utils' } from 'next-test-utils'
const appDir = path.join(__dirname, '..') const appDir = path.join(__dirname, '..')
...@@ -33,15 +34,17 @@ const runTests = () => { ...@@ -33,15 +34,17 @@ const runTests = () => {
it('Refreshes query on mount', async () => { it('Refreshes query on mount', async () => {
const browser = await webdriver(appPort, '/post-1') const browser = await webdriver(appPort, '/post-1')
await check(() => browser.eval('document.body.innerHTML'), /post.*post-1/)
const html = await browser.eval('document.body.innerHTML') const html = await browser.eval('document.body.innerHTML')
expect(html).toMatch(/post.*post-1/)
expect(html).toMatch(/nextExport/) expect(html).toMatch(/nextExport/)
}) })
it('should update asPath after mount', async () => { it('should update asPath after mount', async () => {
const browser = await webdriver(appPort, '/zeit/cmnt-2') const browser = await webdriver(appPort, '/zeit/cmnt-2')
const html = await browser.eval(`document.documentElement.innerHTML`) await check(
expect(html).toMatch(/\/zeit\/cmnt-2/) () => browser.eval(`document.documentElement.innerHTML`),
/\/zeit\/cmnt-2/
)
}) })
it('should not replace URL with page name while asPath is delayed', async () => { it('should not replace URL with page name while asPath is delayed', async () => {
......
module.exports = {
experimental: {
swcLoader: false,
},
}
module.exports = {
experimental: {
swcLoader: false,
},
}
module.exports = {
experimental: {
swcLoader: false,
},
}
...@@ -218,7 +218,7 @@ export default function (render, fetch, ctx) { ...@@ -218,7 +218,7 @@ export default function (render, fetch, ctx) {
const styleId = $('#blue-box').attr('class') const styleId = $('#blue-box').attr('class')
const style = $('style') const style = $('style')
expect(style.text().includes(`p.${styleId}{color:blue`)).toBeTruthy() expect(style.text().includes(`p.${styleId} {color:blue`)).toBeTruthy()
}) })
test('renders styled jsx external', async () => { test('renders styled jsx external', async () => {
...@@ -226,7 +226,7 @@ export default function (render, fetch, ctx) { ...@@ -226,7 +226,7 @@ export default function (render, fetch, ctx) {
const styleId = $('#blue-box').attr('class') const styleId = $('#blue-box').attr('class')
const style = $('style') const style = $('style')
expect(style.text().includes(`p.${styleId}{color:blue`)).toBeTruthy() expect(style.text().includes(`p.${styleId} {color:blue`)).toBeTruthy()
}) })
test('renders properties populated asynchronously', async () => { test('renders properties populated asynchronously', async () => {
......
...@@ -46,7 +46,7 @@ describe('Custom _error', () => { ...@@ -46,7 +46,7 @@ describe('Custom _error', () => {
await fs.writeFile(page404, 'export default <h1>') await fs.writeFile(page404, 'export default <h1>')
const html = await renderViaHTTP(appPort, '/404') const html = await renderViaHTTP(appPort, '/404')
await fs.remove(page404) await fs.remove(page404)
expect(html).toContain('Syntax error') expect(html).toContain('Unexpected eof')
expect(stderr).not.toMatch(customErrNo404Match) expect(stderr).not.toMatch(customErrNo404Match)
}) })
}) })
......
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
initNextServerScript, initNextServerScript,
nextExport, nextExport,
hasRedbox, hasRedbox,
check,
} from 'next-test-utils' } from 'next-test-utils'
let appDir = join(__dirname, '..') let appDir = join(__dirname, '..')
...@@ -156,8 +157,10 @@ const runTests = (isDev = false) => { ...@@ -156,8 +157,10 @@ const runTests = (isDev = false) => {
it('should parse params correctly for rewrite to auto-export dynamic page', async () => { it('should parse params correctly for rewrite to auto-export dynamic page', async () => {
const browser = await webdriver(appPort, '/rewriting-to-auto-export') const browser = await webdriver(appPort, '/rewriting-to-auto-export')
const text = await browser.eval(() => document.documentElement.innerHTML) await check(
expect(text).toContain('auto-export hello') () => browser.eval(() => document.documentElement.innerHTML),
/auto-export hello/
)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({ expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
rewrite: '1', rewrite: '1',
slug: 'hello', slug: 'hello',
...@@ -2127,8 +2130,10 @@ describe('Custom routes', () => { ...@@ -2127,8 +2130,10 @@ describe('Custom routes', () => {
it('should not error for no-op rewrite and auto export dynamic route', async () => { it('should not error for no-op rewrite and auto export dynamic route', async () => {
const browser = await webdriver(appPort, '/auto-export/my-slug') const browser = await webdriver(appPort, '/auto-export/my-slug')
const html = await browser.eval(() => document.documentElement.innerHTML) await check(
expect(html).toContain(`auto-export my-slug`) () => browser.eval(() => document.documentElement.innerHTML),
/auto-export my-slug/
)
}) })
}) })
......
...@@ -876,8 +876,10 @@ function runTests(dev) { ...@@ -876,8 +876,10 @@ function runTests(dev) {
expect(html).toMatch(/onmpost:.*pending/) expect(html).toMatch(/onmpost:.*pending/)
const browser = await webdriver(appPort, '/on-mount/post-1') const browser = await webdriver(appPort, '/on-mount/post-1')
const text = await browser.eval(`document.body.innerHTML`) await check(
expect(text).toMatch(/onmpost:.*post-1/) () => browser.eval(`document.body.innerHTML`),
/onmpost:.*post-1/
)
}) })
it('should not have placeholder query values for SSS', async () => { it('should not have placeholder query values for SSS', async () => {
...@@ -887,16 +889,19 @@ function runTests(dev) { ...@@ -887,16 +889,19 @@ function runTests(dev) {
it('should update with a hash in the URL', async () => { it('should update with a hash in the URL', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#abc') const browser = await webdriver(appPort, '/on-mount/post-1#abc')
const text = await browser.eval(`document.body.innerHTML`) await check(
expect(text).toMatch(/onmpost:.*post-1/) () => browser.eval(`document.body.innerHTML`),
/onmpost:.*post-1/
)
}) })
it('should scroll to a hash on mount', async () => { it('should scroll to a hash on mount', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#item-400') const browser = await webdriver(appPort, '/on-mount/post-1#item-400')
const text = await browser.eval(`document.body.innerHTML`) await check(
expect(text).toMatch(/onmpost:.*post-1/) () => browser.eval(`document.body.innerHTML`),
/onmpost:.*post-1/
)
const scrollPosition = await browser.eval('window.pageYOffset') const scrollPosition = await browser.eval('window.pageYOffset')
expect(scrollPosition).toBe(7232) expect(scrollPosition).toBe(7232)
}) })
......
...@@ -4,21 +4,11 @@ import fs from 'fs-extra' ...@@ -4,21 +4,11 @@ import fs from 'fs-extra'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
const pnpmExecutable = path.join(
__dirname,
'..',
'..',
'..',
'..',
'node_modules',
'.bin',
'pnpm'
)
const packagesDir = path.join(__dirname, '..', '..', '..', '..', 'packages') const packagesDir = path.join(__dirname, '..', '..', '..', '..', 'packages')
const appDir = path.join(__dirname, '..', 'app') const appDir = path.join(__dirname, '..', 'app')
const runNpm = (cwd, ...args) => execa('npm', [...args], { cwd }) const runNpm = (cwd, ...args) => execa('npm', [...args], { cwd })
const runPnpm = (cwd, ...args) => execa(pnpmExecutable, [...args], { cwd }) const runPnpm = (cwd, ...args) => execa('npx', ['pnpm', ...args], { cwd })
async function usingTempDir(fn) { async function usingTempDir(fn) {
const folder = path.join(os.tmpdir(), Math.random().toString(36).substring(2)) const folder = path.join(os.tmpdir(), Math.random().toString(36).substring(2))
...@@ -75,6 +65,7 @@ describe('pnpm support', () => { ...@@ -75,6 +65,7 @@ describe('pnpm support', () => {
// To ensure that they are installed upon installing "next", a package.json "pnpm.overrides" // To ensure that they are installed upon installing "next", a package.json "pnpm.overrides"
// field is used to override these dependency paths at install time. // field is used to override these dependency paths at install time.
await usingTempDir(async (tempDir) => { await usingTempDir(async (tempDir) => {
console.error('using dir', tempDir)
const nextTarballPath = await pack(tempDir, 'next') const nextTarballPath = await pack(tempDir, 'next')
const dependencyTarballPaths = { const dependencyTarballPaths = {
'@next/env': await pack(tempDir, 'next-env'), '@next/env': await pack(tempDir, 'next-env'),
...@@ -105,7 +96,12 @@ describe('pnpm support', () => { ...@@ -105,7 +96,12 @@ describe('pnpm support', () => {
) )
await runPnpm(tempAppDir, 'install') await runPnpm(tempAppDir, 'install')
await runPnpm(tempAppDir, 'add', nextTarballPath) await runPnpm(tempAppDir, 'add', `next@${nextTarballPath}`)
await fs.copy(
path.join(__dirname, '../../../../packages/next/native'),
path.join(tempAppDir, 'node_modules/next/native')
)
expect( expect(
await fs.pathExists(path.join(tempAppDir, 'pnpm-lock.yaml')) await fs.pathExists(path.join(tempAppDir, 'pnpm-lock.yaml'))
...@@ -117,7 +113,7 @@ describe('pnpm support', () => { ...@@ -117,7 +113,7 @@ describe('pnpm support', () => {
expect(packageJson.pnpm.overrides[dependency]).toMatch(/^file:/) expect(packageJson.pnpm.overrides[dependency]).toMatch(/^file:/)
} }
const { stdout, stderr } = await runPnpm(tempAppDir, 'run', 'build') const { stdout, stderr } = await runPnpm(tempAppDir, 'next', 'build')
console.log(stdout, stderr) console.log(stdout, stderr)
expect(stdout).toMatch(/Compiled successfully/) expect(stdout).toMatch(/Compiled successfully/)
}) })
......
...@@ -12,7 +12,7 @@ describe('Re-export all exports from page is disallowed', () => { ...@@ -12,7 +12,7 @@ describe('Re-export all exports from page is disallowed', () => {
expect(code).toBe(1) expect(code).toBe(1)
expect(stderr).toMatch(/\/export-all-in-page/) expect(stderr).toMatch(/\/export-all-in-page/)
expect(stderr.split('\n\n')[1]).toMatchInlineSnapshot(` expect(stderr.split('\n\n')[2]).toMatchInlineSnapshot(`
"./pages/contact.js:3:1 "./pages/contact.js:3:1
Syntax error: Using \`export * from '...'\` in a page is disallowed. Please use \`export { default } from '...'\` instead. Syntax error: Using \`export * from '...'\` in a page is disallowed. Please use \`export { default } from '...'\` instead.
Read more: https://nextjs.org/docs/messages/export-all-in-page" Read more: https://nextjs.org/docs/messages/export-all-in-page"
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
nextStart, nextStart,
nextBuild, nextBuild,
File, File,
check,
} from 'next-test-utils' } from 'next-test-utils'
let app let app
...@@ -16,25 +17,34 @@ let appPort ...@@ -16,25 +17,34 @@ let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const invalidPage = new File(join(appDir, 'pages/invalid.js')) const invalidPage = new File(join(appDir, 'pages/invalid.js'))
const checkIsReadyValues = (browser, expected = []) => {
return check(async () => {
const values = JSON.stringify(
(await browser.eval('window.isReadyValues')).sort()
)
return JSON.stringify(expected.sort()) === values ? 'success' : values
}, 'success')
}
function runTests() { function runTests() {
it('isReady should be true immediately for pages without getStaticProps', async () => { it('isReady should be true immediately for pages without getStaticProps', async () => {
const browser = await webdriver(appPort, '/appGip') const browser = await webdriver(appPort, '/appGip')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for pages without getStaticProps, with query', async () => { it('isReady should be true immediately for pages without getStaticProps, with query', async () => {
const browser = await webdriver(appPort, '/appGip?hello=world') const browser = await webdriver(appPort, '/appGip?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for getStaticProps page without query', async () => { it('isReady should be true immediately for getStaticProps page without query', async () => {
const browser = await webdriver(appPort, '/gsp') const browser = await webdriver(appPort, '/gsp')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true after query update for getStaticProps page with query', async () => { it('isReady should be true after query update for getStaticProps page with query', async () => {
const browser = await webdriver(appPort, '/gsp?hello=world') const browser = await webdriver(appPort, '/gsp?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([false, true]) await checkIsReadyValues(browser, [false, true])
}) })
} }
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
nextStart, nextStart,
nextBuild, nextBuild,
File, File,
check,
} from 'next-test-utils' } from 'next-test-utils'
let app let app
...@@ -16,55 +17,64 @@ let appPort ...@@ -16,55 +17,64 @@ let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const invalidPage = new File(join(appDir, 'pages/invalid.js')) const invalidPage = new File(join(appDir, 'pages/invalid.js'))
const checkIsReadyValues = (browser, expected = []) => {
return check(async () => {
const values = JSON.stringify(
(await browser.eval('window.isReadyValues')).sort()
)
return JSON.stringify(expected.sort()) === values ? 'success' : values
}, 'success')
}
function runTests() { function runTests() {
it('isReady should be true immediately for getInitialProps page', async () => { it('isReady should be true immediately for getInitialProps page', async () => {
const browser = await webdriver(appPort, '/gip') const browser = await webdriver(appPort, '/gip')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for getInitialProps page with query', async () => { it('isReady should be true immediately for getInitialProps page with query', async () => {
const browser = await webdriver(appPort, '/gip?hello=world') const browser = await webdriver(appPort, '/gip?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for getServerSideProps page', async () => { it('isReady should be true immediately for getServerSideProps page', async () => {
const browser = await webdriver(appPort, '/gssp') const browser = await webdriver(appPort, '/gssp')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for getServerSideProps page with query', async () => { it('isReady should be true immediately for getServerSideProps page with query', async () => {
const browser = await webdriver(appPort, '/gssp?hello=world') const browser = await webdriver(appPort, '/gssp?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true immediately for auto-export page without query', async () => { it('isReady should be true immediately for auto-export page without query', async () => {
const browser = await webdriver(appPort, '/auto-export') const browser = await webdriver(appPort, '/auto-export')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
it('isReady should be true after query update for auto-export page with query', async () => { it('isReady should be true after query update for auto-export page with query', async () => {
const browser = await webdriver(appPort, '/auto-export?hello=world') const browser = await webdriver(appPort, '/auto-export?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([false, true]) await checkIsReadyValues(browser, [false, true])
}) })
it('isReady should be true after query update for dynamic auto-export page without query', async () => { it('isReady should be true after query update for dynamic auto-export page without query', async () => {
const browser = await webdriver(appPort, '/auto-export/first') const browser = await webdriver(appPort, '/auto-export/first')
expect(await browser.eval('window.isReadyValues')).toEqual([false, true]) await checkIsReadyValues(browser, [false, true])
}) })
it('isReady should be true after query update for dynamic auto-export page with query', async () => { it('isReady should be true after query update for dynamic auto-export page with query', async () => {
const browser = await webdriver(appPort, '/auto-export/first?hello=true') const browser = await webdriver(appPort, '/auto-export/first?hello=true')
expect(await browser.eval('window.isReadyValues')).toEqual([false, true]) await checkIsReadyValues(browser, [false, true])
}) })
it('isReady should be true after query update for getStaticProps page with query', async () => { it('isReady should be true after query update for getStaticProps page with query', async () => {
const browser = await webdriver(appPort, '/gsp?hello=world') const browser = await webdriver(appPort, '/gsp?hello=world')
expect(await browser.eval('window.isReadyValues')).toEqual([false, true]) await checkIsReadyValues(browser, [false, true])
}) })
it('isReady should be true immediately for getStaticProps page without query', async () => { it('isReady should be true immediately for getStaticProps page without query', async () => {
const browser = await webdriver(appPort, '/gsp') const browser = await webdriver(appPort, '/gsp')
expect(await browser.eval('window.isReadyValues')).toEqual([true]) await checkIsReadyValues(browser, [true])
}) })
} }
......
...@@ -30,7 +30,7 @@ describe('typeof window replace', () => { ...@@ -30,7 +30,7 @@ describe('typeof window replace', () => {
path.join(appDir, '.next', pageFile), path.join(appDir, '.next', pageFile),
'utf8' 'utf8'
) )
expect(content).toMatch(/Hello.*?,.*?("|')object("|')/) expect(content).toMatch(/Hello.*?,.*?\n?.*?("|')object("|')/)
}) })
it('Replaces `typeof window` with undefined for server code', async () => { it('Replaces `typeof window` with undefined for server code', async () => {
...@@ -41,7 +41,7 @@ describe('typeof window replace', () => { ...@@ -41,7 +41,7 @@ describe('typeof window replace', () => {
'utf8' 'utf8'
) )
expect(content).toMatch(/Hello.*?,.*?("|')undefined("|')/) expect(content).toMatch(/Hello.*?,.*?\n?.*?("|')undefined("|')/)
}) })
it('Does not replace `typeof window` for `node_modules` code', async () => { it('Does not replace `typeof window` for `node_modules` code', async () => {
......
...@@ -14,7 +14,12 @@ async function createNextInstall(dependencies) { ...@@ -14,7 +14,12 @@ async function createNextInstall(dependencies) {
for (const item of ['package.json', 'yarn.lock', 'packages']) { for (const item of ['package.json', 'yarn.lock', 'packages']) {
await fs.copy(path.join(origRepoDir, item), path.join(tmpRepoDir, item), { await fs.copy(path.join(origRepoDir, item), path.join(tmpRepoDir, item), {
filter: (item) => { filter: (item) => {
return !item.includes('node_modules') return (
!item.includes('node_modules') &&
!item.includes('.DS_Store') &&
// Exclude Rust compilation files
!/next[\\/]build[\\/]swc[\\/]target/.test(item)
)
}, },
}) })
} }
......
...@@ -95,6 +95,8 @@ export default async function webdriver( ...@@ -95,6 +95,8 @@ export default async function webdriver(
callback() callback()
} }
// TODO: should we also ensure router.isReady is true
// by default before resolving?
if ((window as any).__NEXT_HYDRATED) { if ((window as any).__NEXT_HYDRATED) {
console.log('Next.js page already hydrated') console.log('Next.js page already hydrated')
callback() callback()
......
...@@ -15179,11 +15179,6 @@ pngjs@^5.0.0: ...@@ -15179,11 +15179,6 @@ pngjs@^5.0.0:
resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-5.0.0.tgz#e79dd2b215767fd9c04561c01236df960bce7fbb" resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-5.0.0.tgz#e79dd2b215767fd9c04561c01236df960bce7fbb"
integrity sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw== integrity sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==
pnpm@5.14.3:
version "5.14.3"
resolved "https://registry.yarnpkg.com/pnpm/-/pnpm-5.14.3.tgz#88e53906652c85ba2e6f69294042d95aad018cbe"
integrity sha512-PFjHFWCsHgaNCpOwOAgN6H71PA8td8PnwSE1ArXz//OyfdfIwws1s23XLmokhHcnE3JsBSiIR3NOW8JZ5QcxlQ==
posix-character-classes@^0.1.0: posix-character-classes@^0.1.0:
version "0.1.1" version "0.1.1"
resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
...@@ -16659,6 +16654,11 @@ regenerate@^1.4.0: ...@@ -16659,6 +16654,11 @@ regenerate@^1.4.0:
version "1.4.0" version "1.4.0"
resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.4.0.tgz#4a856ec4b56e4077c557589cae85e7a4c8869a11" resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.4.0.tgz#4a856ec4b56e4077c557589cae85e7a4c8869a11"
regenerator-runtime@0.13.4:
version "0.13.4"
resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.4.tgz#e96bf612a3362d12bb69f7e8f74ffeab25c7ac91"
integrity sha512-plpwicqEzfEyTQohIKktWigcLzmNStMGwbOUbykx51/29Z3JOGYldaaNGK7ngNXV+UcoqvIMmloZ48Sr74sd+g==
regenerator-runtime@^0.13.4: regenerator-runtime@^0.13.4:
version "0.13.5" version "0.13.5"
resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz#d878a1d094b4306d10b9096484b33ebd55e26697" resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz#d878a1d094b4306d10b9096484b33ebd55e26697"
......
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