Next.js Compiler

Version History

VersionChanges
v12.3.0SWC Minifier stable.
v12.2.0SWC Plugins experimental support added.
v12.1.0Added support for Styled Components, Jest, Relay, Remove React Properties, Legacy Decorators, Remove Console, and jsxImportSource.
v12.0.0Next.js Compiler introduced.

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:

  1. module.exports = {
  2. compiler: {
  3. // see https://styled-components.com/docs/tooling#babel-plugin for more info on the options.
  4. styledComponents: boolean | {
  5. // Enabled by default in development, disabled in production to reduce file size,
  6. // setting this will override the default for all environments.
  7. displayName?: boolean,
  8. // Enabled by default.
  9. ssr?: boolean,
  10. // Enabled by default.
  11. fileName?: boolean,
  12. // Empty by default.
  13. topLevelImportPaths?: string[],
  14. // Defaults to ["index"].
  15. meaninglessFileNames?: string[],
  16. // Enabled by default.
  17. cssProp?: boolean,
  18. // Empty by default.
  19. namespace?: string,
  20. // Not supported yet.
  21. minify?: boolean,
  22. // Not supported yet.
  23. transpileTemplateLiterals?: boolean,
  24. // Not supported yet.
  25. pure?: boolean,
  26. },
  27. },
  28. }

minify, transpileTemplateLiterals and pure are not yet implemented. You can follow the progress here. ssr and displayName transforms are the main requirement for using styled-components in Next.js.

Jest

Jest support not only includes the transformation previously provided by Babel, but also 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:

  1. // jest.config.js
  2. const nextJest = require('next/jest')
  3. // Providing the path to your Next.js app which will enable loading next.config.js and .env files
  4. const createJestConfig = nextJest({ dir: './' })
  5. // Any custom config you want to pass to Jest
  6. const customJestConfig = {
  7. setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  8. }
  9. // createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
  10. module.exports = createJestConfig(customJestConfig)

Relay

To enable Relay support:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. relay: {
  5. // This should match relay.config.js
  6. src: './',
  7. artifactDirectory: './__generated__',
  8. language: 'typescript',
  9. },
  10. },
  11. }

NOTE: 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:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. reactRemoveProperties: true,
  5. },
  6. }

To remove custom properties:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. // The regexes defined here are processed in Rust so the syntax is different from
  5. // JavaScript `RegExp`s. See https://docs.rs/regex.
  6. reactRemoveProperties: { properties: ['^data-custom$'] },
  7. },
  8. }

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:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. removeConsole: true,
  5. },
  6. }

Remove console.* output except console.error:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. removeConsole: {
  5. exclude: ['error'],
  6. },
  7. },
  8. }

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:

  1. {
  2. "compilerOptions": {
  3. "experimentalDecorators": true
  4. }
  5. }

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:

  1. {
  2. "compilerOptions": {
  3. "jsxImportSource": 'preact'
  4. }
  5. }

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:

  1. // next.config.js
  2. module.exports = {
  3. compiler: {
  4. emotion: boolean | {
  5. // default is true. It will be disabled when build type is production.
  6. sourceMap?: boolean,
  7. // default is 'dev-only'.
  8. autoLabel?: 'never' | 'dev-only' | 'always',
  9. // default is '[local]'.
  10. // Allowed values: `[local]` `[filename]` and `[dirname]`
  11. // This option only works when autoLabel is set to 'dev-only' or 'always'.
  12. // It allows you to define the format of the resulting label.
  13. // The format is defined via string where variable parts are enclosed in square brackets [].
  14. // For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
  15. labelFormat?: string,
  16. },
  17. },
  18. }

Only importMap in @emotion/babel-plugin is not supported for now.

Minification

You can opt-in to using the Next.js compiler for minification. This is 7x faster than Terser.

  1. // next.config.js
  2. module.exports = {
  3. swcMinify: true,
  4. }

If you have feedback about swcMinify, please share it on the feedback discussion.

Experimental Features

Minifier debug options

While the minifier is experimental, we are making the following options available for debugging purposes. They will not be available once the minifier is made stable.

  1. // next.config.js
  2. module.exports = {
  3. experimental: {
  4. swcMinifyDebugOptions: {
  5. compress: {
  6. defaults: true,
  7. side_effects: false,
  8. },
  9. },
  10. },
  11. swcMinify: true,
  12. }

If your app works with the options above, it means side_effects is the problematic option. See the SWC documentation for detailed options.

Modularize Imports

Allows to modularize imports, similar to babel-plugin-transform-imports.

Transforms member style imports:

  1. import { Row, Grid as MyGrid } from 'react-bootstrap'
  2. import { merge } from 'lodash'

…into default style imports:

  1. import Row from 'react-bootstrap/lib/Row'
  2. import MyGrid from 'react-bootstrap/lib/Grid'
  3. import merge from 'lodash/merge'

Config for the above transform:

  1. // next.config.js
  2. module.exports = {
  3. experimental: {
  4. modularizeImports: {
  5. 'react-bootstrap': {
  6. transform: 'react-bootstrap/lib/{{member}}',
  7. },
  8. lodash: {
  9. transform: 'lodash/{{member}}',
  10. },
  11. },
  12. },
  13. }

Advanced transformations:

  • Using regular expressions

Similar to babel-plugin-transform-imports, but the transform is templated with handlebars and regular expressions are in Rust regex crate’s syntax.

The config:

  1. // next.config.js
  2. module.exports = {
  3. experimental: {
  4. modularizeImports: {
  5. 'my-library/?(((\\w*)?/?)*)': {
  6. transform: 'my-library/{{ matches.[1] }}/{{member}}',
  7. },
  8. },
  9. },
  10. }

Cause this code:

  1. import { MyModule } from 'my-library'
  2. import { App } from 'my-library/components'
  3. import { Header, Footer } from 'my-library/components/App'

To become:

  1. import MyModule from 'my-library/MyModule'
  2. import App from 'my-library/components/App'
  3. import Header from 'my-library/components/App/Header'
  4. import Footer from 'my-library/components/App/Footer'
  • Handlebars templating

This transform uses handlebars to template the replacement import path in the transform field. These variables and helper functions are available:

  1. matches: Has type string[]. All groups matched by the regular expression. matches.[0] is the full match.
  2. member: Has type string. The name of the member import.
  3. lowerCase, upperCase, camelCase, kebabCase: Helper functions to convert a string to lower, upper, camel or kebab cases.

SWC Trace profiling

You can generate SWC’s internal transform traces as chromium’s trace event format.

  1. // next.config.js
  2. module.exports = {
  3. experimental: {
  4. swcTraceProfiling: true,
  5. },
  6. }

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.

  1. // next.config.js
  2. module.exports = {
  3. experimental: {
  4. swcPlugins: [
  5. [
  6. 'plugin',
  7. {
  8. ...pluginOptions,
  9. },
  10. ],
  11. ],
  12. },
  13. }

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.