部署
要为生产环境构建网站的静态文件,请运行:
- npm
- Yarn
- pnpm
npm run build
yarn build
pnpm run build
Once it finishes, the static files will be generated within the build
directory.
The only responsibility of Docusaurus is to build your site and emit static files in build
.
现在,该由你来决定怎么托管这些静态文件了。
You can deploy your site to static site hosting services such as Vercel, GitHub Pages, Netlify, Render, and Surge.
Docusaurus 网站是静态渲染的,而且一般不需要 JavaScript 也能运行!
Configuration
The following parameters are required in docusaurus.config.js
to optimize routing and serve files from the correct location:
参数 | 描述 |
---|---|
url | 站点 URL。 For a site deployed at https://my-org.com/my-project/ , url is https://my-org.com/ . |
baseUrl | 站点的 base URL,带有末尾斜杠。 For a site deployed at https://my-org.com/my-project/ , baseUrl is /my-project/ . |
Testing your Build Locally
在部署到生产环境前,事先进行本地测试尤为重要。 Docusaurus provides a docusaurus serve
command for that:
- npm
- Yarn
- pnpm
npm run serve
yarn serve
pnpm run serve
By default, this will load your site at http://localhost:3000/
.
Trailing slash configuration
Docusaurus has a trailingSlash
config to allow customizing URLs/links and emitted filename patterns.
你一般不需要修改默认值。 Unfortunately, each static hosting provider has a different behavior, and deploying the exact same site to various hosts can lead to distinct results. 根据你的托管商的不同,你可能需要修改此配置。
Use slorber/trailing-slash-guide to understand better the behavior of your host and configure trailingSlash
appropriately.
Using environment variables
把可能敏感的信息放在环境变量中的做法很常见。 However, in a typical Docusaurus website, the docusaurus.config.js
file is the only interface to the Node.js environment (see our architecture overview), while everything else (MDX pages, React components, etc.) are client side and do not have direct access to the process
global variable. In this case, you can consider using customFields
to pass environment variables to the client side.
// 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>Contact us through {customFields.teamEmail}!</div>;
}
Choosing a hosting provider
有几种常见的托管选择:
- 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 部署的工作流程设置起来可能很麻烦。 (Evidence: see the length of Deploying to 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 页面不能做部署预览,至少方法非常复杂。 每个仓库只能和一个站点部署相关联。 另一方面,你还是可以控制哪些人有站点部署的写权限。
不存在通用方案。 你需要权衡你的需求和资源 ,然后再做决定。
Self-Hosting
Docusaurus can be self-hosted using docusaurus serve
. Change port using --port
and --host
to change 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. 不过你可以在其他网站上写一篇关于某个服务提供商的文章(比如你的博客,或者提供商官网),然后让我们添加一个这篇文章的链接。
Deploying to 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
// ...
};
Then, create your site with Netlify.
在设立站点时,指定如下构建指令和目录:
- build command:
npm run build
- publish directory:
build
If you did not configure these build options, you may still go to "Site settings" -> "Build & deploy" after your site is created.
Once properly configured with the above options, your site should deploy and automatically redeploy upon merging to your deploy branch, which defaults to main
.
Some Docusaurus sites put the docs
folder outside of website
(most likely former Docusaurus v1 sites):
repo # git 根目录
├── docs # MD 文件
└── website # Docusaurus 根目录
If you decide to use the website
folder as Netlify's base directory, Netlify will not trigger builds when you update the docs
folder, and you need to configure a custom ignore
command:
[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.
Be very careful: the Disable asset optimization
global checkbox is broken and does not really disable the Pretty URLs
setting in practice. Please make sure to uncheck it independently.
If you want to keep the Pretty Urls
Netlify setting on, adjust the trailingSlash
Docusaurus config appropriately.
Refer to slorber/trailing-slash-guide for more information.
Deploying to Vercel
Deploying your Docusaurus project to Vercel will provide you with various benefits in the areas of performance and ease of use.
To deploy your Docusaurus project with a Vercel for Git Integration, make sure it has been pushed to a Git repository.
Import the project into Vercel using the Import Flow. During the import, you will find all relevant options preconfigured for you; however, you can choose to change any of these options.
After your project has been imported, all subsequent pushes to branches will generate Preview Deployments, and all changes made to the Production Branch (usually "main" or "master") will result in a Production Deployment.
Deploying to GitHub Pages
Docusaurus provides an easy way to publish to GitHub Pages, which comes free with every GitHub repository.
Overview
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. In the following tutorial, they will be referred to as "source" and "deployment", respectively.
每个 GitHub 仓库都关联有一个 GitHub Pages 服务。 If the deployment repository is called my-org/my-project
(where my-org
is the organization name or username), the deployed site will appear at 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/
.
In case you want to use your custom domain for GitHub Pages, create a CNAME
file in the static
directory. Anything within the static
directory will be copied to the root of the build
directory for deployment. When using a custom domain, you should be able to move back from baseUrl: '/projectName/'
to baseUrl: '/'
, and also set your url
to your custom domain.
You may refer to GitHub Pages' documentation User, Organization, and Project Pages for more details.
GitHub Pages picks up deploy-ready files (the output from docusaurus build
) from the default branch (master
/ main
, usually) or the gh-pages
branch, and either from the root or the /docs
folder. You can configure that through Settings > Pages
in your repository. 这个分支会被称作「部署分支」。
We provide a docusaurus deploy
command that helps you deploy your site from the source branch to the deployment branch in one command: clone, build, and commit.
docusaurus.config.js
settings
First, modify your docusaurus.config.js
and add the following params:
参数 | 描述 |
---|---|
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 网址链接添加末尾斜杠。 It is recommended to set a trailingSlash
config (true
or false
, not undefined
).
示例:
export default {
// ...
url: 'https://endiliey.github.io', // Your website URL
baseUrl: '/',
projectName: 'endiliey.github.io',
organizationName: 'endiliey',
trailingSlash: false,
// ...
};
By default, GitHub Pages runs published files through Jekyll. Since Jekyll will discard any files that begin with _
, it is recommended that you disable Jekyll by adding an empty file named .nojekyll
file to your static
directory.
Environment settings
参数 | 描述 |
---|---|
USE_SSH | Set to true to use SSH instead of the default HTTPS for the connection to the GitHub repo. If the source repo URL is an SSH URL (e.g. [email protected]:facebook/docusaurus.git ), USE_SSH is inferred to be true . |
GIT_USER | The username for a GitHub account that has push access to the deployment repo. 对于你自己的仓库,这一般会是你自己的 GitHub 用户名。 不使用 SSH 时必填,使用 SSH 时则会被忽略。 |
GIT_PASS | Personal access token of the git user (specified by GIT_USER ), to facilitate non-interactive deployment (e.g. continuous deployment) |
CURRENT_BRANCH | 源分支。 Usually, the branch will be main or master , but it could be any branch except for gh-pages . If nothing is set for this variable, then the current branch from which docusaurus deploy is invoked will be used. |
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 企业网站的端口。 |
Deploy
最后,要把你的网站部署到 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'
Beginning in August 2021, GitHub requires every command-line sign-in to use the personal access token instead of the password. 当 GitHub 提示你输入密码时,请输入个人访问令牌。 See the GitHub documentation for more information.
Alternatively, you can use SSH (USE_SSH=true
) to log in.
Triggering deployment with GitHub Actions
GitHub Actions allow you to automate, customize, and execute your software development workflows right in your repository.
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.
我们的目标是:
- When a new pull request is made to
main
, there's an action that ensures the site builds successfully, without actually deploying. This job will be calledtest-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. This job will be calleddeploy
.
下面是两种通过 GitHub Actions 部署文档的方法。 Based on the location of your deployment branch (gh-pages
), choose the relevant tab below:
- Source repo and deployment repo are the same repository.
- The deployment repo is a remote repository, different from the source. Instructions for this scenario assume publishing source is the
gh-pages
branch.
- Same
- Remote
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 files
添加这两个工作流文件:
这些文件假设你使用的是 Yarn。 If you use npm, change cache: yarn
, yarn install --frozen-lockfile
, yarn build
to cache: npm
, npm ci
, npm run build
accordingly.
If your Docusaurus project is not at the root of your repo, you may need to configure a default working directory, and adjust the paths accordingly.
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