Next.js Cheatsheet
Traduzione:
__HTML_TAG_73_
Next.js - Il quadro di reazione per la produzione
Next.js è un framework React che ti dà la costruzione di blocchi per creare applicazioni web. Per struttura, intendiamo Next.js gestisce l'attrezzo e la configurazione necessaria per React, e fornisce ulteriori strutture, caratteristiche e ottimizzazioni per la vostra applicazione.
Traduzione:
__HTML_TAG_78_
__HTML_TAG_79_
📋 Copia tutti i comandi_HTML_TAG_81__
📄 Genera PDF_HTML_TAG_83__
__HTML_TAG_84_
__HTML_TAG_85_
## Tavola dei contenuti
- [Installazione](#installazione)
- [Project Creation](#project-creation)
- [Struttura progetto](#struttura progetto)
[Routing](#routing)
- [Pages and Layouts](#pages-and-layouts)
[API Routes](#api-routes)
[Data Fetching](#data-fetching)
[Styling](#styling)
- [Image Optimization](#image-ottimizzazione)
- [Ottimizzazione delle prestazioni](#ottimizzazione delle prestazioni)
[Authentication](#authentication)
- [Integrazione database](#database-integrazione)
- [Deployment](#deployment)
[Testing](#testing)
- [Troubleshooting](#troubleshooting)
[Le migliori pratiche](#best-practices)
## Installazione
## Prerequisiti
Traduzione:
## # Create Next.js App
Traduzione:
### Installazione manuale
Traduzione:
### Package.json Scripts
Traduzione:
## Project Creation
### Template disponibili
Traduzione:
### Development Server
Traduzione:
## # Build and Production
Traduzione:
## Struttura del progetto
### App Router Structure (Next.js 13+)
Traduzione:
## Pages Router Structure (Legacy)
Traduzione:
# Routing #
### App Router (Next.js 13+)
#### Routing basato su file
Traduzione:
#### Routes dinamiche
Traduzione:
### Catch-all Routes
Traduzione:
### Navigazione
#
### Route Groups and Parallel Route
Traduzione:
## Pagine e layout
## Root Layout
Traduzione:
## Layouts Nested
Traduzione:
### Page Components
Traduzione:
## Caricamento e Stati di errore
Traduzione:
## API Routes
### App Router API Router Routes
Traduzione:
### Routes API dinamiche
Traduzione:
## Middleware #
Traduzione:
### Gestione errori API
Traduzione:
# Prelievo dei dati
### Componenti server (Default)
Traduzione:
### Componenti client
Traduzione:
### Static Site Generation (SSG)
Traduzione:
## Incremental Static Regeneration (ISR)
Traduzione:
# Styling #
### Modulo CSS
Traduzione:
// components/Home.tsx
import styles from '../styles/Home.module.css' ;
export default function Home () {
return (
< div className = { styles . container } >
< main className = { styles . main } >
< h1 className = { styles . title } > Welcome to Next . js !< /h1>
< /main>
< /div>
);
}
## Tailwind CSS
Traduzione:
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module . exports = {
content : [
'./pages/**/*.{js,ts,jsx,tsx,mdx}' ,
'./components/**/*.{js,ts,jsx,tsx,mdx}' ,
'./app/**/*.{js,ts,jsx,tsx,mdx}' ,
],
theme : {
extend : {
colors : {
primary : '#3b82f6' ,
secondary : '#64748b' ,
},
},
},
plugins : [],
};
/* app/globals.css */
@ tailwind base ;
@ tailwind components ;
@ tailwind utilities ;
@ layer components {
. btn-primary {
@apply bg-primary text-white px-4 py-2 rounded hover : bg-blue-600 ;
}
}
### Styled Components
Traduzione:
// components/Button.tsx
import styled from 'styled-components' ;
const StyledButton = styled . button < { variant ?: 'primary' | 'secondary' } > `
padding: 0.5rem 1rem;
border: none;
border-radius: 0.25rem;
cursor: pointer;
font-weight: 500;
${ props => props . variant === 'primary' && `
background-color: #3b82f6;
color: white;
&:hover {
background-color: #2563eb;
}
` }
${ props => props . variant === 'secondary' && `
background-color: #6b7280;
color: white;
&:hover {
background-color: #4b5563;
}
` }
` ;
export default function Button ({ children , variant = 'primary' , ... props }) {
return (
< StyledButton variant = { variant } {... props } >
{ children }
< /StyledButton>
);
}
### CSS-in-JS with Emotion
Traduzione:
// components/Card.tsx
import styled from '@emotion/styled' ;
import { css } from '@emotion/react' ;
const Card = styled . div `
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 1rem;
margin: 1rem 0;
` ;
const cardTitle = css `
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 0.5rem;
color: #1f2937;
` ;
export default function ProductCard ({ title , description }) {
return (
< Card >
< h3 css = { cardTitle } > { title } < /h3>
< p > { description } < /p>
< /Card>
);
}
## Ottimizzazione immagine
## Next.js Image Component
Traduzione:
### Configurazione immagine
Traduzione:
### Custom Image Loader
Traduzione:
## Ottimizzazione delle prestazioni
### Analisi Bundle
Traduzione:
### Codice Spalato
Traduzione:
### Carico pigro
Traduzione:
### Performance Monitoring
Traduzione:
### Caching Strategies
Traduzione:
## Autenticazione
## NextAuth.js Setup
Traduzione:
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth' ;
import GoogleProvider from 'next-auth/providers/google' ;
import CredentialsProvider from 'next-auth/providers/credentials' ;
const handler = NextAuth ({
providers : [
GoogleProvider ({
clientId : process.env.GOOGLE_CLIENT_ID ! ,
clientSecret : process.env.GOOGLE_CLIENT_SECRET ! ,
}),
CredentialsProvider ({
name : 'credentials' ,
credentials : {
email : { label : 'Email' , type : 'email' },
password : { label : 'Password' , type : 'password' }
},
async authorize ( credentials ) {
// Verify credentials
const user = await verifyCredentials ( credentials );
return user ? { id : user.id , email : user.email } : null ;
}
})
],
callbacks : {
async jwt ({ token , user }) {
if ( user ) {
token . id = user . id ;
}
return token ;
},
async session ({ session , token }) {
session . user . id = token . id ;
return session ;
},
},
pages : {
signIn : '/auth/signin' ,
signUp : '/auth/signup' ,
},
});
export { handler as GET , handler as POST };
## Gestione sessione
Traduzione:
### Itinerari protetti
Traduzione:
## Integrazione Database
### Prisma Setup
Traduzione:
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
// lib/prisma.ts
import { PrismaClient } from '@prisma/client' ;
const globalForPrisma = globalThis as unknown as {
prisma : PrismaClient | undefined ;
};
export const prisma = globalForPrisma . prisma ?? new PrismaClient ();
if ( process . env . NODE_ENV !== 'production' ) globalForPrisma . prisma = prisma ;
### Database Operations
Traduzione:
### Integrazione API
Traduzione:
#
## Vercel Deployment
Traduzione:
// vercel.json
{
"framework" : "nextjs" ,
"buildCommand" : "npm run build" ,
"devCommand" : "npm run dev" ,
"installCommand" : "npm install" ,
"functions" : {
"app/api/**/*.ts" : {
"maxDuration" : 30
}
},
"regions" : [ "iad1" ],
"env" : {
"DATABASE_URL" : "@database-url"
}
}
## Docker Deployment
__________
### Esportazione statica
Traduzione:
# Build and export
npm run build
# Serve static files
npx serve out
## Testing
## Jest e React Test Library
Traduzione:
// jest.config.js
const nextJest = require ( 'next/jest' );
const createJestConfig = nextJest ({
dir : './' ,
});
const customJestConfig = {
setupFilesAfterEnv : [ '<rootDir>/jest.setup.js' ],
moduleNameMapping : {
'^@/components/(.*)$' : '<rootDir>/components/$1' ,
'^@/pages/(.*)$' : '<rootDir>/pages/$1' ,
},
testEnvironment : 'jest-environment-jsdom' ,
};
module . exports = createJestConfig ( customJestConfig );
// jest.setup.js
import '@testing-library/jest-dom' ;
### Component Testing
Traduzione:
### API Testing
Traduzione:
### E2E Prova con Playwright
Traduzione:
// tests/e2e/home.spec.ts
import { test , expect } from '@playwright/test' ;
test ( 'homepage loads correctly' , async ({ page }) => {
await page . goto ( '/' );
await expect ( page ). toHaveTitle ( /My App/ );
await expect ( page . getByRole ( 'heading' , { name : 'Welcome' })). toBeVisible ();
});
test ( 'navigation works' , async ({ page }) => {
await page . goto ( '/' );
await page . getByRole ( 'link' , { name : 'About' }). click ();
await expect ( page ). toHaveURL ( '/about' );
await expect ( page . getByRole ( 'heading' , { name : 'About' })). toBeVisible ();
});
## Risoluzione dei problemi
### Questioni comuni
### Hydration Mismatch
Traduzione:
#### Memory Leaks
Traduzione:
#### Costruire errori
Traduzione:
### Performance Issues
Traduzione:
# Migliori Pratiche
### Struttura del progetto
Traduzione:
## Performance Best Practices
Traduzione:
### SEO # Migliori Pratiche
Traduzione:
### Migliori pratiche di sicurezza
Traduzione:
---
## Sommario
Next.js è un potente framework React che fornisce una soluzione completa per la costruzione di applicazioni web moderne. Le caratteristiche principali includono:
- **App Router**: Nuovo sistema di routing con layout, stati di carico e limiti di errore
- **Server Components**: Componenti di ricambio sul server per prestazioni migliori
- **API Routes**: endpoint API integrati con funzionalità complete
- **Image Optimization**: ottimizzazione automatica dell'immagine e carico pigro
- **Performance**: Ottimizzazioni integrate per Core Web Vitals
- **Deployment**: Distribuzione senza cuciture a Vercel e altre piattaforme
Per ottenere risultati ottimali, sfruttare i Componenti Server per impostazione predefinita, utilizzare i Componenti client con parsimonia, implementare strategie di caching adeguate e seguire le convenzioni Next.js per il routing e il recupero dati.