astro v6一个环境变量的break change 后端谨慎使用import.meta.env

astro v6一个环境变量的break change 后端谨慎使用import.meta.env
astro v6一个环境变量的break change 后端谨慎使用import.meta.env

之前升级v6没注意这个,结果发现数据库密码内联到了dist里,非常的诧异。结果发现是v6改了行为:

Docs

Changed: import.meta.env values are always inlined - Upgrade to Astro v6

In Astro 5.13, the experimental.staticImportMetaEnv flag was introduced to update the behavior when accessing import.meta.env directly to align with Vite’s handling of environment variables and ensures that import.meta.env values are always inlined....

In Astro 5.13, the experimental.staticImportMetaEnv flag was introduced to update the behavior when accessing import.meta.env directly to align with Vite’s handling of environment variables and ensures that import.meta.env values are always inlined.

In Astro 5.x, non-public environment variables were replaced by a reference to process.env. Additionally, Astro could also convert the value type of your environment variables used through import.meta.env, which could prevent access to some values such as the strings “true” (which was converted to a boolean value), and “1” (which was converted to a number).

Astro 6 removes this experimental flag and makes this the new default behavior in Astro: import.meta.env values are always inlined and never coerced.

也就是之前5.x,非公开变量(不是PUBLIC_开头的),你用import.meta.env使用他会变成process.env,这个行为很符合直觉,后端用的变量应该在运行时动态取,但是这样的话有点污染import.meta.env本身,v6改成了全部都走内联。

也就是
假设你在代码里写了:

const db = drizzle(import.meta.env.DATABASE_URL);

那么在build时提供了系统环境变量或者.env的时候,且值是 mysql://user:password@localhost:3306/db,它最终的dist会变成(也就是直接inline替换了):

const db = drizzle("mysql://user:password@localhost:3306/db");

但是如果你改成用process.env,Astro会处理它自己的import.meta.env,但不会帮你把.env自动变成系统环境变量(也就是不做任何处理的话,process.env无法获取.env定义的内容)。

生产环境用Docker之类的问题不大,本来就应该通过环境变量的方式注入到容器里;本地dev时最简单的做法就是手动用dotenv,例如直接写到astro.config.mjs里:

// @ts-check
import { defineConfig } from "astro/config";
import tailwindcss from "@tailwindcss/vite";

import react from "@astrojs/react";

import node from "@astrojs/node";
import "dotenv/config"; // <- 添加这一行

// https://astro.build/config
export default defineConfig({
  vite: {
    plugins: [tailwindcss()],
  },

  integrations: [react()],

  adapter: node({
    mode: "standalone",
  }),
});

升级v6并且之前使用import.meta.env引入后端用的变量的建议看看,就是怕密码随着dist漏出去。

1 个帖子 - 1 位参与者

阅读完整话题

来源: LinuxDo 最新话题查看原文