部署
要为生产环境构建网站的静态文件,请运行:
- npm
- Yarn
- pnpm
npm run build
yarn build
pnpm run build
完成后,静态文件会被生成在 build
目录中。
Docusaurus 只负责构建站点,然后把静态文件输出到 build
文件夹。
现在,该由你来决定怎么托管这些静态文件了。
你可以把你的网站部署到静态网站托管服务上,比如 Vercel、GitHub Pages、Netlify、Render、Surge,等等。
Docusaurus 网站是静态渲染的,而且一般不需要 JavaScript 也能运行!
配置
在 docusaurus.config.js
中,下面这些参数是必填的,让 Docusaurus 能够优化路由,并从正确的位置加载文件:
参数 | 描述 |
---|---|
url | 站点 URL。 如果网站部署在 https://my-org.com/my-project/ , url 就是 https://my-org.com/ |
baseUrl | 站点的 base URL,带有末尾斜杠。 如果网站部署在 https://my-org.com/my-project/ , baseUrl 就是 /my-project/ |
本地测试构建
在部署到生产环境前,事先进行本地测试尤为重要。 Docusaurus 提供了 docusaurus serve
命令来测试:
- npm
- Yarn
- pnpm
npm run serve
yarn serve
pnpm run serve
站点默认会部署在 http://localhost:3000/
。
末尾斜杠配置
Docusaurus 有一个 trailingSlash
配置,允许你自定义 URL 链接和输出的文件名格式。
你一般不需要修改默认值。 遗憾的是,每家静态托管商的行为都不一样,而把同一网站部署到不同服务商的结果可能大相径庭。 根据你的托管商的不同,你可能需要修改此配置。
要更好地了解你的托管商的行为,可以参见 slorber/trailing-slash-guide,并依此配置 trailingSlash
选项。
使用环境变量
把可能敏感的信息放在环境变量中的做法很常见。 然而,在典型的 Docusaurus 网站中, docusauurus.config.js
文件是唯一一个可以接触到 Node.js 环境的地方(参见我们的架构概述)。除此之外的所有东西(MDX 页面,React 组件等等),都处于客户端中,不能直接访问 process
全局变量。 在这种情况下,你可以考虑使用 customFields
将环境变量传递给客户端。
// If you are using dotenv (https://www.npmjs.com/package/dotenv)
import 'dotenv/config';
export default {
title: '...',
url: process.env.URL, // You can use environment variables to control site specifics as well
customFields: {
// Put your custom environment here
teamEmail: process.env.EMAIL,
},
};
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
export default function Home() {
const {
siteConfig: {customFields},
} = useDocusaurusContext();
return <div>通过 {customFields.teamEmail} 联系我们!</div>;
}
选择托管服务商
有几种常见的托管选择:
- Self hosting with an HTTP server like Apache2 or Nginx.
- Jamstack providers (e.g. Netlify and Vercel). 我们会以它们为参考,但同样的道理也可以适用于其他提供商。
- GitHub Pages (by definition, it is also Jamstack, but we compare it separately).
如果你不清楚选择哪一个,问自己下面几个问题:
How many resources (money, person-hours, etc.) am I willing to invest in this?
- 🔴 Self-hosting requires experience in networking as well as Linux and web server administration. It's the most difficult option, and would require the most time to manage successfully. Expense-wise, cloud services are almost never free, and purchasing/deploying an onsite server can be even more costly.
- 🟢 Jamstack providers can help you set up a working website in almost no time and offer features like server-side redirects that are easily configurable. Many providers offer generous build-time quotas even for free plans that you would almost never exceed. However, free plans have limits, and you would need to pay once you hit those limits. 要了解详情,请查看你的提供商的定价页面。
- 🟡 GitHub Pages 部署的工作流程设置起来可能很麻烦。 (不信的话,可以看看部署到 GitHub Pages 部分的长度!) 但是,这项服务(包括构建和部署)对所有公共仓库都永久免费,并且我们也有详细教程,帮助你正确运行它。
How much server-side customization do I need?
- 🟢 自行托管时,你可以控制整个服务器的配置。 You can configure the virtual host to serve different content based on the request URL, you can do complicated server-side redirects, you can implement authentication, and so on. 如果你需要很多服务器端功能,请选择自行托管网站。
- 🟡 Jamstack usually offers some server-side configuration (e.g. URL formatting (trailing slashes), server-side redirects, etc.).
- 🔴 GitHub Pages doesn't expose server-side configuration besides enforcing HTTPS and setting CNAME records.
Do I need collaboration-friendly deployment workflows?
- 🟡 Self-hosted services can leverage continuous deployment functionality like Netlify, but more heavy-lifting is involved. Usually, you would designate a specific person to manage the deployment, and the workflow wouldn't be very git-based as opposed to the other two options.
- 🟢 Netlify 和 Vercel 对每个 Pull Request 都会生成部署预览,这对于在合并到生产环境之前的团队审核工作非常有用。 你也可以做团队管理,不同成员拥有不同的部署访问权限。
- 🟡 GitHub 页面不能做部署预览,至少方法非常复杂。 每个仓库只能和一个站点部署相关联。 另一方面,你还是可以控制哪些人有站点部署的写权限。
不存在通用方案。 你需要权衡你的需求和资源,然后再做决定。
自行托管
你可以用 docusaurus service
命令来自行托管 Docusaurus。 可以用 --port
和 --host
来分别更改端口和绑定主机。
- npm
- Yarn
- pnpm
npm run serve -- --build --port 80 --host 0.0.0.0
yarn serve --build --port 80 --host 0.0.0.0
pnpm run serve --build --port 80 --host 0.0.0.0
相较于其他静态托管提供商 / CDN,这不是最佳解决方案。
在后面几节中,我们会介绍几个常用的托管提供商,以及如何做最有效的 Docusaurus 部署设置。 Docusaurus is not affiliated with any of these services, and this information is provided for convenience only. Some of the write-ups are provided by third-parties, and recent API changes may not be reflected on our side. If you see outdated content, PRs are welcome.
Because we can only provide this content on a best-effort basis only, we have stopped accepting PRs adding new hosting options. 不过你可以在其他网站上写一篇关于某个服务提供商的文章(比如你的博客,或者提供商官网),然后让我们添加一个这篇文章的链接。
部署到 Netlify
To deploy your Docusaurus sites to Netlify, first make sure the following options are properly configured:
export default {
url: 'https://docusaurus-2.netlify.app', // Url to your site with no trailing slash
baseUrl: '/', // Base directory of your site relative to your repo
// ...
};
然后,用 Netlify 创建你的网站。
在设立站点时,指定如下构建指令和目录:
- 构建指令:
npm run build
- 发布目录:
build
如果你没有设置这些构建选项,你还是可以在创建站点之后前往 "Site settings" -> "Build & deploy" 完成配置。
用上述选项配置完毕后,你的网站就会在有代码合并到部署分支(默认为 main
)时自动重新部署,
某些 Docusaurus 网站把 docs
文件夹放在 website
之外(尤其是从 Docusaurus v1 迁移而来的站点):
repo # git 根目录
├── docs # MD 文件
└── website # Docusaurus 根目录
如果你选择用 website
文件夹作为 Netlify 的 base directory,那么更新 docs
时,Netlify 不会触发构建。你需要配置自定义 ignore
命令:
[build]
ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF . ../docs/"
默认情况下,Netlify 会为 Docusaurus URL 添加末尾斜杠。
It is recommended to disable the Netlify setting Post Processing > Asset Optimization > Pretty Urls
to prevent lowercase URLs, unnecessary redirects, and 404 errors.
特别当心:Disable asset optimization
的全局选项不能正常工作,实际上并不会禁用 Pretty URLs
设置。 请确保单独取消勾选了 "Pretty URLs"。
如果你想保持开启 Pretty URLs
Netlify 设置,就要适当配置 Docusaurus 的 trailingSlash
选项。
更多信息请参阅 slorber/trailing-slash-guide。
部署到 Vercel
部署 Docusaurus 项目到 Vercel 会带来多项收益,包括性能、易用性,等等。
要通过 Vercel 的 Git 集成部署你的 Docusaurus 项目,先确保项目已经被推送到了某个 Git 仓库中。
用 Import Flow 把项目导入进 Vercel。 During the import, you will find all relevant options preconfigured for you; however, you can choose to change any of these options.
项目导入完成后,所有分支的后续推送都会生成部署预览。所有生产分支(通常是 "main" 或 "master")的变更都会触发生产部署。
部署到 GitHub Pages
Docusaurus provides an easy way to publish to GitHub Pages, which comes free with every GitHub repository.
概览
Usually, there are two repositories (at least two branches) involved in a publishing process: the branch containing the source files, and the branch containing the build output to be served with GitHub Pages. 在下面的教程中,我们会把这两个仓库(分支)分别叫作源仓库(分支)和部署仓库(分支)。
每个 GitHub 仓库都关联有一个 GitHub Pages 服务。 如果部署仓库叫作 my-org/my-project
(my-org
是组织名或用户名),那么网站会被部署在 https://my-org.github.io/my-project/
处。 If the deployment repository is called my-org/my-org.github.io
(the organization GitHub Pages repo), the site will appear at https://my-org.github.io/
.
如果你需要为 GitHub Pages 自定义域名,可以在 static
目录中创建一个 CNAME
文件。 static
目录中的内容会在部署时被复制到 build
文件夹的根部。 使用自定义域名时,就可以把 baseUrl: '/projectName/'
改回 baseUrl: '/'
了,也可以把 url
设置成你的自定义域名。
你可以参阅 GitHub Pages 的关于 GitHub Pages 文档了解详情。
Github Pages 会从默认分支(一般是 master
/main
)或者 gh-pages
分支中提取部署文件(运行 docusaurus build
产生的文件)。文件可以放在根目录,也可以放在 /docs
目录中。 你可以在仓库的 Settings > Pages
处配置。 这个分支会被称作「部署分支」。
我们提供了 docusaurus deploy
命令,帮助你从源仓库部署到部署仓库,一步完成克隆、构建、提交。
docusaurus.config.js
设置
首先,修改你的 docusaurus.config.js
,添加如下参数:
参数 | 描述 |
---|---|
organizationName | 拥有部署仓库的 GitHub 用户或组织。 |
projectName | 部署仓库的名字。 |
deploymentBranch | The name of the deployment branch. It defaults to 'gh-pages' for non-organization GitHub Pages repos (projectName not ending in .github.io ). Otherwise, it needs to be explicit as a config field or environment variable. |
These fields also have their environment variable counterparts which have a higher priority: ORGANIZATION_NAME
, PROJECT_NAME
, and DEPLOYMENT_BRANCH
.
GitHub Pages 默认为 Docusaurus 网址链接添加末尾斜杠。 建议设置 trailingSlash
(true
或 false
都可以,只要不是 undefined
)。
示例:
export default {
// ...
url: 'https://endiliey.github.io', // 你的网站 URL
baseUrl: '/',
projectName: 'endiliey.github.io',
organizationName: 'endiliey',
trailingSlash: false,
// ...
};
默认情况下,GitHub Pages 会用 Jekyll 构建要被发布的文件。 因为 Jekyll 会忽略所有以 _
开头的文件,所以我们推荐你在 static
文件夹中新建一个 .nojekyll
文件来禁用 Jekyll。
环境设置
参数 | 描述 |
---|---|
USE_SSH | 设置为 true 时,会用 SSH 而不是默认的 HTTPS 来连接到 GitHub 源仓库。 如果源仓库的地址是 SSH URL(比如 [email protected]:facebook/docusaurus.git ),USE_SSH 会被推断为 true 。 |
GIT_USER | 用于推送部署文件的 GitHub 账户用户名,需要有部署仓库的推送权限。 对于你自己的仓库,这一般会是你自己的 GitHub 用户名。 不使用 SSH 时必填,使用 SSH 时则会被忽略。 |
GIT_PASS | GitHub 用户(GIT_USER 所指定)的 personal access token,用于非交互式部署(如持续部署) |
CURRENT_BRANCH | 源分支。 这个分支一般是 main 或 master ,但它也可以是 gh-pages 之外的任何分支。 如果变量没有赋值,那么会使用 docusaurus deploy 被调用时的分支。 |
GIT_USER_NAME | The git config user.name value to use when pushing to the deployment repo |
GIT_USER_EMAIL | The git config user.email value to use when pushing to the deployment repo |
GitHub 企业安装版应该和 github.com 的工作方式一致。你只需要在环境变量中设置组织的 GitHub 企业主机即可。
参数 | 描述 |
---|---|
GITHUB_HOST | 你的 GitHub 企业网站的域名。 |
GITHUB_PORT | 你的 GitHub 企业网站的端口。 |
部署
最后,要把你的网站部署到 GitHub Pages 上,请运行:
- Bash
- Windows
- PowerShell
GIT_USER=<GITHUB_USERNAME> yarn deploy
cmd /C "set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy"
cmd /C 'set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy'
从 2021 年 8 月开始,GitHub 要求每次命令行登录都使用个人访问令牌,而不是密码。 当 GitHub 提示你输入密码时,请输入个人访问令牌。 更多信息请见 GitHub 文档。
或者,你也可以使用 SSH (USE_SSH=true
) 登录。
触发 GitHub Actions 部署
GitHub Actions 允许你在仓库中完成软件开发流程的自动化、自定义执行。
The workflow examples below assume your website source resides in the main
branch of your repository (the source branch is main
), and your publishing source is configured for publishing with a custom GitHub Actions Workflow.
我们的目标是:
- 当向
main
发起新的拉取请求时,有一个 action 确保网站构建成功,但不会真正部署。 这个 job 会被称为test-deploy
。 - When a pull request is merged to the
main
branch or someone pushes to themain
branch directly, it will be built and deployed to GitHub Pages. 这个 job 会被称为deploy
。
下面是两种通过 GitHub Actions 部署文档的方法。 Based on the location of your deployment repository, choose the relevant tab below:
- 源代码仓库和部署代码仓库是同一仓库。
- 部署仓库是一个远程仓库,和源仓库不同。 Instructions for this scenario assume publishing source is the
gh-pages
branch.
- 同一
- 远程
While you can have both jobs defined in the same workflow file, the original deploy
workflow will always be listed as skipped in the PR check suite status, which is not indicative of the actual status and provides no value to the review process. 所以,我们建议把它们作为单独的工作流来管理。
GitHub action 文件
添加这两个工作流文件:
这些文件假设你使用的是 Yarn。 如果你用的是 npm,需要把 cache: yarn
、yarn install --frozen-lockfile
、yarn build
分别修改成 cache: npm
、npm ci
、npm run build
。
如果你的 Docusaurus 项目不在你的仓库的根目录,你可能需要配置默认工作目录,并相应地调整路径。
name: Deploy to GitHub Pages
on:
push:
branches:
- main
# Review gh actions docs if you want to further define triggers, paths, etc
# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on
jobs:
build:
name: Build Docusaurus
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18
cache: yarn
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Build website
run: yarn build
- name: Upload Build Artifact
uses: actions/upload-pages-artifact@v3
with:
path: build
deploy:
name: Deploy to GitHub Pages
needs: build
# Grant GITHUB_TOKEN the permissions required to make a Pages deployment
permissions:
pages: write # to deploy to Pages
id-token: write # to verify the deployment originates from an appropriate source
# Deploy to the github-pages environment
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
name: Test deployment
on:
pull_request:
branches:
- main
# Review gh actions docs if you want to further define triggers, paths, etc
# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on
jobs:
test-deploy:
name: Test deployment
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18
cache: yarn
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Test build website
run: yarn build
A cross-repo publish is more difficult to set up because you need to push to another repo with permission checks. 我们会使用 SSH 完成身份验证。
- 生成一个新 SSH 密钥。 因为这个 SSH 密钥会用在 CI 中,所以不能输入任何密码。
- 默认情况下,你的公钥应该会被创建在
~/.ssh/id_rsa.pub
中。如果没有,那么在添加 GitHub 部署密钥时,要记得使用你在前一步中提供的名字。 - 用
pbcopy < ~/.ssh/id_rsa.pub
把密钥复制到剪贴板,然后在你的部署仓库中,把它粘贴入部署密钥。 如果命令行不适合,可以手动复制文件内容。 在保存部署密钥之前,要勾选Allow write access
。 - 你需要把你的私钥设置成 GitHub secret,从而允许 Docusaurus 为你运行部署。
- 用
pbcopy < ~/.ssh/id_rsa
复制你的私钥,然后把它粘贴成一个 GitHub secret,名字叫GH_PAGES_DEPLOY
。 如果命令行不适合,可以手动复制文件内容。 保存你的 secret。 - 在
.github/workflows/
中创建你的文档工作流文件。 In this example, it'sdeploy.yml
.
At this point, you should have:
- the source repo with the GitHub workflow set with the private SSH key as the GitHub Secret, and
- your deployment repo set with the public SSH key in GitHub Deploy Keys.
GitHub action 文件
Please make sure that you replace [email protected]
with your GitHub email and gh-actions
with your name.
This file assumes you are using Yarn. 如果你用的是 npm,需要把 cache: yarn
、yarn install --frozen-lockfile
、yarn build
分别修改成 cache: npm
、npm ci
、npm run build
。
name: Deploy to GitHub Pages
on:
pull_request:
branches: [main]
push:
branches: [main]
permissions:
contents: write
jobs:
test-deploy:
if: github.event_name != 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18
cache: yarn
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Test build website
run: yarn build
deploy:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18
cache: yarn
- uses: webfactory/ssh-[email protected]
with:
ssh-private-key: ${{ secrets.GH_PAGES_DEPLOY }}
- name: Deploy to GitHub Pages
env:
USE_SSH: true
run: |
git config --global user.email "[email protected]"
git config --global user.name "gh-actions"
yarn install --frozen-lockfile
yarn deploy
网站没有正确部署?
After pushing to main, if you don't see your site published at the desired location (for example, it says "There isn't a GitHub Pages site here", or it's showing your repo's README.md file), try the following:
- Wait about three minutes and refresh. It may take a few minutes for GitHub pages to pick up the new files.
- Check your repo's landing page for a little green tick next to the last commit's title, indicating the CI has passed. If you see a cross, it means the build or deployment failed, and you should check the log for more debugging information.
- Click on the tick and make sure you see a "Deploy to GitHub Pages" workflow. Names like "pages build and deployment / deploy" are GitHub's default workflows, indicating your custom deployment workflow failed to be triggered at all. Make sure the YAML files are placed under the
.github/workflows
folder, and that the trigger condition is set correctly (e.g., if your default branch is "master" instead of "main", you need to change theon.push
property). - Under your repo's Settings > Pages, make sure the "Source" (which is the source for the deployment files, not "source" as in our terminology) is set to "gh-pages" + "/ (root)", since we are using
gh-pages
as the deployment branch.
If you are using a custom domain:
- Verify that you have the correct DNS records set up if you're using a custom domain. See GitHub pages documentation on configuring custom domains. Also, please be aware that it may take up to 24 hours for DNS changes to propagate through the internet.
触发 Travis CI 部署
Continuous integration (CI) services are typically used to perform routine tasks whenever new commits are checked in to source control. These tasks can be any combination of running unit tests and integration tests, automating builds, publishing packages to npm, and deploying changes to your website. All you need to do to automate the deployment of your website is to invoke the yarn deploy
script whenever your website is updated. The following section covers how to do just that using Travis CI, a popular continuous integration service provider.
- 在 https://github.com/settings/tokens 上生成一个新 personal access token。 新建令牌时,授予它
repo
权限,这样它就有所有需要的权限了。 - 用你的 GitHub 账户把 Travis CI 应用添加到你想要激活的仓库中。
- 打开你的 Travis CI 主界面。 URL 大概像
https://travisenci.com/USERNAME/REPO
,并导航到你的仓库的More options > Setting > Environment Variables
部分。 - 创建一个新环境变量,命名为
GH_TOKEN
,值为你刚刚生成的令牌。再创建GH_EMAIL
和GH_NAME
两个变量,对应你的邮箱和 GitHub 用户名。 - 在仓库根目录创建一个
.travis.yml
文件,包含下面的内容:
language: node_js
node_js:
- 18
branches:
only:
- main
cache:
yarn: true
script:
- git config --global user.name "${GH_NAME}"
- git config --global user.email "${GH_EMAIL}"
- echo "machine github.com login ${GH_NAME} password ${GH_TOKEN}" > ~/.netrc
- yarn install
- GIT_USER="${GH_NAME}" yarn deploy