Skip to navigation Skip to main content
11ty Logo Sustainability Fundraising
Eleventy
Eleventy Documentation
Stable
2.0.1
Canary
3.0.0-alpha.16
Toggle Menu
Eleventy 5.81s
Remix 40.14s

环境变量

Contents

你可以为项目设置自己专用的环境变量。这些环境变量可以通过 Node.js 的 process.env 属性 在代码中获取。

环境变量通常用于设置部署时的上下文(context)以及 API 的私钥,也是用于 开启 DEBUG 模式 的方法。

INFO:
Note that Eleventy exposes environment variables only to JavaScript files that are evaluated during the build time. This includes the config file and all JavaScript files required from there, JavaScript data files, etc. Environment variables are not available in the templates. You need to expose them yourself. For example, using a Global Data file.

设置你自己的环境变量 Jump to heading

利用 .env 文件 Jump to heading

对于私钥和其他敏感信息,你可以创建一个 .env 文件并通过 dotenv 软件包 来设置这些变量。

WARNING:
请确保将 .env 文件名添加到 .gitignore 文件中。并且 千万不要.env 文件提交到你的代码仓库中!!

通过命令行设置环境变量 Jump to heading

macOS or Linux (et al) Jump to heading

MY_ENVIRONMENT=production npx @11ty/eleventy

Windows cmd.exe Jump to heading

set MY_ENVIRONMENT=production & npx @11ty/eleventy

Windows Powershell (default in VS Code) Jump to heading

$env:MY_ENVIRONMENT="production"; npx @11ty/eleventy

Cross Platform npm scripts Jump to heading

Use the cross-env package to compatibly set your environment variables cross-platform.

npm install cross-env
Filename package.json
{
"scripts": {
"build:prod": "cross-env MY_ENVIRONMENT=production npx @11ty/eleventy"
}
}

用法示例 Jump to heading

Eleventy 提供的环境变量 Jump to heading

Node.js 通过 process.env 变量对外暴露所有环境变量

Eleventy 提供了 Eleventy 专用的环境变量,通常用于更复杂的使用场景。你可以根据自身需要在配置文件或数据文件(data files)中使用这些环境变量。


Other pages in Using Data: