Unverified Commit fa8d5581 authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

Docs: Split Getting Started between App and Pages, improve `Installation` page (#72178)

Prepare **Getting Started** Section for upcoming changes, and work on
the first page: `Installation`.

Closes: 
-
https://linear.app/vercel/issue/DOC-3703/update-how-getting-started-is-handled-in-next-site
-
https://linear.app/vercel/issue/DOC-3694/page-how-to-set-up-a-new-nextjs-project-installation
- https://linear.app/vercel/issue/DOC-3707/create-subsection-for-plugins
- https://linear.app/vercel/issue/DOC-3709/eslint-plugin-api-reference
- https://linear.app/vercel/issue/DOC-3710/typescript-reference-page

### Key Changes: 

- Duplicate Getting Started Section between App and Pages Router docs 
- Since getting started will vary between the routers, each docs needs
to have their own Getting Started section
- Reorganize folder numbers
   
**Installation Page**: 
- Split app and pages router specific information
- Rename "Installation" to "How to set up a Next.js application" for SEO
- Add setup instructions for **TypeScript**
- Add setup instructions for **ESLint**
- Add setup instructions for **Absolute Imports and Module Path
Aliases**

**Side effects from moving content around**:
- Create a subsection in API Reference called **Configuration**. 
   - Add ESLint Plugin page, and update it to follow template
   - Add TypeScript page, and update it to follow template
- Remove the **Absolute Imports and Module Path Aliases** page, it's
small enough to live under the set up instructions.

---------
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
parent 8f99ab20
---
title: Installation
description: Create a new Next.js application with `create-next-app`. Set up TypeScript, styles, and configure your `next.config.js` file.
related:
title: Next Steps
description: Learn about the files and folders in your Next.js project.
links:
- getting-started/project-structure
title: How to set up a Next.js project
nav_title: Installation
description: Learn how to create a new Next.js application with `create-next-app`, and set up TypeScript, ESLint, and Module Path Aliases.
---
System Requirements:
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
## System requirements
- [Node.js 18.18](https://nodejs.org/) or later.
- macOS, Windows (including WSL), and Linux are supported.
## Automatic Installation
## Automatic installation
We recommend starting a new Next.js app using [`create-next-app`](/docs/app/api-reference/cli/create-next-app), which sets up everything automatically for you. To create a project, run:
......@@ -37,14 +35,7 @@ What import alias would you like configured? @/*
After the prompts, [`create-next-app`](/docs/app/api-reference/cli/create-next-app) will create a folder with your project name and install the required dependencies.
If you're new to Next.js, see the [project structure](/docs/getting-started/project-structure) docs for an overview of all the possible files and folders in your application.
> **Good to know**:
>
> - Next.js now ships with [TypeScript](/docs/app/building-your-application/configuring/typescript), [ESLint](/docs/app/building-your-application/configuring/eslint), and [Tailwind CSS](/docs/app/building-your-application/styling/tailwind-css) configuration by default.
> - You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files.
## Manual Installation
## Manual installation
To manually create a new Next.js app, install the required packages:
......@@ -72,15 +63,13 @@ These scripts refer to the different stages of developing an application:
- `start`: runs [`next start`](/docs/app/api-reference/cli/next#next-start-options) to start a Next.js production server.
- `lint`: runs [`next lint`](/docs/app/api-reference/cli/next#next-lint-options) to set up Next.js' built-in ESLint configuration.
### Creating directories
<AppOnly>
Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files.
#### The `app` directory
### Create the `app` directory
For new applications, we recommend using the [App Router](/docs/app). This router allows you to use React's latest features and is an evolution of the [Pages Router](/docs/pages) based on community feedback.
Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files.
Create an `app/` folder, then add a `layout.tsx` and `page.tsx` file. These will be rendered when the user visits the root of your application (`/`).
Create an `app` folder, then add a `layout.tsx` and `page.tsx` file. These will be rendered when the user visits the root of your application (`/`).
<Image
alt="App Folder Structure"
......@@ -130,15 +119,20 @@ export default function Page() {
}
```
> **Good to know**: If you forget to create `layout.tsx`, Next.js will automatically create this file when running the development server with `next dev`.
> **Good to know**:
>
> - If you forget to create `layout.tsx`, Next.js will automatically create this file when running the development server with `next dev`.
> - You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files.
</AppOnly>
Learn more about [using the App Router](/docs/app/building-your-application/routing/defining-routes).
<PagesOnly>
#### The `pages` directory (optional)
### Create the `pages` directory
If you prefer to use the Pages Router instead of the App Router, you can create a `pages/` directory at the root of your project.
Next.js uses file-system routing, which means the routes in your application are determined by how you structure your files.
Then, add an `index.tsx` file inside your `pages` folder. This will be your home page (`/`):
Create a `pages` directory at the root of your project. Then, add an `index.tsx` file inside your `pages` folder. This will be your home page (`/`):
```tsx filename="pages/index.tsx" switcher
export default function Page() {
......@@ -202,16 +196,156 @@ export default function Document() {
}
```
Learn more about [using the Pages Router](/docs/pages/building-your-application/routing/pages-and-layouts).
</PagesOnly>
> **Good to know**: Although you can use both routers in the same project, routes in `app` will be prioritized over `pages`. We recommend using only one router in your new project to avoid confusion.
### Create the `public` folder (optional)
#### The `public` folder (optional)
You can optionally create a [`public` folder](/docs/app/building-your-application/optimizing/static-assets) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`).
Create a `public` folder to store static assets such as images, fonts, etc. Files inside `public` directory can then be referenced by your code starting from the base URL (`/`).
## Run the Development Server
## Run the development server
1. Run `npm run dev` to start the development server.
2. Visit `http://localhost:3000` to view your application.
3. Edit `app/page.tsx` (or `pages/index.tsx`) file and save it to see the updated result in your browser.
3. Edit the<AppOnly>`app/page.tsx`</AppOnly> <PagesOnly>`pages/index.tsx`</PagesOnly> file and save it to see the updated result in your browser.
## Set up TypeScript
> Minimum TypeScript version: `v4.5.2`
Next.js comes with built-in TypeScript support. To add TypeScript to your project, rename a file to `.ts` / `.tsx`. Run `next dev`, Next.js will automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options.
> **Good to know**:
>
> - If you already have a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file.
<AppOnly>
### IDE Plugin
Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion.
You can enable the plugin in VS Code by:
1. Opening the command palette (`Ctrl/⌘` + `Shift` + `P`)
2. Searching for "TypeScript: Select TypeScript Version"
3. Selecting "Use Workspace Version"
<Image
alt="TypeScript Command Palette"
srcLight="/docs/light/typescript-command-palette.png"
srcDark="/docs/dark/typescript-command-palette.png"
width="1600"
height="637"
/>
Now, when editing files, the custom plugin will be enabled. When running `next build`, the custom type checker will be used.
</AppOnly>
See the [TypeScript configuration](/docs/app/api-reference/next-config-js/typescript) page for more information on how to use TypeScript in your project.
## Set up ESLint
Next.js comes with built-in ESLint, automatically installing the necessary packages and configuring the proper settings when you create a new project with `create-next-app`.
To add ESLint to an existing project, add `next lint` as a script to `package.json`:
```json filename="package.json"
{
"scripts": {
"lint": "next lint"
}
}
```
Then, run `npm run lint` and you will be guided through the installation and configuration process.
```bash filename="Terminal"
pnpm lint
```
You'll see a prompt like this:
> ? How would you like to configure ESLint?
>
> ❯ Strict (recommended)
> Base
> Cancel
- **Strict**: Includes Next.js' base ESLint configuration along with a stricter Core Web Vitals rule-set. This is the recommended configuration for developers setting up ESLint for the first time.
- **Base**: Includes Next.js' base ESLint configuration.
- **Cancel**: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration.
If either of the two configuration options are selected, Next.js will automatically install `eslint` and `eslint-config-next` as dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration.
You can now run `next lint` every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (`next build`). Errors will fail the build, while warnings will not.
See the [ESLint Plugin](/docs/app/api-reference/next-config-js/eslint) page for more information on how to configure ESLint in your project.
## Set up Absolute Imports and Module Path Aliases
Next.js has in-built support for the `"paths"` and `"baseUrl"` options of `tsconfig.json` and `jsconfig.json` files. These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:
```jsx
// Before
import { Button } from '../../../components/button'
// After
import { Button } from '@/components/button'
```
To configure absolute imports, add the `baseUrl` configuration option to your `tsconfig.json` or `jsconfig.json` file. For example:
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": "src/"
}
}
```
In addition to configuring the `baseUrl` path, you can use the `"paths"` option to `"alias"` module paths.
For example, the following configuration maps `@/components/*` to `components/*`:
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": "src/",
"paths": {
"@/styles/*": ["styles/*"],
"@/components/*": ["components/*"]
}
}
}
```
Each of the `"paths"` are relative to the `baseUrl` location. For example:
```tsx filename="src/app/page.tsx" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}
```
```jsx filename="src/app/page.js" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
export default function HomePage() {
return (
<div>
<h1>Hello World</h1>
<Button />
</div>
)
}
```
......@@ -35,14 +35,14 @@ Top-level files are used to configure your application, manage dependencies, run
| ------------------------------------------------------------------------------------------- | --------------------------------------- |
| **Next.js** | |
| [`next.config.js`](/docs/app/api-reference/next-config-js) | Configuration file for Next.js |
| [`package.json`](/docs/getting-started/installation#manual-installation) | Project dependencies and scripts |
| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts |
| [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) | OpenTelemetry and Instrumentation file |
| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware |
| [`.env`](/docs/app/building-your-application/configuring/environment-variables) | Environment variables |
| [`.env.local`](/docs/app/building-your-application/configuring/environment-variables) | Local environment variables |
| [`.env.production`](/docs/app/building-your-application/configuring/environment-variables) | Production environment variables |
| [`.env.development`](/docs/app/building-your-application/configuring/environment-variables) | Development environment variables |
| [`.eslintrc.json`](/docs/app/building-your-application/configuring/eslint) | Configuration file for ESLint |
| [`.eslintrc.json`](/docs/app/api-reference/config/eslint) | Configuration file for ESLint |
| `.gitignore` | Git files and folders to ignore |
| `next-env.d.ts` | TypeScript declaration file for Next.js |
| `tsconfig.json` | Configuration file for TypeScript |
......
......@@ -4,7 +4,7 @@ description: Learn how navigation works in Next.js, and how to use the Link Comp
related:
links:
- app/building-your-application/caching
- app/building-your-application/configuring/typescript
- app/api-reference/config/typescript
---
There are four ways to navigate between routes in Next.js:
......
......@@ -7,10 +7,9 @@ related:
- app/building-your-application/routing/defining-routes
- app/building-your-application/routing/route-groups
- app/building-your-application/configuring/src-directory
- app/building-your-application/configuring/absolute-imports-and-module-aliases
---
Apart from [routing folder and file conventions](/docs/getting-started/project-structure#app-routing-conventions), Next.js is **unopinionated** about how you organize and colocate your project files.
Apart from [folder and file conventions](/docs/app/getting-started/project-structure), Next.js is **unopinionated** about how you organize and colocate your project files.
This page shares default behavior and features you can use to organize your project.
......@@ -88,7 +87,7 @@ Since files in the `app` directory can be [safely colocated by default](#safe-co
>
> - While not a framework convention, you might also consider marking files outside private folders as "private" using the same underscore pattern.
> - You can create URL segments that start with an underscore by prefixing the folder name with `%5F` (the URL-encoded form of an underscore): `%5FfolderName`.
> - If you don't use private folders, it would be helpful to know Next.js [special file conventions](/docs/getting-started/project-structure#routing-files) to prevent unexpected naming conflicts.
> - If you don't use private folders, it would be helpful to know Next.js [special file conventions](/docs/app/getting-started/project-structure#routing-files) to prevent unexpected naming conflicts.
### Route Groups
......@@ -125,7 +124,7 @@ Next.js supports storing application code (including `app`) inside an optional [
### Module Path Aliases
Next.js supports [Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) which make it easier to read and maintain imports across deeply nested project files.
Next.js supports [Module Path Aliases](/docs/app/getting-started/installation#set-up-absolute-imports-and-module-path-aliases) which make it easier to read and maintain imports across deeply nested project files.
```jsx filename="app/dashboard/settings/analytics/page.js"
// before
......
......@@ -137,4 +137,4 @@ export default async function Page({ params }) {
| `app/shop/[[...slug]]/page.js` | `{ slug?: string[] }` |
| `app/[categoryId]/[itemId]/page.js` | `{ categoryId: string, itemId: string }` |
> **Good to know**: This may be done automatically by the [TypeScript plugin](/docs/app/building-your-application/configuring/typescript#typescript-plugin) in the future.
> **Good to know**: This may be done automatically by the [TypeScript plugin](/docs/app/api-reference/config/typescript#ide-plugin) in the future.
......@@ -117,7 +117,7 @@ const nextConfig = {
export default nextConfig
```
- [Ignoring TypeScript Errors](/docs/pages/building-your-application/configuring/typescript#ignoring-typescript-errors)
- [Ignoring TypeScript Errors](/docs/app/api-reference/config/typescript#disabling-typescript-errors-in-production)
- [ESLint in Next.js config](/docs/pages/api-reference/next-config-js/eslint)
Keep in mind that this may produce faulty deploys due to type errors or linting issues.
......
......@@ -200,7 +200,7 @@ module.exports = new Proxy(
## Optional: Handling Absolute Imports and Module Path Aliases
If your project is using [Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases), you will need to configure Jest to resolve the imports by matching the paths option in the `jsconfig.json` file with the `moduleNameMapper` option in the `jest.config.js` file. For example:
If your project is using [Module Path Aliases](/docs/app/getting-started/installation#set-up-absolute-imports-and-module-path-aliases), you will need to configure Jest to resolve the imports by matching the paths option in the `jsconfig.json` file with the `moduleNameMapper` option in the `jest.config.js` file. For example:
```json filename="tsconfig.json or jsconfig.json"
{
......
......@@ -121,7 +121,7 @@ While building your application, we recommend using the following features to en
### Type safety
- **TypeScript and [TS Plugin](/docs/app/building-your-application/configuring/typescript):** Use TypeScript and the TypeScript plugin for better type-safety, and to help you catch errors early.
- **TypeScript and [TS Plugin](/docs/app/api-reference/config/typescript):** Use TypeScript and the TypeScript plugin for better type-safety, and to help you catch errors early.
## Before going to production
......
......@@ -493,6 +493,6 @@ If everything went according to plan, you now have a functioning Next.js applica
- [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images)
- [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts)
- [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts)
- [Update your ESLint configuration to support Next.js rules](/docs/app/building-your-application/configuring/eslint)
- [Update your ESLint configuration to support Next.js rules](/docs/app/api-reference/config/eslint)
> **Good to know:** Using a static export [does not currently support](https://github.com/vercel/next.js/issues/54393) using the `useParams` hook.
......@@ -123,7 +123,7 @@ Here's an example of a working `tsconfig.json` with those changes:
```
You can find more information about configuring TypeScript on the
[Next.js docs](/docs/app/building-your-application/configuring/typescript#typescript-plugin).
[Next.js docs](/docs/app/api-reference/config/typescript#ide-plugin).
### Step 4: Create the Root Layout
......@@ -605,4 +605,4 @@ do next:
- [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images)
- [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts)
- [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts)
- [Update your ESLint configuration to support Next.js rules](/docs/app/building-your-application/configuring/eslint)
- [Update your ESLint configuration to support Next.js rules](/docs/app/api-reference/config/eslint)
......@@ -685,13 +685,13 @@ export default function Page({ posts }) {
<AppOnly>
If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/app/building-your-application/configuring/eslint#eslint-plugin), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.
If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/pages/api-reference/config/eslint), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.
</AppOnly>
<PagesOnly>
If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/pages/building-your-application/configuring/eslint#eslint-plugin), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.
If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/pages/api-reference/config/eslint), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.
</PagesOnly>
......
......@@ -69,4 +69,4 @@ export default function manifest() {
### Manifest Object
The manifest object contains an extensive list of options that may be updated due to new web standards. For information on all the current options, refer to the `MetadataRoute.Manifest` type in your code editor if using [TypeScript](https://nextjs.org/docs/app/building-your-application/configuring/typescript#typescript-plugin) or see the [MDN](https://developer.mozilla.org/docs/Web/Manifest) docs.
The manifest object contains an extensive list of options that may be updated due to new web standards. For information on all the current options, refer to the `MetadataRoute.Manifest` type in your code editor if using [TypeScript](https://nextjs.org/docs/app/api-reference/config/typescript#ide-plugin) or see the [MDN](https://developer.mozilla.org/docs/Web/Manifest) docs.
......@@ -1111,7 +1111,7 @@ ReactDOM.prefetchDNS(href: string)
## Types
You can add type safety to your metadata by using the `Metadata` type. If you are using the [built-in TypeScript plugin](/docs/app/building-your-application/configuring/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
You can add type safety to your metadata by using the `Metadata` type. If you are using the [built-in TypeScript plugin](/docs/app/api-reference/config/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
### `metadata` object
......
......@@ -175,7 +175,7 @@ export const viewport = {
## Types
You can add type safety to your viewport object by using the `Viewport` type. If you are using the [built-in TypeScript plugin](/docs/app/building-your-application/configuring/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
You can add type safety to your viewport object by using the `Viewport` type. If you are using the [built-in TypeScript plugin](/docs/app/api-reference/config/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
### `viewport` object
......
---
title: unstable_cache
description: API Reference for the unstable_cache function.
version: legacy
---
> This API will be deprecated in future versions. If you're using Next.js 15 canary, we recommend using [`connection`](/docs/app/api-reference/functions/connection) instead of `unstable_noStore`.
In version 15, we recommend using the [`use cache`](/docs/app/api-reference/directives/use-cache) directive instead.
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
......
---
title: unstable_noStore
description: API Reference for the unstable_noStore function.
version: legacy
---
> This API will be deprecated in future versions. If you're using Next.js 15 canary, we recommend using [`connection`](/docs/app/api-reference/functions/connection) instead of `unstable_noStore`.
In version 15, we recommend using [`connection`](/docs/app/api-reference/functions/connection) instead of `unstable_noStore`.
`unstable_noStore` can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.
......
......@@ -99,7 +99,7 @@ module.exports = (phase, { defaultConfig }) => {
## TypeScript
If you are using TypeScript in your project, you can use [`next.config.ts`](/docs/app/building-your-application/configuring/typescript#type-checking-nextconfigts) to use TypeScript in your configuration:
If you are using TypeScript in your project, you can use `next.config.ts` to use TypeScript in your configuration:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
......
......@@ -4,7 +4,7 @@ description: Enable experimental support for statically typed links.
version: experimental
---
Experimental support for [statically typed links](/docs/app/building-your-application/configuring/typescript#statically-typed-links). This feature requires using the App Router as well as TypeScript in your project.
Experimental support for [statically typed links](/docs/app/api-reference/config/typescript#statically-typed-links). This feature requires using the App Router as well as TypeScript in your project.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
......
......@@ -5,37 +5,15 @@ description: Next.js provides a TypeScript-first development experience for buil
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Next.js provides a TypeScript-first development experience for building your React application.
Next.js comes with built-in TypeScript, automatically installing the necessary packages and configuring the proper settings when you create a new project with `create-next-app`.
It comes with built-in TypeScript support for automatically installing the necessary packages and configuring the proper settings.
To add TypeScript to an existing project, rename a file to `.ts` / `.tsx`. Run `next dev` and `next build` to automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options.
<AppOnly>
As well as a [TypeScript Plugin](#typescript-plugin) for your editor.
> **🎥 Watch:** Learn about the built-in TypeScript plugin → [YouTube (3 minutes)](https://www.youtube.com/watch?v=pqMqn9fKEf8)
</AppOnly>
## New Projects
`create-next-app` now ships with TypeScript by default.
```bash filename="Terminal"
npx create-next-app@latest
```
## Existing Projects
Add TypeScript to your project by renaming a file to `.ts` / `.tsx`. Run `next dev` and `next build` to automatically install the necessary dependencies and add a `tsconfig.json` file with the recommended config options.
If you already had a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file.
We also recommend you to use [`next.config.ts`](#type-checking-nextconfigts) over `next.config.js` for better type inference.
> **Good to know**: If you already have a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file.
<AppOnly>
## TypeScript Plugin
## IDE Plugin
Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion.
......@@ -55,8 +33,6 @@ You can enable the plugin in VS Code by:
Now, when editing files, the custom plugin will be enabled. When running `next build`, the custom type checker will be used.
### Plugin Features
The TypeScript plugin can help with:
- Warning if the invalid values for [segment config options](/docs/app/api-reference/file-conventions/route-segment-config) are passed.
......@@ -64,32 +40,41 @@ The TypeScript plugin can help with:
- Ensuring the `use client` directive is used correctly.
- Ensuring client hooks (like `useState`) are only used in Client Components.
> **Good to know**: More features will be added in the future.
> **🎥 Watch:** Learn about the built-in TypeScript plugin → [YouTube (3 minutes)](https://www.youtube.com/watch?v=pqMqn9fKEf8)
</AppOnly>
## End-to-End Type Safety
## Minimum TypeScript Version
The Next.js App Router has **enhanced type safety**. This includes:
It is highly recommended to be on at least `v4.5.2` of TypeScript to get syntax features such as [type modifiers on import names](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#type-on-import-names) and [performance improvements](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#real-path-sync-native).
1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types.
2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching) in the App Router, this is no longer an issue.
## Type checking in Next.js Configuration
[Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.
### Type checking next.config.js
We're able to type the response data as you would expect with normal TypeScript. For example:
When using the `next.config.js` file, you can add some type checking in your IDE using JSDoc as below:
```tsx filename="app/page.tsx" switcher
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
return res.json()
}
```js filename="next.config.js"
// @ts-check
export default async function Page() {
const name = await getData()
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
return '...'
}
module.exports = nextConfig
```
### Type checking next.config.ts
For _complete_ end-to-end type safety, this also requires your database or content provider to support TypeScript. This could be through using an [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) or type-safe query builder.
</AppOnly>
## Examples
### Type checking `next.config.ts`
You can use TypeScript and import types in your Next.js configuration by using `next.config.ts`.
......@@ -103,11 +88,24 @@ const nextConfig: NextConfig = {
export default nextConfig
```
> **Note**: Module resolution in `next.config.ts` is currently limited to `CommonJS`. This may cause incompatibilities with ESM only packages being loaded in `next.config.ts`.
> **Good to know**: Module resolution in `next.config.ts` is currently limited to `CommonJS`. This may cause incompatibilities with ESM only packages being loaded in `next.config.ts`.
When using the `next.config.js` file, you can add some type checking in your IDE using JSDoc as below:
```js filename="next.config.js"
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
}
module.exports = nextConfig
```
<AppOnly>
## Statically Typed Links
### Statically Typed Links
Next.js can statically type links to prevent typos and other errors when using `next/link`, improving type safety when navigating between pages.
......@@ -162,46 +160,12 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) {
>
> When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links.
## End-to-End Type Safety
The Next.js App Router has **enhanced type safety**. This includes:
1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types.
2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching) in the App Router, this is no longer an issue.
[Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.
We're able to type the response data as you would expect with normal TypeScript. For example:
```tsx filename="app/page.tsx"
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
return res.json()
}
export default async function Page() {
const name = await getData()
return '...'
}
```
For _complete_ end-to-end type safety, this also requires your database or content provider to support TypeScript. This could be through using an [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) or type-safe query builder.
## Async Server Component TypeScript Error
## With Async Server Componens
To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
If you are using an older version of TypeScript, you may see a `'Promise<Element>' is not a valid JSX element` type error. Updating to the latest version of TypeScript and `@types/react` should resolve this issue.
## Passing Data Between Server & Client Components
When passing data between a Server and Client Component through props, the data is still serialized (converted to a string) for use in the browser. However, it does not need a special type. It’s typed the same as passing any other props between components.
Further, there is less code to be serialized, as un-rendered data does not cross between the server and client (it remains on the server). This is only now possible through support for Server Components.
</AppOnly>
<PagesOnly>
......@@ -228,11 +192,11 @@ export const getServerSideProps = (async (context) => {
> **Good to know:** `satisfies` was added to TypeScript in [4.9](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html). We recommend upgrading to the latest version of TypeScript.
## API Routes
## With API Routes
The following is an example of how to use the built-in types for API routes:
```ts
```ts filename="pages/api/hello.ts"
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
......@@ -242,7 +206,7 @@ export default function handler(req: NextApiRequest, res: NextApiResponse) {
You can also type the response data:
```ts
```ts filename="pages/api/hello.ts"
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
......@@ -257,7 +221,7 @@ export default function handler(
}
```
## Custom `App`
## With custom `App`
If you have a [custom `App`](/docs/pages/building-your-application/routing/custom-app), you can use the built-in type `AppProps` and change file name to `./pages/_app.tsx` like so:
......@@ -271,27 +235,11 @@ export default function MyApp({ Component, pageProps }: AppProps) {
</PagesOnly>
## Path aliases and baseUrl
Next.js automatically supports the `tsconfig.json` `"paths"` and `"baseUrl"` options.
<AppOnly>
You can learn more about this feature on the [Module Path aliases documentation](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases).
</AppOnly>
<PagesOnly>
You can learn more about this feature on the [Module Path aliases documentation](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases).
</PagesOnly>
## Incremental type checking
Since `v10.2.1` Next.js supports [incremental type checking](https://www.typescriptlang.org/tsconfig#incremental) when enabled in your `tsconfig.json`, this can help speed up type checking in larger applications.
## Ignoring TypeScript Errors
## Disabling TypeScript errors in production
Next.js fails your **production build** (`next build`) when TypeScript errors are present in your project.
......@@ -319,7 +267,7 @@ export default nextConfig
> **Good to know**: You can run `tsc --noEmit` to check for TypeScript errors yourself before building. This is useful for CI/CD pipelines where you'd like to check for TypeScript errors before deploying.
## Custom Type Declarations
## Custom type declarations
When you need to declare custom types, you might be tempted to modify `next-env.d.ts`. However, this file is automatically generated, so any changes you make will be overwritten. Instead, you should create a new file, let's call it `new-types.d.ts`, and reference it in your `tsconfig.json`:
......
---
title: ESLint
description: Next.js provides an integrated ESLint experience by default. These conformance rules help you use Next.js in an optimal way.
title: ESLint Plugin
nav_title: ESLint
description: Learn how to use and configure the ESLint plugin to catch common issues and problems in a Next.js application.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Next.js provides an integrated [ESLint](https://eslint.org/) experience out of the box. Add `next lint` as a script to `package.json`:
Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application.
```json filename="package.json"
{
"scripts": {
"lint": "next lint"
}
}
```
Then run `npm run lint` or `yarn lint`:
```bash filename="Terminal"
yarn lint
```
If you don't already have ESLint configured in your application, you will be guided through the installation and configuration process.
```bash filename="Terminal"
yarn lint
```
> You'll see a prompt like this:
>
> ? How would you like to configure ESLint?
>
> ❯ Strict (recommended)
> Base
> Cancel
One of the following three options can be selected:
- **Strict**: Includes Next.js' base ESLint configuration along with a stricter [Core Web Vitals rule-set](#core-web-vitals). This is the recommended configuration for developers setting up ESLint for the first time.
```json filename=".eslintrc.json"
{
"extends": "next/core-web-vitals"
}
```
- **Base**: Includes Next.js' base ESLint configuration.
```json filename=".eslintrc.json"
{
"extends": "next"
}
```
- **Cancel**: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration.
If either of the two configuration options are selected, Next.js will automatically install `eslint` and `eslint-config-next` as dependencies in your application and create an `.eslintrc.json` file in the root of your project that includes your selected configuration.
You can now run `next lint` every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (`next build`). Errors will fail the build, while warnings will not.
<AppOnly>
> If you do not want ESLint to run during `next build`, refer to the documentation for [Ignoring ESLint](/docs/app/api-reference/next-config-js/eslint).
</AppOnly>
<PagesOnly>
> If you do not want ESLint to run during `next build`, refer to the documentation for [Ignoring ESLint](/docs/pages/api-reference/next-config-js/eslint).
</PagesOnly>
We recommend using an appropriate [integration](https://eslint.org/docs/user-guide/integrations#editors) to view warnings and errors directly in your code editor during development.
## ESLint Config
The default configuration (`eslint-config-next`) includes everything you need to have an optimal out-of-the-box linting experience in Next.js. If you do not have ESLint already configured in your application, we recommend using `next lint` to set up ESLint along with this configuration.
> If you would like to use `eslint-config-next` along with other ESLint configurations, refer to the [Additional Configurations](#additional-configurations) section to learn how to do so without causing any conflicts.
## Reference
Recommended rule-sets from the following ESLint plugins are all used within `eslint-config-next`:
......@@ -87,58 +18,39 @@ Recommended rule-sets from the following ESLint plugins are all used within `esl
This will take precedence over the configuration from `next.config.js`.
## ESLint Plugin
Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application. The full set of rules is as follows:
<Check size={18} /> Enabled in the recommended configuration
| | Rule | Description |
| :-----------------: | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| <Check size={18} /> | [@next/next/google-font-display](/docs/messages/google-font-display) | Enforce font-display behavior with Google Fonts. |
| <Check size={18} /> | [@next/next/google-font-preconnect](/docs/messages/google-font-preconnect) | Ensure `preconnect` is used with Google Fonts. |
| <Check size={18} /> | [@next/next/inline-script-id](/docs/messages/inline-script-id) | Enforce `id` attribute on `next/script` components with inline content. |
| <Check size={18} /> | [@next/next/next-script-for-ga](/docs/messages/next-script-for-ga) | Prefer `next/script` component when using the inline script for Google Analytics. |
| <Check size={18} /> | [@next/next/no-assign-module-variable](/docs/messages/no-assign-module-variable) | Prevent assignment to the `module` variable. |
| <Check size={18} /> | [@next/next/no-async-client-component](/docs/messages/no-async-client-component) | Prevent client components from being async functions. |
| <Check size={18} /> | [@next/next/no-before-interactive-script-outside-document](/docs/messages/no-before-interactive-script-outside-document) | Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-css-tags](/docs/messages/no-css-tags) | Prevent manual stylesheet tags. |
| <Check size={18} /> | [@next/next/no-document-import-in-page](/docs/messages/no-document-import-in-page) | Prevent importing `next/document` outside of `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-duplicate-head](/docs/messages/no-duplicate-head) | Prevent duplicate usage of `<Head>` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-head-element](/docs/messages/no-head-element) | Prevent usage of `<head>` element. |
| <Check size={18} /> | [@next/next/no-head-import-in-document](/docs/messages/no-head-import-in-document) | Prevent usage of `next/head` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-html-link-for-pages](/docs/messages/no-html-link-for-pages) | Prevent usage of `<a>` elements to navigate to internal Next.js pages. |
| <Check size={18} /> | [@next/next/no-img-element](/docs/messages/no-img-element) | Prevent usage of `<img>` element due to slower LCP and higher bandwidth. |
| <Check size={18} /> | [@next/next/no-page-custom-font](/docs/messages/no-page-custom-font) | Prevent page-only custom fonts. |
| <Check size={18} /> | [@next/next/no-script-component-in-head](/docs/messages/no-script-component-in-head) | Prevent usage of `next/script` in `next/head` component. |
| <Check size={18} /> | [@next/next/no-styled-jsx-in-document](/docs/messages/no-styled-jsx-in-document) | Prevent usage of `styled-jsx` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-sync-scripts](/docs/messages/no-sync-scripts) | Prevent synchronous scripts. |
| <Check size={18} /> | [@next/next/no-title-in-document-head](/docs/messages/no-title-in-document-head) | Prevent usage of `<title>` with `Head` component from `next/document`. |
| <Check size={18} /> | @next/next/no-typos | Prevent common typos in [Next.js's data fetching functions](/docs/pages/building-your-application/data-fetching) |
| <Check size={18} /> | [@next/next/no-unwanted-polyfillio](/docs/messages/no-unwanted-polyfillio) | Prevent duplicate polyfills from Polyfill.io. |
If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met. Refer to the [Recommended Plugin Ruleset](#recommended-plugin-ruleset) to learn more.
### Custom Settings
#### `rootDir`
If you're using `eslint-plugin-next` in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell `eslint-plugin-next` where to find your Next.js application using the `settings` property in your `.eslintrc`:
### Rules
The full set of rules is as follows:
| Enabled in recommended config | Rule | Description |
| :---------------------------: | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| <Check size={18} /> | [@next/next/google-font-display](/docs/messages/google-font-display) | Enforce font-display behavior with Google Fonts. |
| <Check size={18} /> | [@next/next/google-font-preconnect](/docs/messages/google-font-preconnect) | Ensure `preconnect` is used with Google Fonts. |
| <Check size={18} /> | [@next/next/inline-script-id](/docs/messages/inline-script-id) | Enforce `id` attribute on `next/script` components with inline content. |
| <Check size={18} /> | [@next/next/next-script-for-ga](/docs/messages/next-script-for-ga) | Prefer `next/script` component when using the inline script for Google Analytics. |
| <Check size={18} /> | [@next/next/no-assign-module-variable](/docs/messages/no-assign-module-variable) | Prevent assignment to the `module` variable. |
| <Check size={18} /> | [@next/next/no-async-client-component](/docs/messages/no-async-client-component) | Prevent client components from being async functions. |
| <Check size={18} /> | [@next/next/no-before-interactive-script-outside-document](/docs/messages/no-before-interactive-script-outside-document) | Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-css-tags](/docs/messages/no-css-tags) | Prevent manual stylesheet tags. |
| <Check size={18} /> | [@next/next/no-document-import-in-page](/docs/messages/no-document-import-in-page) | Prevent importing `next/document` outside of `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-duplicate-head](/docs/messages/no-duplicate-head) | Prevent duplicate usage of `<Head>` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-head-element](/docs/messages/no-head-element) | Prevent usage of `<head>` element. |
| <Check size={18} /> | [@next/next/no-head-import-in-document](/docs/messages/no-head-import-in-document) | Prevent usage of `next/head` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-html-link-for-pages](/docs/messages/no-html-link-for-pages) | Prevent usage of `<a>` elements to navigate to internal Next.js pages. |
| <Check size={18} /> | [@next/next/no-img-element](/docs/messages/no-img-element) | Prevent usage of `<img>` element due to slower LCP and higher bandwidth. |
| <Check size={18} /> | [@next/next/no-page-custom-font](/docs/messages/no-page-custom-font) | Prevent page-only custom fonts. |
| <Check size={18} /> | [@next/next/no-script-component-in-head](/docs/messages/no-script-component-in-head) | Prevent usage of `next/script` in `next/head` component. |
| <Check size={18} /> | [@next/next/no-styled-jsx-in-document](/docs/messages/no-styled-jsx-in-document) | Prevent usage of `styled-jsx` in `pages/_document.js`. |
| <Check size={18} /> | [@next/next/no-sync-scripts](/docs/messages/no-sync-scripts) | Prevent synchronous scripts. |
| <Check size={18} /> | [@next/next/no-title-in-document-head](/docs/messages/no-title-in-document-head) | Prevent usage of `<title>` with `Head` component from `next/document`. |
| <Check size={18} /> | @next/next/no-typos | Prevent common typos in [Next.js's data fetching functions](/docs/pages/building-your-application/data-fetching) |
| <Check size={18} /> | [@next/next/no-unwanted-polyfillio](/docs/messages/no-unwanted-polyfillio) | Prevent duplicate polyfills from Polyfill.io. |
```json filename=".eslintrc.json"
{
"extends": "next",
"settings": {
"next": {
"rootDir": "packages/my-app/"
}
}
}
```
We recommend using an appropriate [integration](https://eslint.org/docs/user-guide/integrations#editors) to view warnings and errors directly in your code editor during development.
`rootDir` can be a path (relative or absolute), a glob (i.e. `"packages/*/"`), or an array of paths and/or globs.
## Examples
## Linting Custom Directories and Files
### Linting custom directories and files
By default, Next.js will run ESLint for all files in the `pages/`, `app/`, `components/`, `lib/`, and `src/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds:
......@@ -156,25 +68,32 @@ Similarly, the `--dir` and `--file` flags can be used for `next lint` to lint sp
next lint --dir pages --dir utils --file bar.js
```
## Caching
### Specifying a root directory within a monorepo
<AppOnly>
To improve performance, information of files processed by ESLint are cached by default. This is stored in `.next/cache` or in your defined [build directory](/docs/app/api-reference/next-config-js/distDir). If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the `--no-cache` flag with `next lint`.
If you're using `eslint-plugin-next` in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell `eslint-plugin-next` where to find your Next.js application using the `settings` property in your `.eslintrc`:
</AppOnly>
```json filename=".eslintrc.json"
{
"extends": "next",
"settings": {
"next": {
"rootDir": "packages/my-app/"
}
}
}
```
<PagesOnly>
`rootDir` can be a path (relative or absolute), a glob (i.e. `"packages/*/"`), or an array of paths and/or globs.
To improve performance, information of files processed by ESLint are cached by default. This is stored in `.next/cache` or in your defined [build directory](/docs/pages/api-reference/next-config-js/distDir). If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the `--no-cache` flag with `next lint`.
### Disabling the cache
</PagesOnly>
To improve performance, information of files processed by ESLint are cached by default. This is stored in `.next/cache` or in your defined [build directory](/docs/app/api-reference/next-config-js/distDir). If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the `--no-cache` flag with `next lint`.
```bash filename="Terminal"
next lint --no-cache
```
## Disabling Rules
### Disabling rules
If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`:
......@@ -188,7 +107,7 @@ If you would like to modify or disable any rules provided by the supported plugi
}
```
### Core Web Vitals
### With Core Web Vitals
The `next/core-web-vitals` rule set is enabled when `next lint` is run for the first time and the **strict** option is selected.
......@@ -202,7 +121,7 @@ The `next/core-web-vitals` rule set is enabled when `next lint` is run for the f
> The `next/core-web-vitals` entry point is automatically included for new applications built with [Create Next App](/docs/app/api-reference/cli/create-next-app).
### TypeScript
### With TypeScript
In addition to the Next.js ESLint rules, `create-next-app --typescript` will also add TypeScript-specific lint rules with `next/typescript` to your config:
......@@ -215,9 +134,7 @@ In addition to the Next.js ESLint rules, `create-next-app --typescript` will als
Those rules are based on [`plugin:@typescript-eslint/recommended`](https://typescript-eslint.io/linting/configs#recommended).
See [typescript-eslint > Configs](https://typescript-eslint.io/linting/configs) for more details.
## Usage With Other Tools
### Prettier
### With Prettier
ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together.
......@@ -241,7 +158,7 @@ Then, add `prettier` to your existing ESLint config:
}
```
### lint-staged
### Running lint on staged files
If you would like to use `next lint` with [lint-staged](https://github.com/okonet/lint-staged) to run the linter on staged git files, you'll have to add the following to the `.lintstagedrc.js` file in the root of your project in order to specify usage of the `--file` flag.
......@@ -258,11 +175,43 @@ module.exports = {
}
```
## Migrating Existing Config
## Disabling linting during production builds
If you do not want ESLint to run during `next build`, you can set the `eslint.ignoreDuringBuilds` option in `next.config.js` to `true`:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
const nextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}
export default nextConfig
```
### Migrating existing config
If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met.
### Recommended Plugin Ruleset
#### Recommended plugin ruleset
If you already have ESLint configured in your application and any of the following conditions are true:
If the following conditions are true:
- You have one or more of the following plugins already installed (either separately or through a different config such as `airbnb` or `react-app`):
- `react`
......@@ -297,7 +246,7 @@ bun add --dev @next/eslint-plugin-next
This eliminates the risk of collisions or errors that can occur due to importing the same plugin or parser across multiple configurations.
### Additional Configurations
#### Additional configurations
If you already use a separate ESLint configuration and want to include `eslint-config-next`, ensure that it is extended last after other configurations. For example:
......
---
title: Absolute Imports and Module Path Aliases
description: Configure module path aliases that allow you to remap certain import paths.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
<details>
<summary>Examples</summary>
- [Absolute Imports and Aliases](https://github.com/vercel/next.js/tree/canary/examples/with-absolute-imports)
</details>
Next.js has in-built support for the `"paths"` and `"baseUrl"` options of `tsconfig.json` and `jsconfig.json` files.
These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:
```tsx
// before
import { Button } from '../../../components/button'
// after
import { Button } from '@/components/button'
```
> **Good to know**: `create-next-app` will prompt to configure these options for you.
## Absolute Imports
The `baseUrl` configuration option allows you to import directly from the root of the project.
An example of this configuration:
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": "."
}
}
```
```tsx filename="components/button.tsx" switcher
export default function Button() {
return <button>Click me</button>
}
```
```jsx filename="components/button.js" switcher
export default function Button() {
return <button>Click me</button>
}
```
```tsx filename="app/page.tsx" switcher
import Button from 'components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
```
```jsx filename="app/page.js" switcher
import Button from 'components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
```
## Module Aliases
In addition to configuring the `baseUrl` path, you can use the `"paths"` option to "alias" module paths.
For example, the following configuration maps `@/components/*` to `components/*`:
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
```
```tsx filename="components/button.tsx" switcher
export default function Button() {
return <button>Click me</button>
}
```
```jsx filename="components/button.js" switcher
export default function Button() {
return <button>Click me</button>
}
```
```tsx filename="app/page.tsx" switcher
import Button from '@/components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
```
```jsx filename="app/page.js" switcher
import Button from '@/components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
```
Each of the `"paths"` are relative to the `baseUrl` location. For example:
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": "src/",
"paths": {
"@/styles/*": ["styles/*"],
"@/components/*": ["components/*"]
}
}
}
```
```tsx filename="app/page.tsx" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
import Helper from 'utils/helper'
export default function HomePage() {
return (
<Helper>
<h1>Hello World</h1>
<Button />
</Helper>
)
}
```
```jsx filename="app/page.js" switcher
import Button from '@/components/button'
import '@/styles/styles.css'
import Helper from 'utils/helper'
export default function HomePage() {
return (
<Helper>
<h1>Hello World</h1>
<Button />
</Helper>
)
}
```
---
title: Create a new Next.js application
nav_title: Installation
description: How to create a new Next.js application with `create-next-app`. Set up TypeScript, ESLint,and configure your `next.config.js` file.
source: app/getting-started/installation
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: Next.js Project Structure
nav_title: Project Structure
description: A list of folders and files conventions in a Next.js project
source: app/getting-started/project-structure
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: Getting Started
description: Learn how to create full-stack web applications with Next.js.
---
---
title: TypeScript
description: Next.js provides a TypeScript-first development experience for building your React application.
source: app/building-your-application/configuring/typescript
source: app/api-reference/config/typescript
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: ESLint
description: Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.
source: app/building-your-application/configuring/eslint
source: app/api-reference/config/eslint
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
......@@ -15,7 +15,7 @@ The Next.js route announcer looks for the page name to announce by first inspect
## Linting
Next.js provides an [integrated ESLint experience](/docs/pages/building-your-application/configuring/eslint) out of the box, including custom rules for Next.js. By default, Next.js includes `eslint-plugin-jsx-a11y` to help catch accessibility issues early, including warning on:
Next.js provides an [integrated ESLint experience](/docs/pages/api-reference/config/eslint) out of the box, including custom rules for Next.js. By default, Next.js includes `eslint-plugin-jsx-a11y` to help catch accessibility issues early, including warning on:
- [aria-props](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/aria-props.md?rgh-link-date=2021-06-04T02%3A10%3A36Z)
- [aria-proptypes](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/aria-proptypes.md?rgh-link-date=2021-06-04T02%3A10%3A36Z)
......
......@@ -59,7 +59,7 @@ Next.js allows you to use the latest JavaScript features out of the box. In addi
### TypeScript Features
Next.js has built-in TypeScript support. [Learn more here](/docs/pages/building-your-application/configuring/typescript).
Next.js has built-in TypeScript support. [Learn more here](/docs/pages/api-reference/config/typescript).
### Customizing Babel Config (Advanced)
......
---
title: Absolute Imports and Module Path Aliases
description: Configure module path aliases that allow you to remap certain import paths.
source: app/building-your-application/configuring/absolute-imports-and-module-aliases
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
......@@ -17,14 +17,14 @@ Whether you're an individual developer or part of a larger team, Next.js can hel
Some of the main Next.js features include:
| Feature | Description |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [Routing](/docs/app/building-your-application/routing) | A file-system based router built on top of Server Components that supports layouts, nested routing, loading states, error handling, and more. |
| [Rendering](/docs/app/building-your-application/rendering) | Client-side and Server-side Rendering with Client and Server Components. Further optimized with Static and Dynamic Rendering on the server with Next.js. Streaming on Edge and Node.js runtimes. |
| [Data Fetching](/docs/app/building-your-application/data-fetching) | Simplified data fetching with async/await in Server Components, and an extended `fetch` API for request memoization, data caching and revalidation. |
| [Styling](/docs/app/building-your-application/styling) | Support for your preferred styling methods, including CSS Modules, Tailwind CSS, and CSS-in-JS |
| [Optimizations](/docs/app/building-your-application/optimizing) | Image, Fonts, and Script Optimizations to improve your application's Core Web Vitals and User Experience. |
| [TypeScript](/docs/app/building-your-application/configuring/typescript) | Improved support for TypeScript, with better type checking and more efficient compilation, as well as custom TypeScript Plugin and type checker. |
| Feature | Description |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [Routing](/docs/app/building-your-application/routing) | A file-system based router built on top of Server Components that supports layouts, nested routing, loading states, error handling, and more. |
| [Rendering](/docs/app/building-your-application/rendering) | Client-side and Server-side Rendering with Client and Server Components. Further optimized with Static and Dynamic Rendering on the server with Next.js. Streaming on Edge and Node.js runtimes. |
| [Data Fetching](/docs/app/building-your-application/data-fetching) | Simplified data fetching with async/await in Server Components, and an extended `fetch` API for request memoization, data caching and revalidation. |
| [Styling](/docs/app/building-your-application/styling) | Support for your preferred styling methods, including CSS Modules, Tailwind CSS, and CSS-in-JS |
| [Optimizations](/docs/app/building-your-application/optimizing) | Image, Fonts, and Script Optimizations to improve your application's Core Web Vitals and User Experience. |
| [TypeScript](/docs/app/api-reference/config/typescript) | Improved support for TypeScript, with better type checking and more efficient compilation, as well as custom TypeScript Plugin and type checker. |
## How to Use These Docs
......@@ -32,7 +32,7 @@ On the left side of the screen, you'll find the docs navbar. The pages of the do
On the right side of the screen, you'll see a table of contents that makes it easier to navigate between sections of a page. If you need to quickly find a page, you can use the search bar at the top, or the search shortcut (`Ctrl+K` or `Cmd+K`).
To get started, check out the [Installation](/docs/getting-started/installation) guide.
To get started, check out the [Installation](/docs/app/getting-started/installation) guide.
## App Router vs Pages Router
......
......@@ -48,7 +48,7 @@ export default Home
This rule can normally locate your `pages` directory automatically.
If you're working in a monorepo, we recommend configuring the [`rootDir`](/docs/pages/building-your-application/configuring/eslint#rootdir) setting in `eslint-plugin-next`, which `pagesDir` will use to locate your `pages` directory.
If you're working in a monorepo, we recommend configuring the [`rootDir`](/docs/pages/api-reference/config/eslint #specifying-a-root-directory-within-a-monorepo) setting in `eslint-plugin-next`, which `pagesDir` will use to locate your `pages` directory.
In some cases, you may also need to configure this rule directly by providing a `pages` directory. This can be a path or an array of paths.
......
......@@ -55,10 +55,10 @@ function validate(docPath) {
}
const appRouterValid = validate(
`docs/02-app/02-api-reference/05-next-config-js/serverExternalPackages.mdx`
`docs/01-app/03-api-reference/05-next-config-js/serverExternalPackages.mdx`
)
const pagesRouterValid = validate(
`docs/03-pages/02-api-reference/04-next-config-js/serverExternalPackages.mdx`
`docs/02-pages/03-api-reference/04-next-config-js/serverExternalPackages.mdx`
)
if (appRouterValid && pagesRouterValid) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment