skip to Main Content

I have created an application with React js with Vite implementation in it.
So now I have to use the environment variable in the json file while running the application in development mode.

Attaching some code for reference.

.env.development

VITE_NODE_ENV=development
VITE_REACT_APP_BASE_URL = "http://localhost:3000"

vite.config.js

import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import viteTsconfigPaths from 'vite-tsconfig-paths';
import { TransformOption, viteStaticCopy } from 'vite-plugin-static-copy';

const copyPlugin = (env: any) => {
  const reactBaseURLtransform: TransformOption = (contents, path) => {
    return contents.replace(/<REACT_APP_BASE_URL>/g, env.VITE_REACT_APP_BASE_URL);
  };

  return viteStaticCopy({
    flatten: true,
    targets: [
      {
        src: 'public/*.json',
        dest: '',
        transform: reactBaseURLtransform,
      }
    ],
  });
};

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const plugins: any[] = [react(), viteTsconfigPaths()];
  plugins.push(copyPlugin(env));

  return {
    plugins: [...plugins],
    build: {
      outDir: 'build',
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
      chunkSizeWarningLimit: 5000,
    },
    server: {
      open: false,
      port: 3000,
    },
  };
});

Currently with this configuration of Vite, when we build the application using yarn build(which internally runs "vite build"), Vite replaces all the <REACT_APP_BASE_URL> with the URL defined in the .env file.

In the same way, when we start the application using yarn start(which internally runs "vite"), it should replace all the <REACT_APP_BASE_URL> with the URL defined in the .env file but currently it’s not doing it.

So what can be the approach to replace all the <REACT_APP_BASE_URL>(defined in json file) with the URL defined in the .env file when we start our application in dev mode.

2

Answers


  1. The problem I’m having is that I can’t get the variables in the .env file. Originally my .env file was in the src folder and when I put the .env file into the root of the project I was able to get it.

    Login or Signup to reply.
  2. Try this:

    • Create a custom Vite plugin
    • Use the transform hook for JSON files
    • Replace <REACT_APP_BASE_URL> during development
    // Custom plugin in vite.config.js
    const replaceBaseUrlPlugin = (env) => {
      return {
        name: 'replace-base-url',
        transform(code, id) {
          if (id.endsWith('.json') && env.VITE_NODE_ENV === 'development') {
            return code.replace(/<REACT_APP_BASE_URL>/g, env.VITE_REACT_APP_BASE_URL);
          }
        },
      };
    };
    
    // Add the plugin to your configuration
    export default defineConfig(({ command, mode }) => {
      const env = loadEnv(mode, process.cwd(), '');
      const plugins: any[] = [react(), viteTsconfigPaths(), replaceBaseUrlPlugin(env)];
    
      // ...
    });
    

    This should work for replacing <REACT_APP_BASE_URL> in JSON files during development.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search