Eleventy(11ty) logo Eleventy
The possum is Eleventy’s mascot
Eleventy 中文文档
Menu
Eleventy 5.81s
Nuxt 14.77s

环境变量

Contents

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

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

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

利用 .env 文件 Jump to heading

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

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

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

Mac OS (或 Linux 等系统) Jump to heading

MY_ENVIRONMENT=production npx @11ty/eleventy

Windows cmd.exe Jump to heading

set MY_ENVIRONMENT=production & npx @11ty/eleventy

Windows Powershell (VS Code 默认使用的命令行工具) Jump to heading

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

通过 npm 脚本设置环境变量 Jump to heading

你可以在项目的 package.json 文件中通过设置 npm 脚本来使用上述命令。

Filename package.json
{
"scripts": {
"build:prod": "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: