Static Exports
Next.js 支持从静态站点或单页应用 (SPA) 开始,之后可以选择升级使用需要服务器的功能。
在运行 next build
时,Next.js 会为每个路由生成一个 HTML 文件。通过将严格的 SPA 拆分成单独的 HTML 文件,Next.js 可以避免在客户端加载不必要的 JavaScript 代码,从而减小包的大小并实现更快的页面加载。
由于 Next.js 支持这种静态导出,它可以被部署和托管在任何能够提供 HTML/CSS/JS 静态资源的 Web 服务器上。
配置
要启用静态导出,请在 next.config.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 将生成一个 out
文件夹,其中包含你应用程序的 HTML/CSS/JS 资源。
你可以使用 getStaticProps
和 getStaticPaths
为 pages
目录中的每个页面生成一个 HTML 文件 (对于 动态路由 可能会生成更多)。
支持的功能
大多数构建静态站点所需的 Next.js 核心功能都得到支持,包括:
- 使用
getStaticPaths
的动态路由 - 使用
next/link
进行预获取 - 预加载 JavaScript
- 动态导入
- 任何样式选项 (例如 CSS Modules、styled-jsx)
- 客户端数据获取
getStaticProps
getStaticPaths
图像优化
通过在 next.config.js
中定义自定义图像加载器,可以在静态导出中使用 next/image
进行 图像优化。例如,你可以使用 Cloudinary 这样的服务来优化图像:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
images: {
loader: "custom",
loaderFile: "./my-loader.ts",
},
};
module.exports = nextConfig;
这个自定义加载器将定义如何从远程源获取图像。例如,以下加载器将构造 Cloudinary 的 URL:
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}`;
}
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 中图像的相对路径:
import Image from "next/image";
export default function Page() {
return <Image alt="海龟" src="/turtles.jpg" width={300} height={300} />;
}
不支持的功能
需要 Node.js 服务器或无法在构建过程中计算的动态逻辑的功能 不 受支持:
- 国际化路由
- API 路由
- 重写
- 重定向
- Headers
- 中间件
- 增量静态再生成
- 使用默认
loader
的 图像优化 - 草稿模式
getStaticPaths
与fallback: true
getStaticPaths
与fallback: 'blocking'
getServerSideProps
部署
通过静态导出,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 这样的静态主机,你可以配置重写规则,将传入的请求重定向到正确的文件:
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" |