Next.js コンパイラ
Next.js コンパイラは、Rust で SWC を使用して記述されており、Next.js が JavaScript コードを本番用に変換および最小化できるようにします。これは、個々のファイルに対して Babel を、出力バンドルの最小化に対して Terser を置き換えます。
Next.js コンパイラを使用したコンパイルは、Babel よりも 17 倍高速であり、Next.js バージョン 12 以降でデフォルトで有効になっています。既存の Babel 設定がある場合や、サポートされていない機能を使用している場合、アプリケーションは Next.js コンパイラからオプトアウトし、Babel を引き続き使用します。
SWC を使用する理由
SWC は、次世代の高速開発者ツールのための、拡張可能な Rust ベースのプラットフォームです。
SWC は、コンパイル、最小化、バンドルなどのために使用でき、拡張できるように設計されています。コード変換 (組み込みまたはカスタム) を実行するために呼び出すことができるものです。これらの変換の実行は、Next.js のような高レベルツールを通じて行われます。
いくつかの理由で SWC を基盤にすることを選択しました。
- 拡張性: SWC は、ライブラリをフォークしたり、設計上の制約を回避したりすることなく、Next.js 内で Crate として使用できます。
- パフォーマンス: SWC に切り替えることで、Next.js の Fast Refresh が約 3 倍、ビルドが約 5 倍高速になり、さらに最適化の余地も残っています。
- WebAssembly: Rust の WASM サポートは、すべての可能なプラットフォームをサポートし、Next.js 開発をどこにでも拡張するために不可欠です。
- コミュニティ: Rust コミュニティとエコシステムは素晴らしく、成長を続けています。
サポートされている機能
Styled Components
babel-plugin-styled-components を Next.js コンパイラに移植中です。
まず、Next.js の最新バージョンに更新します: npm install next@latest。次に、next.config.js ファイルを更新します。
module.exports = {
compiler: {
styledComponents: true,
},
}高度なユースケースでは、styled-components コンパイルの個々のプロパティを設定できます。
注:
ssrおよびdisplayName変換は、Next.js でstyled-componentsを使用するための主な要件です。
module.exports = {
compiler: {
// see https://styled-components.dokyumento.jp/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
Next.js コンパイラは、テストを変換し、Jest を Next.js と共に設定することを簡素化します。これには以下が含まれます。
.css、.module.css(およびそれらの.scssバリアント)、および画像インポートの自動モック- SWC を使用して
transformを自動的に設定します。 .env(およびすべてのバリアント) をprocess.envにロードします。- テスト解決および変換から
node_modulesを無視します。 - テスト解決から
.nextを無視します。 - 実験的な SWC 変換を有効にするフラグのために
next.config.jsをロードします。
まず、Next.js の最新バージョンに更新します: npm install next@latest。次に、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
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
Relay サポートを有効にするには
module.exports = {
compiler: {
relay: {
// This should match relay.config.js
src: './',
artifactDirectory: './__generated__',
language: 'typescript',
eagerEsModules: false,
},
},
}重要: Next.js では、
pagesディレクトリ内のすべての JavaScript ファイルがルートとして扱われます。したがって、relay-compilerの場合、artifactDirectory設定をpagesの外に指定する必要があります。そうしないと、relay-compilerはソースファイルの隣の__generated__ディレクトリにファイルを生成し、このファイルがルートとして扱われ、本番ビルドが失敗する可能性があります。
React プロパティの削除
JSX プロパティを削除できるようにします。これはテストによく使用されます。babel-plugin-react-remove-properties に似ています。
デフォルトの正規表現 ^data-test に一致するプロパティを削除するには
module.exports = {
compiler: {
reactRemoveProperties: true,
},
}カスタムプロパティを削除するには
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$'] },
},
}コンソールの削除
この変換により、アプリケーションコード (node_modules 以外) のすべての console.* 呼び出しを削除できます。babel-plugin-transform-remove-console に似ています。
すべての console.* 呼び出しを削除
module.exports = {
compiler: {
removeConsole: true,
},
}console.error 以外は console.* 出力を削除
module.exports = {
compiler: {
removeConsole: {
exclude: ['error'],
},
},
}レガシーデコレータ
Next.js は、jsconfig.json または tsconfig.json の experimentalDecorators を自動的に検出します。レガシーデコレータは、mobx のような古いバージョンのライブラリと共によく使用されます。
このフラグは、既存のアプリケーションとの互換性のためにのみサポートされています。新しいアプリケーションでのレガシーデコレータの使用は推奨しません。
まず、Next.js の最新バージョンに更新します: npm install next@latest。次に、jsconfig.json または tsconfig.json ファイルを更新します。
{
"compilerOptions": {
"experimentalDecorators": true
}
}importSource
Next.js は、jsconfig.json または tsconfig.json の jsxImportSource を自動的に検出し、それを適用します。これは、Theme UI のようなライブラリでよく使用されます。
まず、Next.js の最新バージョンに更新します: npm install next@latest。次に、jsconfig.json または tsconfig.json ファイルを更新します。
{
"compilerOptions": {
"jsxImportSource": "theme-ui"
}
}Emotion
@emotion/babel-plugin を Next.js コンパイラに移植中です。
まず、Next.js の最新バージョンに更新します: npm install next@latest。次に、next.config.js ファイルを更新します。
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],
}
}
},
},
},
}最小化
Next.js の swc コンパイラは、v13 以降、デフォルトで最小化に使用されます。これは Terser よりも 7 倍高速です。
重要: v15 から、
next.config.jsを使用した最小化のカスタマイズはできなくなりました。swcMinifyフラグのサポートは削除されました。
モジュール変換
Next.js は、ローカルパッケージ(monorepos など)または外部依存関係 (node_modules) からの依存関係を自動的にトランスパイルおよびバンドルできます。これは next-transpile-modules パッケージに取って代わるものです。
module.exports = {
transpilePackages: ['@acme/ui', 'lodash-es'],
}インポートのモジュール化
このオプションは、Next.js 13.5 の optimizePackageImports によって置き換えられました。手動でのインポートパスの設定が不要な新しいオプションを使用することをお勧めします。
define (ビルド時に変数を置き換える)
define オプションを使用すると、ビルド時にコード内の変数を静的に置き換えることができます。このオプションは、キーが置き換える変数、値が対応する値となるオブジェクトを受け取ります。
すべての環境 (サーバー、エッジ、クライアント) の変数定義には、next.config.js の compiler.define フィールドを使用します。または、サーバーサイド (サーバーおよびエッジ) コードのみの変数定義には compiler.defineServer を使用します。
module.exports = {
compiler: {
define: {
MY_VARIABLE: 'my-string',
'process.env.MY_ENV_VAR': 'my-env-var',
},
defineServer: {
MY_SERVER_VARIABLE: 'my-server-var',
},
},
}ビルドライフサイクルイベント
Next.js コンパイラは、ビルドプロセスの特定のポイントでカスタムコードを実行できるライフサイクルイベントをサポートしています。現在、以下のイベントがサポートされています。
runAfterProductionCompile
本番ビルドのコンパイルが完了した後、型チェックや静的ページ生成などのコンパイル後タスクを実行する前に実行されるフック関数です。このフックは、プロジェクトディレクトリやビルド出力ディレクトリを含むプロジェクトメタデータへのアクセスを提供するため、サードパーティツールがソースマップのようなビルド出力を収集するのに役立ちます。
module.exports = {
compiler: {
runAfterProductionCompile: async ({ distDir, projectDir }) => {
// Your custom code here
},
},
}フックは、次のプロパティを持つオブジェクトを受け取ります。
distDir: ビルド出力ディレクトリ (デフォルトは.next)projectDir: プロジェクトのルートディレクトリ
実験的機能
SWC Trace プロファイリング
Chromium の trace event format として SWC の内部変換トレースを生成できます。
module.exports = {
experimental: {
swcTraceProfiling: true,
},
}有効にすると、swc は .next/ に swc-trace-profile-${timestamp}.json という名前のトレースを生成します。Chromium のトレースビューア (chrome://tracing/, https://ui.perfetto.dev/)、または互換性のあるフレームグラフビューア (https://www.speedscope.app/) は、生成されたトレースをロードして視覚化できます。
SWC プラグイン (実験的)
wasm で記述された SWC の実験的なプラグインサポートを使用して、変換動作をカスタマイズするように swc の変換を設定できます。
module.exports = {
experimental: {
swcPlugins: [
[
'plugin',
{
...pluginOptions,
},
],
],
},
}swcPlugins は、プラグインの設定のためにタプルの配列を受け取ります。プラグインのタプルには、プラグインへのパスとプラグイン設定用のオブジェクトが含まれます。プラグインへのパスは、npm モジュールパッケージ名、または .wasm バイナリ自体への絶対パスにすることができます。
サポートされていない機能
アプリケーションに .babelrc ファイルがある場合、Next.js は自動的に Babel にフォールバックして個々のファイルを変換します。これにより、カスタム Babel プラグインを利用する既存のアプリケーションとの後方互換性が確保されます。
カスタム Babel セットアップを使用している場合は、設定を共有してください。できるだけ多くの一般的に使用される Babel 変換を移植し、将来的にはプラグインもサポートする予定です。
バージョン履歴
| バージョン | 変更履歴 |
|---|---|
v13.1.0 | モジュール変換 と インポートのモジュール化 が安定版になりました。 |
v13.0.0 | SWC Minifier がデフォルトで有効になりました。 |
v12.3.0 | SWC Minifier 安定版。 |
v12.2.0 | SWC プラグインの実験的サポートが追加されました。 |
v12.1.0 | Styled Components, Jest, Relay, Remove React Properties, Legacy Decorators, Remove Console, jsxImportSource のサポートが追加されました。 |
v12.0.0 | Next.js コンパイラが導入されました。 |
役に立ちましたか?