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

fix: workaround import.meta.env error in vitest #103

Draft
wants to merge 1 commit into
base: refactor-reference-sync-import
Choose a base branch
from
Draft
Changes from all commits
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
17 changes: 17 additions & 0 deletions examples/react-server/src/features/test/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import MagicString from "magic-string";
import type { Plugin } from "vite";
import { $__global } from "../../global";

Expand All @@ -6,6 +7,7 @@ export function vitePluginTestReactServerStream(): Plugin {

return {
name: vitePluginTestReactServerStream.name,
enforce: "pre",
resolveId(source, _importer, _options) {
if (source.startsWith(prefix)) {
return "\0" + source;
Expand Down Expand Up @@ -37,6 +39,21 @@ export function vitePluginTestReactServerStream(): Plugin {
}
return;
},
transform(code) {
// Workaround module runner `import.meta.env` usage inside Vitest
// Error: [module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.DEV" instead.
if (code.includes("import.meta.env.DEV")) {
const output = new MagicString(code);
for (const match of code.matchAll(/\bimport\.meta\.env\.DEV\b/dg)) {
const [start, end] = match.indices![0];
output.update(start, end, "true");
}
if (output.hasChanged()) {
return { code: output.toString(), map: output.generateMap() };
}
}
return;
},
};
}

Expand Down