- Stable
3.0.0- Canary
3.0.1-alpha.4
Toggle Menu
Eleventy
5.81sRemix
40.14s环境变量
Contents
- 设置你自己的环境变量
- 利用 .env 文件
- 通过命令行设置环境变量
- 用法示例
- Eleventy 提供的环境变量
- Disable Colors
你可以为项目设置自己专用的环境变量。这些环境变量可以通过 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 文件
- 通过命令行设置环境变量
- 用法示例
- Eleventy 提供的环境变量
- Disable Colors
设置你自己的环境变量
利用 .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"
}
}
用法示例
- Expose Environment Variables to your templates using JavaScript Data Files.
- Opt-in to
git Last Modifiedonly in production - Use fewer image formats in the Image plugin to speed up local development
Eleventy 提供的环境变量
Node.js 通过 process.env 变量对外暴露所有环境变量。
Eleventy 提供了 Eleventy 专用的环境变量,通常用于更复杂的使用场景。你可以根据自身需要在配置文件或数据文件(data files)中使用这些环境变量。
process.env.ELEVENTY_ROOTthe absolute path to the directory in which you’ve run the Eleventy command.process.env.ELEVENTY_SOURCEis the method in which Eleventy has run, current eithercliorscript.process.env.ELEVENTY_RUN_MODEAdded in v2.0.0 is one ofbuild,serve, orwatch.process.env.ELEVENTY_VERSIONAdded 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.
