Skip to content

Commit

Permalink
docs: EnvironmentPlugin docs (#6266)
Browse files Browse the repository at this point in the history
* docs: EnvironmentPlugin docs zh

* docs: EnvironmentPlugin en docs

* docs: add mysecretkey
  • Loading branch information
SyMind authored Apr 17, 2024
1 parent c11d422 commit e9556a3
Show file tree
Hide file tree
Showing 4 changed files with 275 additions and 0 deletions.
135 changes: 135 additions & 0 deletions website/docs/en/plugins/webpack/environment-plugin.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { ApiMeta } from '../../../../components/ApiMeta.tsx';
import WebpackLicense from '../../../../components/webpack-license';

<WebpackLicense from="https://webpack.js.org/plugins/environment-plugin/" />

# EnvironmentPlugin

<ApiMeta addedVersion={'0.2.5'} />

The `EnvironmentPlugin` is shorthand for using the [`DefinePlugin`](/plugins/webpack/define-plugin) on [`process.env`](https://nodejs.org/api/process.html#process_process_env) keys.

## Options

- **Type:** `string[] | Record<string, string>`

## Examples

### Basic Use Case

The `EnvironmentPlugin` accepts either an array of keys or an object mapping its keys to their default values.

```js
new rspack.EnvironmentPlugin(['NODE_ENV', 'DEBUG']);
```

This is equivalent to the following `DefinePlugin` application:

```js
new rspack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
});
```

:::tip
Not specifying the environment variable raises an "`EnvironmentPlugin` - `${key}` environment variable is undefined" error.
:::

### Usage with default values

Alternatively, the `EnvironmentPlugin` supports an object, which maps keys to their default values. The default value for a key is taken if the key is undefined in `process.env`.

```js
new rspack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false,
});
```

:::warning
Variables coming from `process.env` are always strings.
:::

:::tip
Unlike [`DefinePlugin`](/plugins/webpack/define-plugin), default values are applied to `JSON.stringify` by the `EnvironmentPlugin`.
:::

:::tip
Default values of `null` and `undefined` behave differently. Use `undefined` for variables that must be provided during bundling, or `null` if they are optional.
:::

:::warning
If an environment variable is not found during bundling and no default value was provided, Rspack will throw an error instead of a warning.
:::

Let's investigate the result when running the previous `EnvironmentPlugin` configuration on a test file `entry.js`:

```js
if (process.env.NODE_ENV === 'production') {
console.log('Welcome to production');
}
if (process.env.DEBUG) {
console.log('Debugging output');
}
```

When executing `NODE_ENV=production` Rspack in the terminal to build, `entry.js` becomes this:

```js
if ('production' === 'production') {
// <-- 'production' from NODE_ENV is taken
console.log('Welcome to production');
}
if (false) {
// <-- default value is taken
console.log('Debugging output');
}
```

Running `DEBUG=false` Rspack yields:

```js
if ('development' === 'production') {
// <-- default value is taken
console.log('Welcome to production');
}
if ('false') {
// <-- 'false' from DEBUG is taken
console.log('Debugging output');
}
```

### Git Version

The following `EnvironmentPlugin` configuration provides `process.env.GIT_VERSION` (such as "v5.4.0-2-g25139f57f") and `process.env.GIT_AUTHOR_DATE` (such as "2020-11-04T12:25:16+01:00") corresponding to the last Git commit of the repository:

```js
const child_process = require('child_process');
function git(command) {
return child_process.execSync(`git ${command}`, { encoding: 'utf8' }).trim();
}

new rspack.EnvironmentPlugin({
GIT_VERSION: git('describe --always'),
GIT_AUTHOR_DATE: git('log -1 --format=%aI'),
});
```

### DotenvPlugin

The third-party [`DotenvPlugin`](https://github.com/mrsteele/dotenv-webpack) (`dotenv-webpack`) allows you to expose (a subset of) [dotenv variables](https://www.npmjs.com/package/dotenv):

```js
// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey
```

```js
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
});
```
135 changes: 135 additions & 0 deletions website/docs/zh/plugins/webpack/environment-plugin.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { ApiMeta } from '../../../../components/ApiMeta.tsx';
import WebpackLicense from '../../../../components/webpack-license';

<WebpackLicense from="https://webpack.js.org/plugins/environment-plugin/" />

# EnvironmentPlugin

<ApiMeta addedVersion={'0.2.5'} />

`EnvironmentPlugin` 简化了使用 [`DefinePlugin`](/plugins/webpack/define-plugin) 设置 `process.env` 变量的过程。

## 选项

- **类型:** `string[] | Record<string, string>`

## 示例

### 基本使用

`EnvironmentPlugin` 接受一个包含键的数组或者一个键到其默认值的对象映射。

```js
new rspack.EnvironmentPlugin(['NODE_ENV', 'DEBUG']);
```

这等同于以下 `DefinePlugin` 的使用方式:

```js
new rspack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
});
```

:::tip 提示
如果没有指定环境变量,将会抛出“`EnvironmentPlugin` - `${key}` environment variable is undefined”错误。
:::

### 带有默认值的使用

作为替代,`EnvironmentPlugin` 支持一个映射键到其默认值的对象。如果在 `process.env` 中某个键未定义,则采用该键的默认值。

```js
new rspack.EnvironmentPlugin({
NODE_ENV: 'development', // 除非定义了 process.env.NODE_ENV,否则使用 'development'
DEBUG: false,
});
```

:::warning 警告
`process.env` 来的变量总是字符串。
:::

:::tip 提示
[`DefinePlugin`](/plugins/webpack/define-plugin) 不同,`EnvironmentPlugin` 会对默认值使用 `JSON.stringify`
:::

:::tip 提示
`null``undefined` 的默认值有不同的表现。如果变量在打包时必须提供,则使用 `undefined`;如果它们是可选的,则使用 `null`
:::

:::warning 警告
如果在打包过程中找不到环境变量,并且没有提供默认值,Rspack 将抛出错误而不是警告。
:::

让我们来看看在 test 文件 `entry.js` 上运行前述 `EnvironmentPlugin` 配置的结果:

```js
if (process.env.NODE_ENV === 'production') {
console.log('Welcome to production');
}
if (process.env.DEBUG) {
console.log('Debugging output');
}
```

当在终端执行 `NODE_ENV=production` Rspack 构建时,`entry.js` 变成了这样:

```js
if ('production' === 'production') {
// <-- 取自 NODE_ENV 的 'production'
console.log('Welcome to production');
}
if (false) {
// <-- 取默认值
console.log('Debugging output');
}
```

运行 `DEBUG=false` Rspack 产生:

```js
if ('development' === 'production') {
// <-- 取默认值
console.log('Welcome to production');
}
if ('false') {
// <-- 取自 DEBUG 的 'false'
console.log('Debugging output');
}
```

### Git 版本

下面的 `EnvironmentPlugin` 配置提供了对应于仓库最后一次 Git 提交的 `process.env.GIT_VERSION`(例如 "v5.4.0-2-g25139f57f")和 `process.env.GIT_AUTHOR_DATE`(例如 "2020-11-04T12:25:16+01:00"):

```js
const child_process = require('child_process');
function git(command) {
return child_process.execSync(`git ${command}`, { encoding: 'utf8' }).trim();
}

new rspack.EnvironmentPlugin({
GIT_VERSION: git('describe --always'),
GIT_AUTHOR_DATE: git('log -1 --format=%aI'),
});
```

### DotenvPlugin

第三方 [`DotenvPlugin`](https://github.com/mrsteele/dotenv-webpack)`dotenv-webpack`)允许你暴露一部分 [dotenv 变量](https://www.npmjs.com/package/dotenv)

```js
// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey
```

```js
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
});
```
1 change: 1 addition & 0 deletions website/project-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,4 @@ modulegeneratorcssautoexportsconvention
modulegeneratorcssautoexportsonly
modulegeneratorcssautolocalidentname
cssextractrspackplugin
mysecretkey
4 changes: 4 additions & 0 deletions website/rspress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ function getSidebarConfig(lang: 'zh' | 'en'): Sidebar {
text: 'ModuleFederationPluginV1',
link: getLink('/plugins/webpack/module-federation-plugin-v1'),
},
{
text: 'EnvironmentPlugin',
link: getLink('/plugins/webpack/environment-plugin'),
},
],
},
{
Expand Down

0 comments on commit e9556a3

Please sign in to comment.