将你的 Astro 网站部署到 GitLab Pages
你可以使用 GitLab Pages 为你的 GitLab 项目、群组或用户帐户托管 Astro 网站。
如何部署
标题为“如何部署”的部分你可以通过使用 GitLab CI/CD 自动构建和部署你的网站,将 Astro 网站部署到 GitLab Pages。为此,你的源代码必须托管在 GitLab 上,并且你需要对你的 Astro 项目进行以下更改
-
在
astro.config.mjs
中设置site
和base
选项。astro.config.mjs import { defineConfig } from 'astro/config';export default defineConfig({site: 'https://<username>.gitlab.io',base: '/<my-repo>',outDir: 'public',publicDir: 'static',});site
site
的值必须是以下之一- 基于你的用户名的 URL:
https://<username>.gitlab.io
- 基于你的群组名的 URL:
https://<groupname>.gitlab.io
- 如果你已在 GitLab 项目设置中配置了自定义域名:
https://example.com
对于 GitLab 自托管实例,请将
gitlab.io
替换为你的实例的 Pages 域名。base
可能需要为
base
设置一个值,以便 Astro 将你的仓库名称(例如/my-repo
)视为网站的根目录。如果你的页面是从根文件夹提供服务的,则不要设置
base
参数。base
的值应该是你的仓库名称,以正斜杠开头,例如/my-blog
。这样 Astro 就会明白你的网站根目录是/my-repo
,而不是默认的/
。 - 基于你的用户名的 URL:
-
将
public/
目录重命名为static/
。 -
在
astro.config.mjs
中设置outDir: 'public'
。此设置会指示 Astro 将静态构建输出放在名为public
的文件夹中,这是 GitLab Pages 要求用于暴露文件的文件夹。如果你在 Astro 项目中使用
public/
目录作为静态文件的来源,请将其重命名,并在astro.config.mjs
中使用该新文件夹名称作为publicDir
的值。例如,当
public/
目录重命名为static/
时,以下是正确的astro.config.mjs
设置astro.config.mjs import { defineConfig } from 'astro/config';export default defineConfig({outDir: 'public',publicDir: 'static',}); -
在
.gitignore
中更改构建输出。在我们的示例中,我们需要将dist/
更改为public/
.gitignore # build outputdist/public/ -
在项目的根目录中创建一个名为
.gitlab-ci.yml
的文件,内容如下。当你对内容进行更改时,这将构建和部署你的网站.gitlab-ci.yml pages:# The Docker image that will be used to build your appimage: node:ltsbefore_script:- npm ciscript:# Specify the steps involved to build your app here- npm run buildartifacts:paths:# The folder that contains the built files to be published.# This must be called "public".- publiconly:# Trigger a new build and deploy only when there is a push to the# branch(es) below- main -
提交你的更改并将其推送到 GitLab。
-
在 GitLab 上,转到你仓库的 Deploy 菜单并选择 Pages。在这里,你将看到你的 GitLab Pages 网站的完整 URL。为了确保你使用的是
https://username.gitlab.io/my-repo
格式的 URL,请在此页面上取消选中 Use unique domain 设置。
你的网站现在应该已经发布了!当你将更改推送到你的 Astro 项目仓库时,GitLab CI/CD 流水线将自动为你部署它们。