Node 模拟

Parcel 包含多个模拟 Node.js API 的功能。这使得 npm 上的许多最初为 Node 编写的模块也可以在浏览器中运行。此外,许多浏览器模块还采用了基于 Node.js 的 API 来处理环境变量等内容。

¥Parcel includes several features that emulate the Node.js API. This allows many modules on npm that were originally written for Node to also work in the browser. In addition, many browser modules have also adopted Node.js-based APIs for things like environment variables.

环境变量

#

¥Environment Variables

Parcel 支持 JavaScript 中的内联环境变量。这可用于确定构建环境(例如开发、暂存、生产)、注入 API 密钥等。

¥Parcel supports inlining environment variables in JavaScript. This can be used to determine the build environment (e.g. development, staging, production), inject API keys, etc.

要访问环境变量,请从 process.env 对象中读取相应的属性。

¥To access an environment variable, read the corresponding property from the process.env object.

if (process.env.NODE_ENV === 'development') {
console.log('Happy developing!');
}

你还可以使用解构语法一次访问多个属性。

¥You can also use destructuring syntax to access multiple properties at once.

let {NODE_ENV, API_TOKEN} = process.env;

不支持以任何非静态方式(例如动态属性查找)访问 process.env

¥Accessing process.env in any non-static ways (e.g. dynamic property lookups) is not supported.

NODE_ENV

#

NODE_ENV 环境变量由 Parcel 根据模式自动设置。运行 parcel build 时,NODE_ENV 默认设置为 production,否则设置为 development。这可以通过自己设置 NODE_ENV 来覆盖(例如在你的 shell 中)。

¥The NODE_ENV environment variable is automatically set by Parcel depending on the mode. When running parcel build, NODE_ENV is set to production by default, otherwise it is set to development. This can be overridden by setting NODE_ENV yourself (e.g. in your shell).

.env 文件

#

¥.env files

Parcel 支持加载项目根目录中 .env 文件中定义的环境变量。这支持由换行符分隔的 NAME=value 对。以 # 开头的行被视为注释。详细信息请参见 dotenv

¥Parcel supports loading environment variables defined in .env files in your project root. This supports NAME=value pairs separated by newlines. Lines starting with # are treated as comments. See dotenv for more details.

.env:
APP_NAME=test
API_KEY=12345

除了 .env 之外,还可以创建特定于环境的覆盖,例如 .env.production.env.development。这些是基于 NODE_ENV 环境变量应用的(包括由 Parcel 自动设置的情况)。任何未在特定于环境的覆盖中设置的变量都会回退到基本 .env 文件中定义的值。

¥In addition to .env, environment-specific overrides such as .env.production and .env.development can also be created. These are applied based on the NODE_ENV environment variable (including when automatically set by Parcel). Any variables that are not set in environment-specific overrides fall back to the values defined in the base .env file.

.env.local 文件还支持环境变量的本地覆盖,但是,NODE_ENV=test 时不使用它,以便测试为每个人产生相同的结果。这也支持特定于环境的覆盖,例如 .env.production.local

¥The .env.local file is also supported for local overrides of environment variables, however, it is not used when NODE_ENV=test so that tests produce the same result for everyone. This is also supported for environment-specific overrides, such as .env.production.local.

Polyfilling 和排除内置节点模块

#

¥Polyfilling & Excluding Builtin Node Modules

当针对浏览器和你的代码(或更可能是依赖)导入内置 Node 模块(例如 cryptofsprocess)时,Parcel 将自动使用以下 polyfill 之一。如果没有可用的 polyfill,则将使用空模块。你还可以使用 aliases 来覆盖这些。

¥When targetting the browser and your code, or more likely a dependency, imports builtin Node modules such as crypto, fs or process, Parcel will automatically use one of the following polyfills. If no polyfill is available, then an empty module will be used instead. You can also use aliases to override these.

原生模块 npm 替换 原生模块 npm 替换
断言 assert 过程 process/browser.js
缓冲 buffer 庞尼代码 punycode
console console-browserify 请求参数 querystring-es3
常量 constants-browserify stream-browserify
加密货币 crypto-browserify 字符串解码器 string_decoder
domain-browser 系统 util/util.js
事件 events 定时器 timers-browserify
http stream-http 终端 tty-browserify
https https-browserify 网址 url
操作系统 os-browserify/browser.js 实用程序 util/util.js
路径 path-browserify 虚拟机 vm-browserify
兹库 browserify-zlib

调整内置节点全局变量

#

¥Shimming Builtin Node Globals

当针对浏览器时,Node 中可用的全局变量的用法将被替换,以免破坏为 Node 编写的代码:

¥When targetting the browser, usages of global variables that are available in Node are replaced to not break code written for Node:

内联 fs.readFileSync

#

¥Inlining fs.readFileSync

如果文件路径是静态可确定的并且位于项目根目录内,则对 fs.readFileSync 的调用将替换为文件的内容。

¥Calls to fs.readFileSync are replaced with the file's contents if the filepath is statically determinable and inside the project root.

__dirname__filename 变量可以在文件名参数中使用。可以使用通过 + 运算符和 path.join 函数进行的字符串连接。不支持其他函数、变量或动态计算。计算路径应始终是绝对路径,并且不依赖于当前工作目录。

¥The __dirname and __filename variables can be used in the filename argument. String concatenation via the + operator and the path.join function may be used. Other functions, variables, or dynamic computations are not supported. Computed paths should always be absolute, and not rely on the current working directory.

index.js:
import fs from "fs";
import path from "path";

const data = fs.readFileSync(path.join(__dirname, "data.json"), "utf8");
console.log(data);
data.json:
{
"foo": "bar"
}

禁用这些功能

#

¥Disabling These Features

可以通过在 package.json 中创建 @parcel/transformer-js 键来禁用 环境变量readFileSync 调用 的内联。

¥Inlining of environment variables and readFileSync calls can be disabled by creating a @parcel/transformer-js key in package.json.

package.json:
{
"name": "my-project",
"dependencies": {
...
},
"@parcel/transformer-js": {
"inlineFS": false,
"inlineEnvironment": false
}
}

inlineEnvironment 也可以是一个 glob 字符串数组,它允许你过滤允许的环境变量。这是确保安全性的好主意,因为 node_modules 中的第三方代码也可以读取环境变量。

¥inlineEnvironment can also be an array of glob strings, which allows you to filter the allowed environment variables. This is a good idea to ensure security, since third party code in node_modules can also read environment variables.

{
"name": "my-project",
"dependencies": {
...
},
"@parcel/transformer-js": {
"inlineEnvironment": ["SENTRY_*"]
}
}
Parcel 中文网 - 粤ICP备13048890号