Uncaught ReferenceError: process is not defined after vite update, why?

Viewed 64

I have a react/typescript app and before I updated vite I had this solution to check either env is development or production by this code:

function getEnvironment(): "production" | "development" {
  if (process.env.NODE_ENV === "production") {
    return "production";
  }
  return "development";
}

type EnvUrl = { development: string; production: string };

const API_URL: EnvUrl = {
  development: "http://localhost:5173/api/endpoint",
  production: "https://ingress-url/api/endpoint",
};

export const apiUrl = API_URL[getEnvironment()];

But after i updated vite to version 3.1.0 I got error when serving production build with following error: Uncaught ReferenceError: process is not defined.

By vite config is:

import react from "@vitejs/plugin-react";
import { resolve } from "path";
import { rollupImportMapPlugin } from "rollup-plugin-import-map";
import { terser } from "rollup-plugin-terser";
import { ConfigEnv } from "vite";
import viteCompression from "vite-plugin-compression";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
import { viteMockServe } from "vite-plugin-mock";
import { UserConfigExport } from "vitest/config";

const reactUrl = "my-cdn-url/react/18/esm/index.js";
const reactDomUrl = "my-cdn-url/react-dom/18/esm/index.js";

const imports = {
  react: reactUrl,
  "react-dom": reactDomUrl,
};

export default ({ command }: ConfigEnv): UserConfigExport => ({
  plugins: [
    react(),
    terser(),
    cssInjectedByJsPlugin(),
    viteCompression({
      algorithm: "gzip",
    }),
    viteCompression({
      algorithm: "brotliCompress",
    }),
    viteMockServe({
      mockPath: "mock",
      localEnabled: command === "serve",
    }),
    {
      ...rollupImportMapPlugin([{ imports }]),
      enforce: "pre",
      apply: "build",
    },
  ],
  build: {
    lib: {
      entry: resolve(__dirname, "src/Mikrofrontend.tsx"),
      name: "sokos-attestasjon-frontend",
      formats: ["es"],
      fileName: () => `bundle.js`,
    },
  },
  test: {
    globals: true,
    environment: "jsdom",
    deps: {
      inline: ["@testing-library/user-event"],
    },
  },
});

Is there another way to fix the problem or am I missing something in my vite.config.js ? If its another solution after upgrade, what the recommended one so my application behave the same as before?

Thank you.

1 Answers

Use import.meta.env.MODE to get the mode string:

if (import.meta.env.MODE === "production") {
  return "production";
}

Or more simply, use import.meta.env.PROD to get a Boolean indicating production mode:

if (import.meta.env.PROD) {
  return "production";
}
Related