This implements the compatibility require hook as per https://github.com/vercel/next.js/issues/21789.
The hook is applied at the point of webpack initialization. In addition the separate packages are exposed for the various webpack subrequires.
The test then ensures instance equality for the basic require hook from the next.js config file.
I suspect this might have bad interactions with Yarn Pnp support, but maybe we will be lucky.
@timneutkens I think this is ready for a review.
I've made some changes to the original design that _seem_ to have paid off. The parenting relationships for traces of normal builds are applied more uniformly, resulting in more intelligible traces:
<img width="900" alt="Screen Shot 2021-01-29 at 12 53 47 AM" src="https://user-images.githubusercontent.com/5016978/106253732-ba321880-61cc-11eb-98fd-d45af5078273.png">
Hot-reloading is surfaced now, too. I will note, however, that we will want to dig in deeper and find out where the large portion of time at the beginning of hot-reload is spent. Example:
<img width="894" alt="Screen Shot 2021-01-29 at 12 53 28 AM" src="https://user-images.githubusercontent.com/5016978/106253828-e057b880-61cc-11eb-967d-46eaff31ecef.png">
Where did those 180 ms go? At the least, we can now track how long a hot-reload takes, and have a place to start with further investigation.
This picks up on the inlining work in https://github.com/vercel/next.js/pull/20598 to also include webpack loader inlining optimizations.
This includes:
* The dependencies of sass-loader
* resolve-url-loader
And for added benefit:
* babel-plugin-transform-define
* babel-plugin-transform-react-remove-prop-types
style-loader and css-loader didn't inline easily. Perhaps we can come back to these ones.
This pull request adds `future.strictPostcssConfiguration`, allowing users to opt-into the more strict PostCSS configuration loading.
This stricter PostCSS configuration loading ensures that CSS can be cached across builds.
This ensures we detect domain specific locales and redirect them client-side. Tests have been added in the `i18n` suite to ensure the domain redirect is applied correctly during a client-side navigation
Fixes: https://github.com/vercel/next.js/issues/19174
There's currently two bugs with the font optimization, but we'd really like to ship a stable version.
To unblock the stable release, we're **temporarily** reflagging this. It'll be unflagged on canary again!
Solves the following warning:
> (node:1484) [DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN] DeprecationWarning: MainTemplate.requireFn is deprecated (use "__webpack_require__")
This PR removes the modern mode experiment because:
- It does not yield meaningful bundle size wins when compared to other initiatives we've taken
- It's not compatible with webpack 5 (which we're upgrading to)
- It's currently broken and causes most apps to malfunction
- There's no champion currently owning the experiment
We can re-introduce this in the future when we'd like to make it a default for all Next.js apps.
Note: **Next.js still supports Differential Loading (`nomodule`) and does it by default.** This PR strictly removes the experimental modern _syntax_, and does not disable our existing modern/legacy polyfilling.
---
Fixes#19200Fixes#18960Fixes#14707Fixes#14465
We accidentally regressed back in 9.5 and dropped support for inline CSS comments. PostCSS always parses these as pass-through (and not a syntax error), which can cause problems when minifying.
Browsers do a similar thing and ignore the comments.
To ensure we generate valid CSS, this adds support for stripping the CSS comments from the build.
---
Fixes#15589Closes#17130
This fixes a few things related to optional catch-all routes and i18n. The first thing is it ensures the correct data route is generated on the client so that the locale isn't duplicated for an optional catch-all route, the next is it ensures the browser history is updated correctly when only a locale change is occurring, and then it also ensures we handle the locales and normalizing for fallback optional catch-all pages correctly.
Tests have been added to ensure these cases are covered properly and we don't regress on them, these changes were also tested on Vercel [here](https://next-js-bug-i18n-root-params-nybg44l0b.vercel.app/)
Fixes: https://github.com/vercel/next.js/issues/18633
Fixes: https://github.com/vercel/next.js/issues/19059
This ensures we use the `defaultLocale` for a locale domain when rendering non-static pages. Static pages will initially contain the global `defaultLocale` and then be updated on the client since we don't currently prerender a version of the pages for each locale domain.
Closes: https://github.com/vercel/next.js/issues/18970
This upgrades to ncc@0.25.0 and fixes the previous bugs including:
* ncc not referenced correctly in build
* Babel type errors
* node-fetch, etag, chalk and raw-body dependencies not building with ncc - these have been "un-ncc'd" for now. As they are relatively small dependencies, this doesn't seem too much of an issue and we can follow up in the tracking ncc issue at https://github.com/vercel/ncc/issues/612.
* `yarn dev` issues
Took a lot of bisecting, but the overall diff isn't too bad here in the end.
This adds inlining for Babel and the Babel plugins used in next.
This is based to the PR at https://github.com/vercel/next.js/pull/18823.
The approach is to make one large bundle and then separate out the individual packages from that in order to avoid duplications.
In the first attempt the Babel bundle size was 10MB... using "resolutions" in the Yarn workspace to reduce the duplicated packages this was brought down to a 2.8MB bundle for Babel and all the used plugins which is exactly the expected file size here.
This will thus add a 2.8MB download size to the next package, but save downloading any babel dependencies separately, removing a large number of package dependencies from the overall install.
This is a prerequisite to being able to ncc inline the Babel dependencies in next.js.
The removal of preset-modules is based on replacing it with preset-env under `targets: { esmodules: true }`, as per the guidance from the package (https://www.npmjs.com/package/@babel/preset-modules):
> Starting from @babel/preset-env 7.9.0, you can enable the bugfixes: true option to get the same behavior as using @babel/preset-modules, but with support for custom targets. If you need to target browsers with native modules support (like this preset does), you can use targets: { esmodules: true }.
From the above, I'm pretty sure this is entirely a backwards compatible change, apart from the change to the runtime plugin list being visible. Perhaps @developit can confirm this as well.
When visiting a non-locale prefixed path (`/hello` instead of `/fr/hello`) we don't trigger locale redirects currently so if another locale is matched we need to ensure this is reset to the `defaultLocale` for rendering to prevent a mis-match on the client and the server.
This also fixes hydration errors from occurring with `asPath` for `getServerSideProps` pages due to `normalizeLocalePath` expecting only a pathname and `asPath` containing `hash` and `query values also.
Fixes: https://github.com/vercel/next.js/issues/18337
Fixes: https://github.com/vercel/next.js/issues/18510
This makes sure we don't use invalid `x-now-route-matches` which can occur when `i18n` default locale is visited and a prerendered page is matched. To correct this we first check if we are able to derive the correct params from the URL and then bail on parsing `x-now-route-matches` if we are. Additional test cases are being added in the builder to ensure we don't regress on this
x-ref: https://github.com/vercel/next.js/discussions/18443Fixes#18602
This ensures we provide the current `locale`, `locales`, and `defaultLocale` in the context when rendering the 404 for a blocking SSG page
Fixes: https://github.com/vercel/next.js/issues/18505
This ensures that when using a `pages/404` file with `getStaticProps` that we call `getStaticProps` in `fallback: 'blocking'` mode
Fixes: https://github.com/vercel/next.js/issues/18293
This updates the fallback 404 handling to render the correct 404 page on the client when a 404 is returned from fetching the data route on a fallback page on the client. This prevents us from having to rely on a cache to be updated by the time we reload the page to prevent non-stop reloading.
This also adds handling in serverless mode to ensure the correct 404 page is rendered when leveraging fallback: 'blocking' mode.
Additional tests for the fallback: 'blocking' 404 handling will be added in a follow-up where returning notFound from `getServerSideProps` is also added.
This makes sure the `locales` are passed to `getStaticPaths` and also disables the removing the default locale from the path when the default locale is the preferred header. It also updates tests to ensure the domain redirects are working as expected.
x-ref: https://github.com/vercel/next.js/pull/17370
This makes sure that we detect the correct default locale for domain specific locales since a domain can have a different default locale residing at the root and we need to check this on the client for prerendered/auto-static pages. This also makes sure we disable the built-in redirect handling when on Vercel since it's handled already.
Tests for this are tricky since we need to load the browser with a custom domain which requires editing the host file. Existing tests should ensure this doesn't break non-domain specific locale behavior though. This was also tested manually while testing https://github.com/vercel/vercel/pull/5298
x-ref: https://github.com/vercel/next.js/pull/17370
This makes sure the correct `initialRevalidateSeconds` field is populated in the `prerender-manifest` for non-dynamic SSG pages since they will be inserted into the `initialPageRevalidationMap` under their locale prefixed variant with `i18n` enabled
x-ref: https://github.com/vercel/next.js/pull/17370
This adds the `locale` prop for `next/link` to allow transitioning between locales client-side and also allows passing the locale to `router.push/replace` via the transition options similar to `shallow` e.g. `router.push('/another', '/another, { locale: 'nl' })`
x-ref: https://github.com/vercel/next.js/pull/17370
This updates to set the `NEXT_LOCALE` cookie to the default locale when the user prefers a different locale from the default in their `accept-language` header but visits the default locale path e.g. `/en-US` with a `accept-language` preferred header of `nl` will set the `NEXT_LOCALE=en-US` header and then redirect to `/`
x-ref: https://github.com/vercel/next.js/pull/17370
Follow-up to https://github.com/vercel/next.js/pull/17370 this adds mapping of locales to domains and handles default locales for specific domains also allowing specifying which locales can be visited for each domain.
This PR also updates to output all statically generated pages under the locale prefix to make it easier to locate/lookup and to not redirect to the default locale prefixed path when no `accept-language` header is provided.
Follow-up PR to #17370 this adds generating auto-export, non-dynamic SSG, and fallback pages with all locales. Dynamic SSG pages still control which locales the pages are generated with using `getStaticPaths`. To further control which locales non-dynamic SSG pages will be prerendered with a follow-up PR adding handling for 404 behavior from `getStaticProps` will be needed.
x-ref: https://github.com/vercel/next.js/issues/17110
This is a follow-up to https://github.com/vercel/next.js/pull/16973 which adds handling for the breaking change in the latest version of css-loader that causes unresolved file references in `url` or `import` to cause the build to fail. This fixes it by adding our own resolve checking and when it fails disabling the `css-loader`'s handling of it.
Fixes: https://github.com/vercel/next.js/issues/17701
Follow-up PR to https://github.com/vercel/next.js/pull/17370 when the path is not prefixed with a locale and the default locale is the detected locale it doesn't redirect to locale prefixed variant. If the default locale path is visited and the default locale is visited this also redirects to the root removing the un-necessary locale in the URL.
This also exposes the `defaultLocale` on the router since the RFC mentions `Setting a defaultLocale is required in every i18n library so it'd be useful for Next.js to provide it to the application.` although doesn't explicitly spec where we want to expose it. If we want to expose it differently this can be updated.
This adds the initial changes outlined in the [i18n routing RFC](https://github.com/vercel/next.js/discussions/17078). This currently treats the locale prefix on routes similar to how the basePath is treated in that the config doesn't require any changes to your pages directory and is automatically stripped/added based on the detected locale that should be used.
Currently redirecting occurs on the `/` route if a locale is detected regardless of if an optional catch-all route would match the `/` route or not we may want to investigate whether we want to disable this redirection automatically if an `/index.js` file isn't present at root of the pages directory.
TODO:
- [x] ensure locale detection/populating works in serverless mode correctly
- [x] add tests for locale handling in different modes, fallback/getStaticProps/getServerSideProps
To be continued in fall-up PRs
- [ ] add tests for revalidate, auto-export, basePath + i18n
- [ ] add mapping of domains with locales
- [ ] investigate detecting locale against non-index routes and populating the locale in a cookie
x-ref: https://github.com/vercel/next.js/issues/17110
This makes sure we have the correct `asPath` value to prevent breaking hydration for `getServerSideProps` pages and doesn't re-use the `resolvedUrl` value for the `asPath` and instead creates a separate `resolvedAsPath` value that only removes the `_next/data` prefix from the path. Additional tests have been added in the `getServerSideProps` suite to ensure correct `asPath` with rewrites.
Fixes: https://github.com/vercel/next.js/issues/17113
This continues off of https://github.com/vercel/next.js/pull/17081 and provides this normalized `asPath` value in the context provided to `getServerSideProps` to provide the consistent value since the request URL can vary between direct visit and client transition and the alternative requires building the URL each time manually.
Kept this change separate from https://github.com/vercel/next.js/pull/17081 since this is addressing a separate issue and allows discussion separately.
Closes: https://github.com/vercel/next.js/issues/16407
This normalizes the `asPath` for `getServerSideProps` and `getStaticProps` pages to ensure it matches the value that would show on the client instead of a) the output pathname when revalidating or generating a fallback or b) the `_next/data` URL on client transition.
Fixes: https://github.com/vercel/next.js/issues/16542
To prevent FOUC, discussed in #10557 i need to store information about css file dependencies for chunk. Right now current implementation just throws away everything but js.
Can there be more than one css file in chunk? If no - code will be simplified.
closes#10557
This fixes a client-side file not being transpiled correctly when rewrites are used. The cross browser tests have been updated to make sure there are rewrites so the related code is included and not dead-code eliminated'
Closes: https://github.com/vercel/next.js/issues/16440
This corrects the case where `/index` is used during revalidation for an optional catch-all route and `index` is passed as a param even though it should be undefined. This also adds test cases to make sure the params are normalized correctly
Fixes: https://github.com/vercel/next.js/issues/16366
This interpolates the dynamic values and rebuilds the request URL for fallback SSG pages since the proxy uses the output path for non-prerendered pages on Vercel which can cause inconsistent request URL/`asPath` values for SSG pages. This also adds tests to ensure the `asPath` is correctly updated
Fixes: https://github.com/vercel/next.js/issues/16269
This updates to not automatically append params to the query for rewrites if one or more of the params are already used in the destination's path. No other behavior is being changed and if the user still wants the params in the query after using them in the destination's path they can manually add them like with redirects.
Closes: https://github.com/vercel/next.js/issues/15626
This pull request edits the `BuildManifest` that is sent to `/_document` instead of modifying a single input array to decouple its implementation details.
Optimally, we'd eliminate the `files` key all together.
---
Related to #16182
Since we now use query parameters to pass dynamic route params while routing on Vercel, this makes sure we normalize the request URL before populating the `asPath`
Fixes: https://github.com/vercel/next.js/issues/15879
- Using `namedChunks` where possible, this will also allow for faster access to the chunks as we no longer have to look them up like we did before using `find`
- Using the new asset hooks introduced in the latest webpack beta
- Using the new externals function signature
This updates collecting dynamic route params on Vercel to make sure that missing optional dynamic routes are undefined. Additional tests for this mode have also been added to ensure the params are being collected properly
Closes: https://github.com/vercel/next.js/issues/15579
This adds handling for custom-routes with `basePath` to automatically add the `basePath` for custom-routes `source` and `destination` unless `basePath: false` is set for the route.
Closes: https://github.com/vercel/next.js/issues/14782
Discovered while working on https://github.com/vercel/next.js/pull/14848
when asPath is the same but href is different it should use `replaceState` instead of `pushState`, so that browser back/forward behavior is preserved. Currently it's comparing a path that includes basepath with one that excludes it, so `pushState` is always used. This makes sure the behavior is the same as when running next.js without a basepath
This makes sure to base64 encode the `.env*` file contents before passing them in the URL for the serverless-loader since `!` is a special character in this case which can cause webpack to fail to build
Closes: https://github.com/vercel/next.js/issues/14749
Initial PR to make `next build` work with webpack 5, still needs more work to make sure runtimeChunk and such are shared between pages.
- No longer needs the custom ChunkNamesPlugin as the default behavior was changed
- Dropping AMP First client page bundles is now compatible
We previously used to remove our FOUC helper inside of the style injection to ensure content was shown as fast as possible.
This behavior, however, was problematic for a few reasons:
1. Large JavaScript chunks would take longer than an animation frame to parse, causing FOUC
1. Rendering would sometimes complete before an animation frame, causing improper effects
To fix the latter, we started removing the no FOUC helper **before** rendering, however, we never fixed the former by removing the dead code.
There's not a great way to test this because the FOUC is so fast and flaky, however, this code really shouldn't exist and isn't likely to be re-added (regress).
Also, we already have FOUC tests that occasionally flake, probably due to this.
Fixes#12448Fixes#13058Fixes#11195Fixes#10404
Updates the way filenames are generated for browser compilation.
Notably:
- All entry bundles now have hashes in production, this includes pages (previously pages used a buildId in the path)
- The AmpFiles no longer depends on hardcoded bundle names, it uses the buildManifest instead (internals)
- All cases where we match the page name from the chunk/entrypoint name now use the same function `getRouteFromEntrypoint` (internals)
- In development we no longer include the "faked" `buildId` set to `development` for page files, instead we just use the `/_next/static/pages` path (was `/_next/static/development/pages`). This was changed as it caused unneeded complexity and makes generating the bundles easier (internals)
- Updated tons of tests to be more resilient to these changes by relying on the buildManifest instead of hardcoded paths (internals)
Follow up of these PRs:
https://github.com/vercel/next.js/pull/13759https://github.com/vercel/next.js/pull/13870https://github.com/vercel/next.js/pull/13937https://github.com/vercel/next.js/pull/14130https://github.com/vercel/next.js/pull/14176https://github.com/vercel/next.js/pull/14268Fixes#6303Fixes#12087Fixes#1948Fixes#4368Fixes#4255Fixes#2548
This toggles the separate Windows `devtool` setting for WSL. We cannot test this as we do not have access to WSL in our current test setup suite, however, this is a temporary patch that should be fixed with the webpack 5 upgrade, so I do not feel strongly about testing it.
---
Fixes#14253
To make `asPath` consistent with `basePath` handling this makes sure it is always stripped including on the client under the `asPath` value and from `req.url` in the `serverless-loader`. Additional tests have been added for this behavior to ensure we don't regress on this
Closes: https://github.com/vercel/next.js/issues/14037
Closes: https://github.com/vercel/next.js/issues/14039
Webpack will randomly execute script order if its runtime is not prioritized before chunks execute.
This seems to be somehow triggered in #13870 because of slightly different script ordering.
This had actually broke CSS, which is why our tests are failing 50% of the time:
Without this PR:
![image](https://user-images.githubusercontent.com/616428/84221491-57f0a000-aaa3-11ea-9dff-c27c87d29ac5.png)
However, it's still problematic to use `async` in development since we rely on script execution order. So, this PR disables `async` in development.
We're exploring `defer` in the future anyway (over `async`), which will be ordered, so I don't mind diverging between dev and prod in this way.
---
Fixes#13911
Initial work to use chunkhashes instead of buildid for the page files in production. This does not change the calculation of the filename itself initially.
Disambiguate between pages/index.js and pages/index/index.js so that they resolve differently.
It all started with a bug in pagesmanifest that propagated throughout the codebase. After fixing pagesmanifest I was able to remove a few hacks here and there and more logic is shared now. especially the logic that resolves an entrypoint back into a route path. To sum up what happened:
- `getRouteFromEntrypoint` is the inverse operation of `getPageFile` that's under `pages/_document.tsx`
- `denormalizePagePath` is the inverse operation of `normalizePagePath`.
Everything is refactored in terms of these operations, that makes their behavior uniform and easier to update/patch in a central place. Before there were subtle differences between those that made `index/index.js` hard to handle.
Some potential follow up on this PR:
- [`hot-reloader`](https://github.com/vercel/next.js/pull/13699/files#diff-6161346d2c5f4b7abc87059d8768c44bR207) still has one place that does very similar behavior to `getRouteFromEntrypoint`. It can probably be rewritten in terms of `getRouteFromEntrypoint`.
- There are a few places where `denormalizePagePath(normalizePagePath(...))` is happening. This is a sign that `normalizePagePath` is doing some validation that is independent of its rewriting logic. That should probably be factored out in its own function. after that I should probably investigate whether `normalizePagePath` is even still needed at all.
- a lot of code is doing `.replace(/\\/g, '')`. If wanted, that could be replaced with `normalizePathSep`.
- It looks to me like some logic that's spread across the project can be centralized in 4 functions
- `getRouteFromEntrypoint` (part of this PR)
- its inverse `getEntrypointFromRoute` (already exists in `_document.tsx` as `getPageFile`)
- `getRouteFromPageFile`
- its inverse `getPageFileFromRoute` (already exists as `findPageFile ` in `server/lib/find-page-file.ts`)
It could be beneficial to structure the code to keep these fuctionalities close together and name them similarly.
- revise `index.amp` handling in pagesmanifest. I left it alone in this PR to keep it scoped, but it may be broken wrt nested index files as well. It might even make sense to reshape the pagesmanifest altogether to handle html/json/amp/... better
This removes remaining references to `granularChunks` in configs, error messages, and comments.
Also removed the `process.env.__NEXT_GRANULAR_CHUNKS` value.
---
Follow up to: https://github.com/vercel/next.js/pull/13663
In serverless mode, it's best practice to propagate an unhandled error so that the function is disposed instead of recycled. This helps fix the "bad state" problem.
Was going through _document and noticed some variable shadowing going on. Added a rule for it to our eslint configuration and went through all warnings with @Timer.
By default, webpack will proceed to run loaders and plugins on all files, even after an error has been encountered during the build process.
This means you might need to wait minutes to see a syntax error encountered in one of your source files. This PR fixes that.
The experimental modern mode runs the type checking plugin twice, which **occasionally** suffers from a race condition that hangs the build.
This PR fixes type checking to only be run once.
While this test cannot 100% reproduce/capture the race condition, I don't feel strongly about the test case:
- We're planning on eliminating this type checking plugin ASAP (for a faster alternative)
- Modern mode implementation as-is will probably go away with webpack 5
As discussed this adds bundling of `.env` files in `serverless` mode so that the environment values are also available when deploying with this target
closes: https://github.com/zeit/next.js/issues/13332
This PR adds support for prepending sass code before the actual entry file.
It's common for developers to import their sass mixins and variables once on their project config so they don't need to import them on every file that requires it. Frameworks like gatsby and nuxt.js already support that handy feature.
The way it works is:
```
/// next.config.js
module.exports = {
experimental: {
sassOptions: {
prependData: `
/// Scss code that you want to be
/// prepended to every single scss file.
`,
},
},
}
```
Fixes#11617 and duplicates
Adding a conformance plugin the make sure users don't undo the benefits of the granularChunks config.
The plugin makes sure that minSize, maxInitialRequests values aren't overridden. Also ensures the cacheGroups - vendors, framework, libs, common, shared are maintained.
The warning and error messages do not break the build with this change. They only display a message.
cc - @prateekbh, @atcastle
* Add basePath in link component and add/remove it consistently
* Update to not use regex for delBasePath
* Expose addBasePath as router method
* Revert "Expose addBasePath as router method"
This reverts commit 40fed596195c6affabf837e42d472452768e13a3.
* Expose basePath as router field
* Apply suggestion
* Expose basePath as router field
* remove un-used vars
* Update externals
* Apply lint fix
* Update size-limit test
* Update prefetch