rsnext/docs/04-architecture/nextjs-compiler.mdx

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

322 lines
13 KiB
Text
Raw Normal View History

---
title: Next.js Compiler
description: Next.js Compiler, written in Rust, which transforms and minifies your Next.js application.
---
The Next.js Compiler, written in Rust using [SWC](https://swc.rs/), allows Next.js to transform and minify your JavaScript code for production. This replaces Babel for individual files and Terser for minifying output bundles.
Compilation using the Next.js Compiler is 17x faster than Babel and enabled by default since Next.js version 12. If you have an existing Babel configuration or are using [unsupported features](#unsupported-features), your application will opt-out of the Next.js Compiler and continue using Babel.
## Why SWC?
[SWC](https://swc.rs/) is an extensible Rust-based platform for the next generation of fast developer tools.
SWC can be used for compilation, minification, bundling, and more and is designed to be extended. It's something you can call to perform code transformations (either built-in or custom). Running those transformations happens through higher-level tools like Next.js.
We chose to build on SWC for a few reasons:
- **Extensibility:** SWC can be used as a Crate inside Next.js, without having to fork the library or workaround design constraints.
- **Performance:** We were able to achieve ~3x faster Fast Refresh and ~5x faster builds in Next.js by switching to SWC, with more room for optimization still in progress.
- **WebAssembly:** Rust's support for WASM is essential for supporting all possible platforms and taking Next.js development everywhere.
- **Community:** The Rust community and ecosystem are amazing and still growing.
## Supported Features
### Styled Components
We're working to port `babel-plugin-styled-components` to the Next.js Compiler.
2021-11-21 12:58:34 +01:00
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `next.config.js` file:
```js filename="next.config.js"
module.exports = {
compiler: {
styledComponents: true,
},
}
```
For advanced use cases, you can configure individual properties for styled-components compilation.
fix(docs): update styled components option (#65718) To [Port babel-plugin-styled-components to SWC](https://github.com/vercel/next.js/issues/30802) was completed, apply and re-order options. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Co-authored-by: Sam Ko <sam@vercel.com>
2024-05-20 21:35:20 +02:00
> Note: `ssr` and `displayName` transforms are the main requirement for using `styled-components` in Next.js.
```js filename="next.config.js"
module.exports = {
compiler: {
// see https://styled-components.com/docs/tooling#babel-plugin for more info on the options.
styledComponents: {
// Enabled by default in development, disabled in production to reduce file size,
// setting this will override the default for all environments.
displayName?: boolean,
// Enabled by default.
ssr?: boolean,
// Enabled by default.
fileName?: boolean,
// Empty by default.
topLevelImportPaths?: string[],
// Defaults to ["index"].
meaninglessFileNames?: string[],
// Enabled by default.
minify?: boolean,
fix(docs): update styled components option (#65718) To [Port babel-plugin-styled-components to SWC](https://github.com/vercel/next.js/issues/30802) was completed, apply and re-order options. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Co-authored-by: Sam Ko <sam@vercel.com>
2024-05-20 21:35:20 +02:00
// Enabled by default.
transpileTemplateLiterals?: boolean,
fix(docs): update styled components option (#65718) To [Port babel-plugin-styled-components to SWC](https://github.com/vercel/next.js/issues/30802) was completed, apply and re-order options. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Co-authored-by: Sam Ko <sam@vercel.com>
2024-05-20 21:35:20 +02:00
// Empty by default.
namespace?: string,
// Disabled by default.
pure?: boolean,
fix(docs): update styled components option (#65718) To [Port babel-plugin-styled-components to SWC](https://github.com/vercel/next.js/issues/30802) was completed, apply and re-order options. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Co-authored-by: Sam Ko <sam@vercel.com>
2024-05-20 21:35:20 +02:00
// Enabled by default.
cssProp?: boolean,
},
},
}
```
### Jest
The Next.js Compiler transpiles your tests and simplifies configuring Jest together with Next.js including:
- Auto mocking of `.css`, `.module.css` (and their `.scss` variants), and image imports
- Automatically sets up `transform` using SWC
- Loading `.env` (and all variants) into `process.env`
- Ignores `node_modules` from test resolving and transforms
- Ignoring `.next` from test resolving
- Loads `next.config.js` for flags that enable experimental SWC transforms
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jest.config.js` file:
```js filename="jest.config.js"
const nextJest = require('next/jest')
// Providing the path to your Next.js app which will enable loading next.config.js and .env files
Update Jest config with SWC docs (#37705) ## Motivation/ Context - When upgrading `next` from `11` to `12`, I followed [Upgrade guide from 11 => 12](https://nextjs.org/docs/upgrading#upgrading-from-11-to-12). I removed `.babelrc` to opt-in `SWC`. I thought that's all, but after removing `.babelrc`, Jest broke immediately. So I follow the guide https://nextjs.org/docs/advanced-features/compiler#jest to configure Jest to work with SWC. I copied the content of `jest.config.js` to my project but it does not work. The reason: ```diff -const createJestConfig = nextJest({ dir }) // `dir` IS NOT DEFINED +const createJestConfig = nextJest({ dir: './' }) // Should change to this. Sync with https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler ``` - This PR is to help others to configure Jest with SWC by copying code from the documentation site without encountering the same issue as I did. ## Documentation - [x] Update the docs so users can just copy and paste when configuring Jest with SWC (Sync with https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler) - [x] Make sure the linting passes by running `pnpm lint` - [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples) ## Future work - Since [Upgrade guide from 11 => 12](https://nextjs.org/docs/upgrading#upgrading-from-11-to-12) did not mention anything about Jest. If I remove `.babelrc` to opt-in SWC. The current Jest settings will crash (since it's using babel). We likely want to update the Upgrade guide to mention this cc: @leerob
2022-06-15 13:27:28 +02:00
const createJestConfig = nextJest({ dir: './' })
// Any custom config you want to pass to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
module.exports = createJestConfig(customJestConfig)
```
### Relay
To enable [Relay](https://relay.dev/) support:
```js filename="next.config.js"
module.exports = {
compiler: {
relay: {
// This should match relay.config.js
src: './',
artifactDirectory: './__generated__',
language: 'typescript',
2023-03-29 01:08:40 +02:00
eagerEsModules: false,
},
},
}
```
> **Good to know**: In Next.js, all JavaScript files in `pages` directory are considered routes. So, for `relay-compiler` you'll need to specify `artifactDirectory` configuration settings outside of the `pages`, otherwise `relay-compiler` will generate files next to the source file in the `__generated__` directory, and this file will be considered a route, which will break production builds.
### Remove React Properties
Allows to remove JSX properties. This is often used for testing. Similar to `babel-plugin-react-remove-properties`.
To remove properties matching the default regex `^data-test`:
```js filename="next.config.js"
module.exports = {
compiler: {
reactRemoveProperties: true,
},
}
```
To remove custom properties:
```js filename="next.config.js"
module.exports = {
compiler: {
// The regexes defined here are processed in Rust so the syntax is different from
// JavaScript `RegExp`s. See https://docs.rs/regex.
reactRemoveProperties: { properties: ['^data-custom$'] },
},
}
```
### Remove Console
This transform allows for removing all `console.*` calls in application code (not `node_modules`). Similar to `babel-plugin-transform-remove-console`.
Remove all `console.*` calls:
```js filename="next.config.js"
module.exports = {
compiler: {
removeConsole: true,
},
}
```
Remove `console.*` output except `console.error`:
```js filename="next.config.js"
module.exports = {
compiler: {
removeConsole: {
exclude: ['error'],
},
},
}
```
### Legacy Decorators
Next.js will automatically detect `experimentalDecorators` in `jsconfig.json` or `tsconfig.json`. Legacy decorators are commonly used with older versions of libraries like `mobx`.
This flag is only supported for compatibility with existing applications. We do not recommend using legacy decorators in new applications.
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jsconfig.json` or `tsconfig.json` file:
```js
{
"compilerOptions": {
"experimentalDecorators": true
}
}
```
### importSource
Next.js will automatically detect `jsxImportSource` in `jsconfig.json` or `tsconfig.json` and apply that. This is commonly used with libraries like [Theme UI](https://theme-ui.com).
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jsconfig.json` or `tsconfig.json` file:
```js
{
"compilerOptions": {
"jsxImportSource": "theme-ui"
}
}
```
2022-03-15 08:51:15 +01:00
### Emotion
We're working to port `@emotion/babel-plugin` to the Next.js Compiler.
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `next.config.js` file:
```js filename="next.config.js"
2022-03-15 08:51:15 +01:00
module.exports = {
compiler: {
2022-03-15 08:51:15 +01:00
emotion: boolean | {
// default is true. It will be disabled when build type is production.
sourceMap?: boolean,
// default is 'dev-only'.
autoLabel?: 'never' | 'dev-only' | 'always',
// default is '[local]'.
// Allowed values: `[local]` `[filename]` and `[dirname]`
// This option only works when autoLabel is set to 'dev-only' or 'always'.
// It allows you to define the format of the resulting label.
// The format is defined via string where variable parts are enclosed in square brackets [].
// For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
labelFormat?: string,
// default is undefined.
// This option allows you to tell the compiler what imports it should
// look at to determine what it should transform so if you re-export
// Emotion's exports, you can still use transforms.
importMap?: {
[packageName: string]: {
[exportName: string]: {
canonicalImport?: [string, string],
styledBaseImport?: [string, string],
}
}
},
2022-03-15 08:51:15 +01:00
},
},
}
```
### Minification
Next.js' swc compiler is used for minification by default since v13. This is 7x faster than Terser.
If Terser is still needed for any reason this can be configured.
```js filename="next.config.js"
module.exports = {
swcMinify: false,
}
```
### Module Transpilation
Next.js can automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`). This replaces the `next-transpile-modules` package.
```js filename="next.config.js"
module.exports = {
transpilePackages: ['@acme/ui', 'lodash-es'],
}
```
### Modularize Imports
This option has been superseded by [`optimizePackageImports`](/docs/app/api-reference/next-config-js/optimizePackageImports) in Next.js 13.5. We recommend upgrading to use the new option that does not require manual configuration of import paths.
## Experimental Features
### SWC Trace profiling
You can generate SWC's internal transform traces as chromium's [trace event format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview?mode=html#%21=).
```js filename="next.config.js"
module.exports = {
experimental: {
swcTraceProfiling: true,
},
}
```
Once enabled, swc will generate trace named as `swc-trace-profile-${timestamp}.json` under `.next/`. Chromium's trace viewer (chrome://tracing/, https://ui.perfetto.dev/), or compatible flamegraph viewer (https://www.speedscope.app/) can load & visualize generated traces.
### SWC Plugins (experimental)
You can configure swc's transform to use SWC's experimental plugin support written in wasm to customize transformation behavior.
```js filename="next.config.js"
module.exports = {
experimental: {
swcPlugins: [
[
'plugin',
{
...pluginOptions,
},
],
],
},
}
```
`swcPlugins` accepts an array of tuples for configuring plugins. A tuple for the plugin contains the path to the plugin and an object for plugin configuration. The path to the plugin can be an npm module package name or an absolute path to the `.wasm` binary itself.
## Unsupported Features
When your application has a `.babelrc` file, Next.js will automatically fall back to using Babel for transforming individual files. This ensures backwards compatibility with existing applications that leverage custom Babel plugins.
If you're using a custom Babel setup, [please share your configuration](https://github.com/vercel/next.js/discussions/30174). We're working to port as many commonly used Babel transformations as possible, as well as supporting plugins in the future.
## Version History
| Version | Changes |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v13.1.0` | [Module Transpilation](https://nextjs.org/blog/next-13-1#built-in-module-transpilation-stable) and [Modularize Imports](https://nextjs.org/blog/next-13-1#import-resolution-for-smaller-bundles) stable. |
| `v13.0.0` | SWC Minifier enabled by default. |
| `v12.3.0` | SWC Minifier [stable](https://nextjs.org/blog/next-12-3#swc-minifier-stable). |
| `v12.2.0` | [SWC Plugins](#swc-plugins-experimental) experimental support added. |
| `v12.1.0` | Added support for Styled Components, Jest, Relay, Remove React Properties, Legacy Decorators, Remove Console, and jsxImportSource. |
| `v12.0.0` | Next.js Compiler [introduced](https://nextjs.org/blog/next-12). |