PlasmoHQ / docs

📘 Documentation site
https://docs.plasmo.com
10 stars 48 forks source link

A process.env variable to indicate a bundle being built for conditional imports? #100

Closed xiata closed 8 months ago

xiata commented 8 months ago

Is there an environment variable that indicate what bundle is being built? Something akin to process.env.PLASMO_BUNDLE containing a value like background or content? Honestly I only care to know during build time if something is a background bundle because I'd like to be able to conditionally change imports. E.g.

const sentry = process.env.PLASMO_BUILD === "background" 
  ? await import("~background/lib/sentry") 
  : await import("~contents/lib/sentry")

Or if implemented via import assertions, stage 3 where you would replace the import with null if the bundle type did not match the bundle being built

import sentryBG from "~background/lib/sentry" with { bundle: "background" }
import sentryContent from "~contents/lib/sentry" with { bundle: "content" }

const sentry = sentryBG ?? sentryContent
sentry.captureException(new Error("Wat"))

Right now the only check I can think of to determine if it's a background bundle is "serviceWorker" in globalThis but this is a runtime check, not a build check, so it cannot be tree shaken causing bundles to include code that will never be executed or worse trigger build/runtime errors.

It would also enable the ability to build a chrome extension api wrapper that would allow content scripts to execute background specific apis via sendToBackground messaging to an internal handler if invoked in a content script.