Next.js Compiler
The Next.js Compiler, written in Rust using SWC, 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, your application will opt-out of the Next.js Compiler and continue using Babel.
Why SWC?β
SWC 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.
First, update to the latest version of Next.js: npm install next@latest
. Then, update your next.config.js
file:
module.exports = {
compiler: {
styledComponents: true,
},
}
For advanced use cases, you can configure individual properties for styled-components compilation.
Note:
ssr
anddisplayName
transforms are the main requirement for usingstyled-components
in Next.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,
// Enabled by default.
transpileTemplateLiterals?: boolean,
// Empty by default.
namespace?: string,
// Disabled by default.
pure?: boolean,
// 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) intoprocess.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:
const nextJest = require('next/jest')
// Providing the path to your Next.js app which will enable loading next.config.js and .env files
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 support:
module.exports = {
compiler: {
relay: {
// This should match relay.config.js
src: './',
artifactDirectory: './__generated__',
language: 'typescript',
eagerEsModules: false,
},
},
}
Good to know: In Next.js, all JavaScript files in
pages
directory are considered routes. So, forrelay-compiler
you'll need to specifyartifactDirectory
configuration settings outside of thepages
, otherwiserelay-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
:
module.exports = {
compiler: {
reactRemoveProperties: true,
},
}
To remove custom properties:
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:
module.exports = {
compiler: {
removeConsole: true,
},
}
Remove console.*
output except console.error
:
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:
{
"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.
First, update to the latest version of Next.js: npm install next@latest
. Then, update your jsconfig.json
or tsconfig.json
file:
{
"compilerOptions": {
"jsxImportSource": "theme-ui"
}
}
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:
module.exports = {
compiler: {
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],
}
}
},
},
},
}
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.
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.
module.exports = {
transpilePackages: ['@acme/ui', 'lodash-es'],
}
Modularize Importsβ
This option has been superseded by 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.
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.
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. 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 and Modularize Imports stable. |
v13.0.0 | SWC Minifier enabled by default. |
v12.3.0 | SWC Minifier stable. |
v12.2.0 | SWC Plugins 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. |