trigger.dev icon indicating copy to clipboard operation
trigger.dev copied to clipboard

Using import.meta.env fails inside of a trigger.dev build

Open ericallam opened this issue 1 year ago • 3 comments

From what I can tell, import.meta.env is a vite thing that populates import.meta.env with environment variables.

https://import-meta-env.org/guide/getting-started/introduction.html

An example usage is here:

https://github.com/usetonearm/core-web/blob/d178a6277306e9bfe0cde49c6550ceae33475292/packages/supabase/src/get-supabase-client-keys.ts#L6

They do have an esbuild plugin that we should look into seeing if it solves the issue.

ericallam avatar Sep 20 '24 11:09 ericallam

Hacky solution:

  • Add @import-meta-env/unplugin as a devDependency
  • If you don't already have it, add @trigger.dev/build as a devDependency

Then update your trigger.config.ts file like so:

import { defineConfig } from "@trigger.dev/sdk/v3";
import { esbuildPlugin } from "@trigger.dev/build";
import { esbuild as importMetaEnvPlugin } from "@import-meta-env/unplugin";

export default defineConfig({
  project: "<your project ref>",
  build: {
    extensions: [
      esbuildPlugin(
        importMetaEnvPlugin({
          example: ".env.example",
          env: ".env",
        }) as any
      ),
    ],
  },
});

(globalThis as any).import_meta_env = process.env;

ericallam avatar Sep 20 '24 13:09 ericallam

Did you test this solution? I'm not able to get it to recognize the import.meta.env variables. It throws the error:

Cannot read properties of undefined (reading 'VITE_CLOUDFLARE_R2_SECRET_ACCESS_KEY')

I tried messing around with the plugin's transformMode and a few other options, but I still couldn't get it to work.

Library versions:

vite="5.1.0",
@trigger.dev/sdk="3.0.12",

the-dream-machine avatar Oct 10 '24 08:10 the-dream-machine

You can actually transpile all the envs at the build time using this option:

importMetaEnvPlugin({
  env: './.env',
  example: './.env.example',
  transformMode: 'compile-time',
})

So you don't have to add the last line to expose it again.

Hacky solution:

  • Add @import-meta-env/unplugin as a devDependency
  • If you don't already have it, add @trigger.dev/build as a devDependency

Then update your trigger.config.ts file like so:

import { defineConfig } from "@trigger.dev/sdk/v3";
import { esbuildPlugin } from "@trigger.dev/build";
import { esbuild as importMetaEnvPlugin } from "@import-meta-env/unplugin";

export default defineConfig({
  project: "<your project ref>",
  build: {
    extensions: [
      esbuildPlugin(
        importMetaEnvPlugin({
          example: ".env.example",
          env: ".env",
        }) as any
      ),
    ],
  },
});

(globalThis as any).import_meta_env = process.env;

JohnCido avatar Oct 21 '24 08:10 JohnCido