- 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
- Expose Environment Variables to your templates using JavaScript Data Files.
- Opt-in to
git Last Modified
only in production - Only perform Eleventy Serverless plugin copy (via
copyEnabled
) in production - Use fewer image formats in the Image plugin to speed up local development
Eleventy 提供的环境变量 Jump to heading
Node.js 通过 process.env
变量对外暴露所有环境变量。
Eleventy 提供了 Eleventy 专用的环境变量,通常用于更复杂的使用场景。你可以根据自身需要在配置文件或数据文件(data files)中使用这些环境变量。
process.env.ELEVENTY_ROOT
Added in v1.0.0 the absolute path to the directory in which you’ve run the Eleventy command.process.env.ELEVENTY_SOURCE
Added in v1.0.0 is the method in which Eleventy has run, current eithercli
orscript
.process.env.ELEVENTY_SERVERLESS
Added in v1.0.0 is set totrue
(String) if Eleventy is running in serverless mode. If Eleventy is not running in serverless mode—due to Node forcing environment variables to be strings—this variable will not exist.process.env.ELEVENTY_RUN_MODE
Added in v2.0.0 is one ofbuild
,serve
, orwatch
.process.env.ELEVENTY_VERSION
Pre-release only: v3.0.0-alpha.6 the current version of Eleventy (e.g."3.0.0-alpha.5"
).