Skip to content

Commit ec604b2

Browse files
Merge pull request #436 from laravel/non-vite-builds
Check for import.meta.env before using Vite environment variables
2 parents fa5b2c4 + 8d93e15 commit ec604b2

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

packages/react/vite.config.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
11
import { resolve } from "path";
2-
import { defineConfig, UserConfig } from "vite";
2+
import { defineConfig, PluginOption, UserConfig } from "vite";
33
import dts from "vite-plugin-dts";
44

5+
const handleEnvVariablesPlugin = (): PluginOption => {
6+
return {
7+
name: "handle-env-variables-plugin",
8+
generateBundle(options, bundle) {
9+
for (const fileName in bundle) {
10+
const file = bundle[fileName];
11+
12+
if (file.type === "chunk" && file.fileName.endsWith(".js")) {
13+
const transformedContent = file.code.replace(
14+
/import\.meta\.env\.VITE_([A-Z0-9_]+)/g,
15+
"(typeof import.meta.env !== 'undefined' ? import.meta.env.VITE_$1 : undefined)",
16+
);
17+
18+
file.code = transformedContent;
19+
}
20+
}
21+
},
22+
};
23+
};
24+
525
const config: UserConfig = (() => {
626
const common: Partial<UserConfig["build"]> = {
727
rollupOptions: {
@@ -40,6 +60,7 @@ const config: UserConfig = (() => {
4060
rollupTypes: true,
4161
include: ["src/**/*.ts"],
4262
}),
63+
handleEnvVariablesPlugin(),
4364
],
4465
define: {
4566
"import.meta.env.VITE_REVERB_APP_KEY":

packages/vue/vite.config.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
11
import { resolve } from "path";
2-
import { defineConfig, UserConfig } from "vite";
2+
import { defineConfig, PluginOption, UserConfig } from "vite";
33
import dts from "vite-plugin-dts";
44

5+
const handleEnvVariablesPlugin = (): PluginOption => {
6+
return {
7+
name: "handle-env-variables-plugin",
8+
generateBundle(options, bundle) {
9+
for (const fileName in bundle) {
10+
const file = bundle[fileName];
11+
12+
if (file.type === "chunk" && file.fileName.endsWith(".js")) {
13+
const transformedContent = file.code.replace(
14+
/import\.meta\.env\.VITE_([A-Z0-9_]+)/g,
15+
"(typeof import.meta.env !== 'undefined' ? import.meta.env.VITE_$1 : undefined)",
16+
);
17+
18+
file.code = transformedContent;
19+
}
20+
}
21+
},
22+
};
23+
};
24+
525
const config: UserConfig = (() => {
626
const common: Partial<UserConfig["build"]> = {
727
rollupOptions: {
@@ -40,6 +60,7 @@ const config: UserConfig = (() => {
4060
rollupTypes: true,
4161
include: ["src/**/*.ts"],
4262
}),
63+
handleEnvVariablesPlugin(),
4364
],
4465
define: {
4566
"import.meta.env.VITE_REVERB_APP_KEY":

0 commit comments

Comments
 (0)