# 静态HTML导出

Examples

  • Static Export

next exportallows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use next exportif you don't need any of the unsupported features requiring a server.

If you're looking to build a hybrid site where only somepages are prerendered to static HTML, Next.js already does that automatically. Learn more about Automatic Static Optimization and Incremental Static Regeneration .

# next export

Update your build script in package.jsonto use next export:

"scripts": {
  "build": "next build && next export"
}

Running npm run buildwill generate an outdirectory.

next exportbuilds an HTML version of your app. During next build, getStaticProps and getStaticPaths will generate an HTML file for each page in your pagesdirectory (or more for dynamic routes . Then, next exportwill copy the already exported files into the correct directory. getInitialPropswill generate the HTML files during next exportinstead of next build.

For more advanced scenarios, you can define a parameter called exportPathMap in your next.config.js file to configure exactly which pages will be generated.

# Supported Features

The majority of core Next.js features needed to build a static site are supported, including:

  • Dynamic Routes when using getStaticPaths
  • Prefetching with next/link
  • Preloading JavaScript
  • Dynamic Imports
  • Any styling options (e.g. CSS Modules, styled-jsx)
  • Client-side data fetching
  • getStaticProps
  • getStaticPaths
  • Image Optimization using a custom loader

# Unsupported Features

Features that require a Node.js server, or dynamic logic that cannot be computed during the build process, are not supported:

  • Image Optimization (default loader)
  • Internationalized Routing
  • API Routes
  • Rewrites
  • Redirects
  • Headers
  • Middleware
  • Incremental Static Regeneration
  • fallback: true
  • getServerSideProps

# getInitialProps

It's possible to use the getInitialProps API instead of getStaticProps, but it comes with a few caveats:

  • getInitialPropscannot be used alongside getStaticPropsor getStaticPathson any given page. If you have dynamic routes, instead of using getStaticPathsyou'll need to configure the exportPathMap parameter in your next.config.js file to let the exporter know which HTML files it should output.
  • When getInitialPropsis called during export, the reqand resfields of its context parameter will be empty objects, since during export there is no server running.
  • getInitialPropswill be called on every client-side navigation, if you'd like to only fetch data at build-time, switch to getStaticProps.
  • getInitialPropsshould fetch from an API and cannot use Node.js-specific libraries or the file system like getStaticPropscan.

We recommend migrating towards getStaticPropsover getInitialPropswhenever possible.

Last Updated: 5/13/2023, 8:55:38 PM