Production vs Environmental .env Files

There comes a time when you have worked hard to take your application from development to production. You've cleared your bugs and now you are ready to publish your React or Laravel application to the web, but you have this .env file and the configurations are set for your local environment, you could do different things, but what is the easiest way?

One of the easiest way to build your production application is to use one simple command. How do you do that? Simple, follow these steps.

  1. Create two files:
    1. $ touch .env.dev
    2. $ touch .env.prod
  2. install env-cmd
    $ npm install --save-dev env-cmd
  3. Update package.json
        "scripts": {
            "dev": "vite",
            "build:dev": "env-cmd -f .env.dev vite build",
            "build:prod": "env-cmd -f .env.prod vite build"
        },
  4. Run terminal commands
    $ npm run build:dev
    $ npm run build:prod

 

[Old way]

  1. Create a .env.development for your development environment
  2. Creae a .env.production file for your production build
  3. Open you the package JSON file, for example, in React is package.json
  4. In the scripts section change the build command to the following:
    "scripts": {
        .....
        "build": "NODE_ENV=development react-scripts build",
        "build:prod": "NODE_ENV=production react-scripts build",
        .....
      },
  5. When you are ready for your build use the build command:
  6. For Development:
    $ npm run build
  7. For Production:
    npm run build:prod

UPDATE: For some peole this is not working, try installing 'env-cmd' package - https://www.npmjs.com/package/env-cmd

More info: https://stackoverflow.com/a/75091721