Next.js:如何为具有多个域/主机名的站点使用 getStaticProps/getStaticPaths?

Tom*_*und 8 reactjs next.js vercel

我正在构建一个具有结构的站点https://[sub.domain.ext]/[language]/articles/[slug],但是它在不同的域(不同的主机名)上会有不同的内容。

一个典型的用例是相同内容的不同语言翻译的不同子域:en.mysite.com、fr.mysite.com 等。

我不想诉诸服务器端渲染使用getServerSideProps(如果内容很少更改,则性能会降低并且不必要)。我可以以某种方式使用getStaticProps/getStaticPaths生成静态站点吗?

这是我当前的siteId = 1硬编码实现:

import React from 'react'
import { useRouter } from 'next/router'

import Page from 'components/page/Page'
import Error from 'components/page/Error'
import ArticleList from 'components/articles/ArticleList'

const { runDatabaseFunction } = require('lib/database')
const { getArticlesForSiteAndLanguage } = require('lib/data/articles')

function ArticleListPage ({ site, articles, error }) {
  const { asPath } = useRouter()
  const title = 'News'
  return (
    <Page
      title={title}
      site={site}
      path={asPath}
    >
      <h1>{title}</h1>

      {error && <Error error={error} />}

      <ArticleList
        articles={articles}
      />
    </Page>
  )
}
export default ArticleListPage

export async function getStaticProps ({ params: { siteId = 1, languageCode = 'en' } }) {
  return {
    revalidate: 10,
    props: await runDatabaseFunction(async (pool) => getArticlesForSiteAndLanguage(pool, { siteId, languageCode }))
  }
}

export async function getStaticPaths () {
  return {
    paths: [
      { params: { languageCode: 'en' } } //  '[siteId]' is not part of folder structure
    ],
    fallback: true
  }
}
Run Code Online (Sandbox Code Playgroud)

更新

也可以看看:

Tom*_*und 5

几种方法:

\n

1.使用Next.js语言环境系统

\n

这里\xe2\x80\x99是使用Next.js\xe2\x80\x99 i18n系统在同一个Next.js站点上托管多个域的示例(同时维护多种语言和静态站点生成/SSG):

\n\n

这个概念:

\n
    \n
  • Next.js\xe2\x80\x99 i18nlocale用于确定站点
  • \n
  • 选择语言是通过pseudoLocaleprop(/[pseudoLocale]文件夹中的页面)来处理的。
  • \n
  • 从到重定向。//en
  • \n
\n

2. 在 Next.js 10.2 中使用重写

\n

请参阅此对话此代码存储库

\n