Skip to navigation Skip to main content
Eleventy
Eleventy Documentation
Stable
3.0.0
Toggle Menu
Eleventy 1.93s
Gatsby 29.05s

环境变量

Contents

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

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

INFO:
Note that environment variables are only available in JavaScript files in your project, evaluated at build time. This includes your config file, JavaScript data files, JavaScript templates, etc. To use environment variables in other template languages, you can use a Javascript Data file.

设置你自己的环境变量

利用 .env 文件

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

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

通过命令行设置环境变量

macOS or Linux (et al)

MY_ENVIRONMENT=production npx @11ty/eleventy

Windows cmd.exe

set MY_ENVIRONMENT=production & npx @11ty/eleventy

Windows Powershell (default in VS Code)

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

Cross Platform npm scripts

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"
}
}

用法示例

Eleventy 提供的环境变量

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

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

  • process.env.ELEVENTY_ROOT the absolute path to the directory in which you’ve run the Eleventy command.
  • process.env.ELEVENTY_SOURCE is the method in which Eleventy has run, current either cli or script.
  • process.env.ELEVENTY_RUN_MODE Added in v2.0.0 is one of build, serve, or watch.
  • process.env.ELEVENTY_VERSION Added in v3.0.0 the current version of Eleventy (e.g. "3.0.0-alpha.5").

Disable Colors

Node.js supports a NODE_DISABLE_COLORS environment variable that will disable colorized text in the terminal output.

NODE_DISABLE_COLORS=1 npx @11ty/eleventy
$env:NODE_DISABLE_COLORS="1"; npx @11ty/eleventy

Or with the older cmd.exe:

set NODE_DISABLE_COLORS=1 & npx @11ty/eleventy
npx cross-env NODE_DISABLE_COLORS=1 npx @11ty/eleventy

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


Other pages in Using Data: