02. 项目配置详解
Next.js 提供了丰富的配置选项,让你可以自定义框架的行为。本章将深入讲解核心配置文件。
1. next.config.js - Next.js 核心配置
next.config.js 是 Next.js 项目的主配置文件,用于自定义构建、路由、图片优化等行为。
基础配置结构
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
// 配置项
}
module.exports = nextConfig常用配置项详解
1.1 图片优化配置
const nextConfig = {
images: {
// 允许的图片域名(外部图片需要配置)
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
pathname: '/images/**',
},
],
// 图片格式
formats: ['image/avif', 'image/webp'],
// 设备尺寸断点
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}实战案例:配置 CDN 图片域名
// next.config.js
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.example.com',
},
{
protocol: 'https',
hostname: '**.cloudinary.com', // 支持通配符
},
],
},
}1.2 环境变量配置
const nextConfig = {
env: {
// 自定义环境变量(会被注入到客户端和服务端)
CUSTOM_KEY: 'custom-value',
},
}⚠️ 注意:这里配置的变量会暴露到客户端,敏感信息不要放在这里。应该使用
.env文件。
1.3 重定向和重写
const nextConfig = {
// 重定向(改变 URL)
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true, // 301 永久重定向
},
]
},
// 重写(不改变 URL,但改变请求目标)
async rewrites() {
return [
{
source: '/api/proxy/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
}实战案例:API 代理
// next.config.js
const nextConfig = {
async rewrites() {
return [
{
source: '/api/external/:path*',
destination: 'https://jsonplaceholder.typicode.com/:path*',
},
]
},
}
// 使用:在组件中调用 /api/external/posts/1
// 实际请求会被转发到 https://jsonplaceholder.typicode.com/posts/11.4 输出配置
const nextConfig = {
// 输出模式
output: 'standalone', // 或 'export'(静态导出)
// 如果设置为 'export',会生成纯静态 HTML
// output: 'export',
}1.5 实验性功能
const nextConfig = {
experimental: {
// 启用服务器组件外部包
serverComponentsExternalPackages: ['some-package'],
// 优化包导入
optimizePackageImports: ['@mui/material', 'lodash'],
},
}2. TypeScript 配置 (tsconfig.json)
TypeScript 配置决定了类型检查的严格程度和编译选项。
基础配置
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.tsx"],
"exclude": ["node_modules"]
}关键配置项说明
| 配置项 | 说明 | 推荐值 |
|---|---|---|
strict | 启用所有严格类型检查 | true |
noEmit | 不生成 JS 文件(Next.js 自己处理) | true |
paths | 路径别名,@/* 指向 src/* | 已配置 |
jsx | JSX 处理方式 | "preserve" |
实战:添加路径别名
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./src/components/*"],
"@/utils/*": ["./src/utils/*"],
"@/types/*": ["./src/types/*"]
}
}
}使用示例:
// 之前
import Button from '../../../components/Button'
// 现在
import Button from '@/components/Button'3. ESLint 配置
ESLint 用于代码质量检查和规范。
Next.js 默认配置
Next.js 会自动生成 .eslintrc.json:
{
"extends": ["next/core-web-vitals", "next/typescript"]
}自定义规则
{
"extends": ["next/core-web-vitals", "next/typescript"],
"rules": {
// 禁止使用 console.log(生产环境)
"no-console": ["warn", { "allow": ["warn", "error"] }],
// 要求使用 === 而不是 ==
"eqeqeq": ["error", "always"],
// 未使用的变量警告
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]
}
}实战:配置 Prettier 集成
步骤 1:安装依赖
npm install -D prettier eslint-config-prettier步骤 2:创建 .prettierrc
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}步骤 3:更新 .eslintrc.json
{
"extends": [
"next/core-web-vitals",
"next/typescript",
"prettier"
]
}4. 完整配置示例
企业级 next.config.js
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
// 图片配置
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
formats: ['image/avif', 'image/webp'],
},
// 重定向
async redirects() {
return [
{
source: '/home',
destination: '/',
permanent: true,
},
]
},
// 重写(API 代理)
async rewrites() {
return [
{
source: '/api/proxy/:path*',
destination: `${process.env.API_BASE_URL}/:path*`,
},
]
},
// 环境变量
env: {
APP_NAME: 'My Next.js App',
},
// 实验性功能
experimental: {
optimizePackageImports: ['@mui/material'],
},
// 压缩
compress: true,
// 生产环境移除 console
...(process.env.NODE_ENV === 'production' && {
compiler: {
removeConsole: {
exclude: ['error', 'warn'],
},
},
}),
}
module.exports = nextConfig5. 实战练习:配置一个博客项目
需求
配置一个博客项目,要求:
- 支持外部图片 CDN(如 Unsplash)
- 配置
/blog重定向到/posts - 设置路径别名
@/components、@/lib
实现
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
],
},
async redirects() {
return [
{
source: '/blog',
destination: '/posts',
permanent: true,
},
]
},
}
module.exports = nextConfigtsconfig.json(添加路径别名)
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./src/components/*"],
"@/lib/*": ["./src/lib/*"]
}
}
}6. 配置验证
检查配置是否正确
# 检查 TypeScript 配置
npx tsc --noEmit
# 检查 ESLint
npm run lint
# 检查 Next.js 配置
npm run build7. 总结
本章我们学习了:
- ✅
next.config.js的核心配置项(图片、重定向、重写等) - ✅ TypeScript 配置和路径别名
- ✅ ESLint 规则自定义
- ✅ 企业级配置最佳实践
下一步:在下一章,我们将学习环境变量的管理,这是开发和生产环境切换的关键。