Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

环境变量(如 API 密钥和数据库凭据)可以添加到 .env 文件中,并且它们将提供给你的应用。

¥Environment variables — like API keys and database credentials — can be added to a .env file, and they will be made available to your application.

你还可以使用 .env.local.env.[mode] 文件 - 有关更多信息,请参阅 Vite 文档。确保将任何包含敏感信息的文件添加到你的 .gitignore 文件中!

¥[!NOTE] You can also use .env.local or .env.[mode] files — see the Vite documentation for more information. Make sure you add any files containing sensitive information to your .gitignore file!

process.env 中的环境变量也可通过 $env/static/private 获得。

¥Environment variables in process.env are also available via $env/static/private.

在这个练习中,我们想使用环境变量允许用户在知道正确密码的情况下进入网站。

¥In this exercise, we want to allow the user to enter the website if they know the correct passphrase, using an environment variable.

首先,在 .env 中添加一个新的环境变量:

¥First, in .env, add a new environment variable:

PASSPHRASE="open sesame"

打开 src/routes/+page.server.js。从 $env/static/private 导入 PASSPHRASE 并在 表单操作 中使用它:

¥Open src/routes/+page.server.js. Import PASSPHRASE from $env/static/private and use it inside the form action:

src/routes/+page.server
import { redirect, fail } from '@sveltejs/kit';
import { PASSPHRASE } from '$env/static/private';

export function load({ cookies }) {
	if (cookies.get('allowed')) {
		redirect(307, '/welcome');
	}
}

export const actions = {
	default: async ({ request, cookies }) => {
		const data = await request.formData();

		if (data.get('passphrase') === PASSPHRASE) {
			cookies.set('allowed', 'true', {
				path: '/'
			});

			redirect(303, '/welcome');
		}

		return fail(403, {
			incorrect: true
		});
	}
};

现在任何知道正确密码的人都可以访问该网站。

¥The website is now accessible to anyone who knows the correct passphrase.

保密(Keeping secrets)

¥Keeping secrets

重要的是,敏感数据不会意外地被发送到浏览器,在那里很容易被黑客和恶棍窃取。

¥It’s important that sensitive data doesn’t accidentally end up being sent to the browser, where it could easily be stolen by hackers and scoundrels.

SvelteKit 可以轻松防止这种情况发生。请注意,如果我们尝试将 PASSPHRASE 导入 src/routes/+page.svelte,会发生什么:

¥SvelteKit makes it easy to prevent this from happening. Notice what happens if we try to import PASSPHRASE into src/routes/+page.svelte:

src/routes/+page
<script>
	import { PASSPHRASE } from '$env/static/private';
	let { form } = $props();
</script>
<script lang="ts">
	import { PASSPHRASE } from '$env/static/private';
	let { form } = $props();
</script>

弹出错误覆盖,告诉我们无法将 $env/static/private 导入客户端代码。它只能导入到服务器模块中:

¥An error overlay pops up, telling us that $env/static/private cannot be imported into client-side code. It can only be imported into server modules:

  • +page.server.js

  • +layout.server.js

  • +server.js

  • 任何以 .server.js 结尾的模块

    ¥any modules ending with .server.js

  • src/lib/server 内的任何模块

    ¥any modules inside src/lib/server

反过来,这些模块只能由其他服务器模块导入。

¥In turn, these modules can only be imported by other server modules.

静态与动态(Static vs dynamic)

¥Static vs dynamic

$env/static/private 中的 static 表示这些值在构建时已知,并且可以静态替换。这可以实现有用的优化:

¥The static in $env/static/private indicates that these values are known at build time, and can be statically replaced. This enables useful optimisations:

import { FEATURE_FLAG_X } from '$env/static/private';

if (FEATURE_FLAG_X === 'enabled') {
	// code in here will be removed from the build output
	// if FEATURE_FLAG_X is not enabled
}

在某些情况下,你可能需要引用动态的环境变量 — 换句话说,在我们运行应用之前是不知道的。我们将在下一个练习中介绍这种情况。

¥In some cases you might need to refer to environment variables that are dynamic — in other words, not known until we run the app. We’ll cover this case in the next exercise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
	let { form } = $props();
</script>
 
<form method="POST">
	<label>
		enter the passphrase
		<input name="passphrase" autocomplete="off" />
	</label>
</form>
 
{#if form?.incorrect}
	<p class="error">wrong passphrase!</p>
{/if}
 
<style>
	.error {
		color: red;
	}
</style>