Skip to content

Commit f734aee

Browse files
authored
Merge branch 'master' into chore/update-advanced-features-custom-server
2 parents 2cbb7b7 + c72bdb7 commit f734aee

File tree

8 files changed

+394
-67
lines changed

8 files changed

+394
-67
lines changed

docs/advanced-features/compiler.md

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
---
2+
description: Learn about the Next.js Compiler, written in Rust, which transforms and minifies your Next.js application.
3+
---
4+
5+
# Next.js Compiler
6+
7+
<details open>
8+
<summary><b>Version History</b></summary>
9+
10+
| Version | Changes |
11+
| --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
12+
| `v12.1.0` | Added support for Styled Components, Jest, Relay, Remove React Properties, Legacy Decorators, Remove Console, and jsxImportSource. |
13+
| `v12.0.0` | Next.js Compiler [introduced](https://nextjs.org/blog/next-12). |
14+
15+
</details>
16+
17+
The Next.js Compiler, written in Rust using [SWC](http://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.
18+
19+
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.
20+
21+
<!-- textlint-disable -->
22+
## Why SWC?
23+
24+
[SWC](http://swc.rs/) is an extensible Rust-based platform for the next generation of fast developer tools.
25+
26+
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.
27+
28+
We chose to build on SWC for a few reasons:
29+
30+
- **Extensibility:** SWC can be used as a Crate inside Next.js, without having to fork the library or workaround design constraints.
31+
- **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.
32+
- **WebAssembly:** Rust's support for WASM is essential for supporting all possible platforms and taking Next.js development everywhere.
33+
- **Community:** The Rust community and ecosystem are amazing and still growing.
34+
35+
## Supported Features
36+
37+
### Styled Components
38+
39+
We're working to port `babel-plugin-styled-components` to the Next.js Compiler.
40+
41+
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `next.config.js` file:
42+
43+
```js
44+
// next.config.js
45+
46+
module.exports = {
47+
compiler: {
48+
// ssr and displayName are configured by default
49+
styledComponents: true,
50+
},
51+
}
52+
```
53+
54+
Currently, only the `ssr` and `displayName` transforms have been implemented. These two transforms are the main requirement for using `styled-components` in Next.js.
55+
56+
### Jest
57+
58+
Jest support not only includes the transformation previously provided by Babel, but also simplifies configuring Jest together with Next.js including:
59+
60+
- Auto mocking of `.css`, `.module.css` (and their `.scss` variants), and image imports
61+
- Automatically sets up `transform` using SWC
62+
- Loading `.env` (and all variants) into `process.env`
63+
- Ignores `node_modules` from test resolving and transforms
64+
- Ignoring `.next` from test resolving
65+
- Loads `next.config.js` for flags that enable experimental SWC transforms
66+
67+
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jest.config.js` file:
68+
69+
```js
70+
// jest.config.js
71+
const nextJest = require('next/jest')
72+
73+
// Providing the path to your Next.js app which will enable loading next.config.js and .env files
74+
const createJestConfig = nextJest({ dir })
75+
76+
// Any custom config you want to pass to Jest
77+
const customJestConfig = {
78+
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
79+
}
80+
81+
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
82+
module.exports = createJestConfig(customJestConfig)
83+
```
84+
85+
### Relay
86+
87+
To enable [Relay](https://relay.dev/) support:
88+
89+
```js
90+
// next.config.js
91+
module.exports = {
92+
compiler: {
93+
relay: {
94+
// This should match relay.config.js
95+
src: './',
96+
artifactDirectory: './__generated__',
97+
language: 'typescript',
98+
},
99+
},
100+
}
101+
```
102+
103+
<!-- textlint-disable -->
104+
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.
105+
106+
### Remove React Properties
107+
108+
Allows to remove JSX properties. This is often used for testing. Similar to `babel-plugin-react-remove-properties`.
109+
110+
To remove properties matching the default regex `^data-test`:
111+
112+
```js
113+
// next.config.js
114+
module.exports = {
115+
compiler: {
116+
reactRemoveProperties: true,
117+
},
118+
}
119+
```
120+
121+
To remove custom properties:
122+
123+
```js
124+
// next.config.js
125+
module.exports = {
126+
compiler: {
127+
// The regexes defined here are processed in Rust so the syntax is different from
128+
// JavaScript `RegExp`s. See https://docs.rs/regex.
129+
reactRemoveProperties: { properties: ['^data-custom$'] },
130+
},
131+
}
132+
```
133+
134+
### Remove Console
135+
136+
This transform allows for removing all `console.*` calls in application code (not `node_modules`). Similar to `babel-plugin-transform-remove-console`.
137+
138+
Remove all `console.*` calls:
139+
140+
```js
141+
// next.config.js
142+
module.exports = {
143+
compiler: {
144+
removeConsole: true,
145+
},
146+
}
147+
```
148+
149+
Remove `console.*` output except `console.error`:
150+
151+
```js
152+
// next.config.js
153+
module.exports = {
154+
compiler: {
155+
removeConsole: {
156+
exclude: ['error'],
157+
},
158+
},
159+
}
160+
```
161+
162+
### Legacy Decorators
163+
164+
Next.js will automatically detect `experimentalDecorators` in `jsconfig.json` or `tsconfig.json`. Legacy decorators are commonly used with older versions of libraries like `mobx`.
165+
166+
This flag is only supported for compatibility with existing applications. We do not recommend using legacy decorators in new applications.
167+
168+
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jsconfig.json` or `tsconfig.json` file:
169+
170+
```js
171+
{
172+
"compilerOptions": {
173+
"experimentalDecorators": true
174+
}
175+
}
176+
```
177+
178+
### importSource
179+
180+
Next.js will automatically detect `jsxImportSource` in `jsconfig.json` or `tsconfig.json` and apply that. This is commonly used with libraries like Theme UI.
181+
182+
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `jsconfig.json` or `tsconfig.json` file:
183+
184+
```js
185+
{
186+
"compilerOptions": {
187+
"jsxImportSource": 'preact'
188+
}
189+
}
190+
```
191+
192+
## Experimental Features
193+
194+
### Minification
195+
196+
You can opt-in to using the Next.js compiler for minification. This is 7x faster than Terser.
197+
198+
```js
199+
// next.config.js
200+
201+
module.exports = {
202+
swcMinify: true,
203+
}
204+
```
205+
206+
If you have feedback about `swcMinify`, please share it on the [feedback discussion](https://github.com/vercel/next.js/discussions/30237).
207+
208+
## Unsupported Features
209+
210+
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.
211+
212+
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.

docs/advanced-features/custom-app.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,16 @@ function MyApp({ Component, pageProps }) {
3434
export default MyApp;
3535
```
3636

37-
- `Component` prop はアクティブな `page` です。なので、ルート間で遷移するたびに `Component` は新しい `page` に変化します。そのため、`Component`に渡した prop はすべてその `page` で受け取ることができます。
37+
`Component` prop はアクティブな `page` です。なので、ルート間で遷移するたびに `Component` は新しい `page` に変化します。そのため、`Component`に渡した prop はすべてその `page` で受け取ることができます。
3838

39-
- `pageProps`[データ取得メソッド](/docs/basic-features/data-fetching.md)の 1 つによってプリロードされた初期 props を持つオブジェクトです。そうでなければ空のオブジェクトになります。
39+
`pageProps`[データ取得メソッド](/docs/basic-features/data-fetching/overview.md)の 1 つによってプリロードされた初期 props を持つオブジェクトです。そうでなければ空のオブジェクトになります。
4040

4141
### 注意事項
4242

4343
- もしアプリが起動していて、独自の `App` を追加しただけの場合は、開発サーバーを再起動する必要があります。もし、`pages/_app.js`が存在しなかったときのみ必要です。
44-
- あなたの `App` で独自の getInitialProps を追加した場合、[Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation)を行わないページで[Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md)が無効になります。
44+
- あなたの `App` で独自の [getInitialProps](/docs/api-reference/data-fetching/get-initial-props.md) を追加した場合、[Static Generation](/docs/basic-features/data-fetching/get-static-props.md)を行わないページで[Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md)が無効になります。
45+
- カスタム `App``getInitialProps` を追加する場合、`import App from "next/app"` を行い `getInitialProps` の中で `App.getInitialProps(appContext)` を実行して返されたオブジェクトを `getInitialProps` が返すオブジェクトへとマージする必要があります。
46+
- `App` コンポーネントは現在 [getStaticProps](/docs/basic-features/data-fetching/get-static-props.md)[getServerSideProps](y/docs/basic-features/data-fetching/get-server-side-props.md) といった [Next.js のデータ取得メソッド](/docs/basic-features/data-fetching/overview.md) をサポートしていません。
4547

4648
### TypeScript
4749

docs/advanced-features/custom-document.md

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ description: Next.jsによって追加された、デフォルトのドキュメ
44

55
# カスタム `Document`
66

7-
カスタム `Document` は通常、アプリケーションの `<html>` タグと `<body>` タグを拡張するために使用されます。これはドキュメントのマークアップ定義を Next.js pages が省略するために必要です。
8-
9-
カスタム `Document` には、非同期サーバーレンダリングのデータ要求を表現するための `getInitialProps` を含めることもできます。
7+
カスタム `Document` は通常、アプリケーションの [ページ](/docs/basic-features/pages.md) がレンダリングされる `<html>` タグと `<body>` タグを拡張するために使用されます。このファイルはサーバーでのみレンダリングされます。そのため `onClick` と言ったイベントハンドラーは `document` で利用できません。
108

119
デフォルトの `Document` をオーバーライドするには `./pages/_document.js` ファイルを作成し、次のように `Document` クラスを拡張します:
1210

@@ -35,31 +33,33 @@ class MyDocument extends Document {
3533
export default MyDocument;
3634
```
3735

38-
ページを適切にレンダリングするには `<Html>`, `<Head />`, `<Main />``<NextScript />` が必要です。
39-
40-
カスタム属性は `lang` のように props として許可されます:
36+
上記のコードは Next.js により追加されるデフォルトの `Document` です。カスタム属性は props として許可されています。例えば `lang="en"``<html>` タグへと追加したいときには以下のようにします:
4137

4238
```jsx
4339
<Html lang="en">
4440
```
4541

46-
`ctx` オブジェクトは [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md#context-object) で受け取るものと同等ですが、1 つ追加されています。
42+
もしくは `className``body` タグへと追加したいときには以下のようにします:
43+
44+
```jsx
45+
<body className="bg-white">
46+
```
4747

48-
- `renderPage`: `Function` - 実際の React レンダリングロジックを(同期的に)実行するコールバックです。 Aphrodite の [`renderStatic`](https://github.com/Khan/aphrodite#server-side-rendering) のようなサーバーレンダリングラッパーをサポートするために、この関数装飾が役立ちます
48+
ページを適切にレンダリングするには `<Html>`, `<Head />`, `<Main />``<NextScript />` が必要です。
4949

5050
## 注意事項
5151

52-
- `Document` はサーバーでのみレンダリングされ、`onClick` などのイベントハンドラーは機能しません
53-
- `<Main />` の外にある React コンポーネントはブラウザによって初期化されません。ここにアプリケーションロジックを追加 _しないで_ ください。すべてのページで共有コンポーネント(メニューやツールバーなど)が必要な場合は、代わりに [`App`](/docs/advanced-features/custom-app.md) コンポーネントをご覧ください
54-
- `Document``getInitialProps` 関数は、クライアント側の遷移中には呼び出されず、ページが[静的に最適化されている場合](/docs/advanced-features/automatic-static-optimization.md)にも呼び出されません
55-
- `getInitialProps``ctx.req` / `ctx.res` が定義されていないかを確認してください。これらの変数は、ページが [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) または [`next export`](/docs/advanced-features/static-html-export.md) によって静的にエクスポートされるとき `undefined` となります
56-
- よくある過ちは `<Head />` タグに `<title>` を追加することや、`styled-jsx` を使用することです。これらは予期しない動作につながるため `pages / _document.js` での利用は避けてください。
52+
- `_document` で使用されている `<Head />` コンポーネントは、[next/head](/docs/api-reference/next/head.md) とは異なります。ここで使われている `<Head />` コンポーネントは、すべてのページに共通する `<head>` のコードにのみ使われるべきものです。それ以外の場合、例えば `<title>` タグなどには、ページやコンポーネントで [next/head](/docs/api-reference/next/head.md) を使用することをお勧めします。
53+
- `<Main />` の外にある React コンポーネントはブラウザによって初期化されません。ここにアプリケーションロジックやカスタムの CSS (styled-jsx など) を追加 _しないで_ ください。すべてのページで共有コンポーネント(メニューやツールバーなど)が必要な場合は、代わりに [`Layout`](/docs/basic-features/layouts.md) コンポーネントをご覧ください
54+
- `Document` コンポーネントは現在 [getStaticProps](/docs/basic-features/data-fetching/get-static-props.md)[getServerSideProps](y/docs/basic-features/data-fetching/get-server-side-props.md) といった [Next.js のデータ取得メソッド](/docs/basic-features/data-fetching/overview.md) をサポートしていません。
5755

5856
## `renderPage` のカスタマイズ
5957

6058
> `renderPage` をカスタマイズする必要があるのは、**css-in-js** ライブラリなどで、サーバーサイドレンダリングを適切に処理するために、アプリケーションをラップする時だけです。
6159
62-
カスタマイズするために、オプションオブジェクトを引数として受け取ります:
60+
[React 18](/docs/advanced-features/react-18.md) 対応のために、できる限り `getInitialProps``renderPage` のカスタマイズは避けることをお勧めします。
61+
62+
`ctx` オブジェクトは [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md#context-object) で受け取るものと同等ですが、`renderPage` を追加で受け取ります。
6363

6464
```jsx
6565
import Document from 'next/document';
@@ -68,6 +68,7 @@ class MyDocument extends Document {
6868
static async getInitialProps(ctx) {
6969
const originalRenderPage = ctx.renderPage;
7070

71+
// React のレンダリングロジックを同期的に動かす
7172
ctx.renderPage = () =>
7273
originalRenderPage({
7374
// react ツリー全体をラップするのに役立ちます
@@ -85,3 +86,23 @@ class MyDocument extends Document {
8586

8687
export default MyDocument;
8788
```
89+
90+
> **注意**: `_document` の中の `getInitialProps` はクライエントサイドでのページ遷移時には発火されません。
91+
92+
## TypeScript
93+
94+
組み込みの `DocumentContext` 型を使用して、ファイル名を `./pages/_document.tsx` のように変更できます:
95+
96+
```tsx
97+
import Document, { DocumentContext } from 'next/document'
98+
99+
class MyDocument extends Document {
100+
static async getInitialProps(ctx: DocumentContext) {
101+
const initialProps = await Document.getInitialProps(ctx)
102+
103+
return initialProps
104+
}
105+
}
106+
107+
export default MyDocument
108+
```

0 commit comments

Comments
 (0)