Andarist / rollup-plugin-dotenv

33 stars 13 forks source link

process not defined #7

Closed Tobbe closed 2 years ago

Tobbe commented 2 years ago

Hi

I started using this plugin when building my app locally, so in dev mode, and it worked great! (It's a StencilJS app.) But when I try to build for production no replacement is taking place and instead I get a "process not defined" error when trying to use my app.

So I tried switching over to @rollup/plugin-replace and that works. But I'd much rather use your plugin :)

This is the code that uses the env var

  private static getBaseUrl(url: string) {
    if (url.indexOf("http") === 0) {
      // Urls that start with http probably have a host in them, and should not
      // have an extra base added
      return "";
    }

    return process.env.API_BASE;
  }

This is my config with rollup-plugin-dotenv. This does not work. No replacement is made.

import { Config } from "@stencil/core";
import dotenvPlugin from "rollup-plugin-dotenv";
import replace from "@rollup/plugin-replace";

export const config: Config = {
  namespace: "test-webcomponents",
  outputTargets: [
    {
      type: "dist",
      esmLoaderPath: "../loader",
    },
    {
      type: "dist-custom-elements-bundle",
    },
    {
      type: "docs-readme",
    },
    {
      type: "www",
      serviceWorker: null, // disable service workers
    },
  ],
  plugins: [dotenvPlugin()],
};

If I use plugin-replace instead it works (only showing the plugin config part) (But it only works on my build server. Of course this doesn't work locally with my .env file)

  plugins: [
    replace({
      "process.env.API_BASE": '"' + process.env.API_BASE + '"',
    }),
  ],

Locally I've been using a .env file, but when building for prod I'm setting an actual env var on the build server.

Can you see if I'm doing anything wrong?

Tobbe commented 2 years ago

I got it figured out.

What I didn't understand was that I had to have a file with the env var in it in order to read the value from the system env vars. So to read API_BASE from my system env vars I need to have a .env (or any other file the plugin will read) with API_BASE='whatever' in it, just to let the plugin know to look for that variable name in the system vars.

Andarist commented 2 years ago

I'm glad that you have figured it out 👍