NextJS中文文档 - Static Exports
Next.js 允许从静态站点或单页应用程序 (SPA) 开始,然后以后可以选择升级以使用需要服务器的功能。
当运行 next build
时,Next.js 为每个路由生成一个 HTML 文件。通过将严格的 SPA 分解为单独的 HTML 文件,Next.js 可以避免在客户端加载不必要的 JavaScript 代码,减小包的大小并实现更快的页面加载。
由于 Next.js 支持这种静态导出,它可以部署和托管在任何能够提供 HTML/CSS/JS 静态资源的 Web 服务器上。
配置
要启用静态导出,请在 next.config.js
中更改输出模式:
js
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'export',
// 可选:更改链接 `/me` -> `/me/` 并生成 `/me.html` -> `/me/index.html`
// trailingSlash: true,
// 可选:阻止自动 `/me` -> `/me/`,而是保留 `href`
// skipTrailingSlashRedirect: true,
// 可选:更改输出目录 `out` -> `dist`
// distDir: 'dist',
}
module.exports = nextConfig
运行 next build
后,Next.js 将创建一个包含应用程序 HTML/CSS/JS 资源的 out
文件夹。
图像优化
通过 next/image
进行的图像优化可以通过在 next.config.js
中定义自定义图像加载器与静态导出一起使用。例如,你可以使用 Cloudinary 等服务优化图像:
js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
images: {
loader: 'custom',
loaderFile: './my-loader.ts',
},
}
module.exports = nextConfig
这个自定义加载器将定义如何从远程源获取图像。例如,以下加载器将构造 Cloudinary 的 URL:
ts
export default function cloudinaryLoader({
src,
width,
quality,
}: {
src: string
width: number
quality?: number
}) {
const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
return `https://res.cloudinary.com/demo/image/upload/${params.join(',')}${src}`
}
js
export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
return `https://res.cloudinary.com/demo/image/upload/${params.join(',')}${src}`
}
然后,你可以在你的应用程序中使用 next/image
,定义 Cloudinary 中图像的相对路径:
tsx
import Image from 'next/image'
export default function Page() {
return <Image alt="海龟" src="/turtles.jpg" width={300} height={300} />
}
jsx
import Image from 'next/image'
export default function Page() {
return <Image alt="海龟" src="/turtles.jpg" width={300} height={300} />
}
不支持的功能
需要 Node.js 服务器或无法在构建过程中计算的动态逻辑的功能不受支持:
部署
使用静态导出,Next.js 可以部署和托管在任何能够提供 HTML/CSS/JS 静态资源的 Web 服务器上。
运行 next build
时,Next.js 将静态导出生成到 out
文件夹中。例如,假设你有以下路由:
/
/blog/[id]
运行 next build
后,Next.js 将生成以下文件:
/out/index.html
/out/404.html
/out/blog/post-1.html
/out/blog/post-2.html
如果你使用像 Nginx 这样的静态主机,你可以配置从传入请求到正确文件的重写:
nginx
server {
listen 80;
server_name acme.com;
root /var/www/out;
location / {
try_files $uri $uri.html $uri/ =404;
}
# 当 `trailingSlash: false` 时这是必需的。
# 当 `trailingSlash: true` 时你可以省略这个。
location /blog/ {
rewrite ^/blog/(.*)$ /blog/$1.html break;
}
error_page 404 /404.html;
location = /404.html {
internal;
}
}
版本历史
版本 | 变更 |
---|---|
v14.0.0 | next export 已被移除,转而使用 "output": "export" |
v13.4.0 | App Router(稳定版)添加了增强的静态导出支持,包括使用 React 服务器组件和路由处理程序。 |
v13.3.0 | next export 已弃用,替换为 "output": "export" |