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(shared): Preserve import.meta without requiring ES2020 target #5203

Closed
wants to merge 8 commits into from
Closed
Changes from 4 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
28 changes: 26 additions & 2 deletions packages/shared/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ export default defineConfig(overrideOptions => {
minify: false,
sourcemap: true,
dts: true,
target: 'es2020',
external: ['react', 'react-dom'],
esbuildPlugins: [WebWorkerMinifyPlugin as any],
esbuildPlugins: [WebWorkerMinifyPlugin as any, preserveImportMetaPlugin],
define: {
PACKAGE_NAME: `"${name}"`,
PACKAGE_VERSION: `"${version}"`,
Expand All @@ -49,3 +48,28 @@ export const WebWorkerMinifyPlugin: Plugin = {
});
},
};

/**
* Preserves import.meta functionality in ESM builds while maintaining ES5 compatibility.
* We originally used target: 'es2020' to handle this but it broke support for older browsers (e.g. iOS 12).
*/
const preserveImportMetaPlugin: Plugin = {
name: 'preserve-import-meta',
setup(build) {
build.onEnd(result => {
if (!result.outputFiles) return;

result.outputFiles.forEach(file => {
if (!file.path.endsWith('.mjs')) return;

const contents = file.contents;
const text = new TextDecoder().decode(contents);

// Remove esbuild's var import_meta = {} transformation and restore original import.meta references
const modified = text.replace(/var\s+import_meta\s*=\s*{};/g, '').replace(/import_meta/g, 'import.meta');
Copy link
Member Author

@wobsoriano wobsoriano Feb 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This restores the original import.meta references

Example built file:

Screenshot 2025-02-19 at 9 08 19 PM

without the plugin and ES2020 target, it gets transformed to:

var import_meta = {};

// ... other code
if (typeof import_meta !== "undefined" && import_meta.env && typeof import_meta.env[name] === "string") {
    return import_meta.env[name];
  }


file.contents = new TextEncoder().encode(modified);
});
});
},
};
Loading