Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add vite environment variables migrate guide #3321

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions website/docs/en/guide/migration/vite.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,24 @@ Notes:

- The above table does not cover all configurations of Vue CLI, feel free to add more.

## Environment Variables

Vite injects environment variables starting with `VITE_` into the client code by default, while Rsbuild injects environment variables starting with `PUBLIC_` by default (see [public variables](/guide/advanced/env-vars#public-variables)).

To be compatible with Vite's behavior, you can manually call Rsbuild's [loadEnv](/api/javascript-api/core#loadenv) method to read environment variables starting with `REACT_APP_`, and inject them into the client code through the [source.define](/config/source/define) config.
chenjiahan marked this conversation as resolved.
Show resolved Hide resolved

```ts title="rsbuild.config.ts"
import { defineConfig, loadEnv } from '@rsbuild/core';

const { publicVars } = loadEnv({ prefixes: ['VITE_'] });

export default defineConfig({
source: {
define: publicVars,
},
});
```

## Glob Import

Vite provides `import.meta.glob()` for importing multiple modules.
Expand Down
18 changes: 18 additions & 0 deletions website/docs/zh/guide/migration/vite.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,24 @@ Rsbuild 会在构建时自动注入 `<script>` 标签到生成的 HTML 文件中

- 上述表格尚未覆盖到 Vite 的所有配置,欢迎补充。

## 环境变量

Vite 默认会将 `VITE_` 开头的环境变量注入到 client 代码中,而 Rsbuild 默认会注入 `PUBLIC_` 开头的环境变量(参考 [public 变量](/guide/advanced/env-vars#public-变量))。

为了兼容 Vite 的行为,你可以手动调用 Rsbuild 提供的 [loadEnv](/api/javascript-api/core#loadenv) 方法来读取 `REACT_APP_` 开头的环境变量,并通过 [source.define](/config/source/define) 配置项注入到 client 代码中。
chenjiahan marked this conversation as resolved.
Show resolved Hide resolved

```ts title="rsbuild.config.ts"
import { defineConfig, loadEnv } from '@rsbuild/core';

const { publicVars } = loadEnv({ prefixes: ['VITE_'] });

export default defineConfig({
source: {
define: publicVars,
},
});
```

## Glob Import

Vite 提供了 `import.meta.glob()` 来批量导入模块。
Expand Down