Skip to content

Latest commit

 

History

History
111 lines (78 loc) · 2.99 KB

v1.md

File metadata and controls

111 lines (78 loc) · 2.99 KB

vite-inject-env

vite-inject-env is a tool that allows you to inject your environment variables after building the static files, allowing you to deploy the same build to multiple environments quickly.

Usage

Sample project

1. Update Code

Create a new file called env.js, and place all your process.env variables here.

export const env = {
    VITE_COLOR: process.env.VITE_COLOR,
    VITE_LOGO_URL: process.env.VITE_LOGO_URL,
    VITE_MAIN_TEXT: process.env.VITE_MAIN_TEXT,
    VITE_LINK_URL: process.env.VITE_LINK_URL
}

When referencing environment variables, import env and reference it from there instead. Do not access process.env directly from now on.

import { env } from './env'

export const App = () => {
    return (
      <div style={{backgroundColor: env.VITE_COLOR}}>
        <span>{env.VITE_MAIN_TEXT}</span>
      </div>
    )
}

2. Build static files with placeholders

[env variable names] npx vite-inject-env build [your build script]

Pass in all your environment variable names (the value does not matter), then run npx vite-inject-env build, followed by your build script.

# if your build script is 'npm run build'
VITE_COLOR= VITE_TEXT= npx vite-inject-env build npm run build

# if your build script is 'react-scripts build'
VITE_COLOR= VITE_TEXT= npx vite-inject-env build react-scripts-build 

3. Inject environment variables

[env variables] vite-inject-env inject -d [path to build folder] -o [new output path]

Pass in all your environment variables, followed by the path to your build folder in Step #2, and the new output path for the static files that will contain the injected environment variables.

# with a black background
VITE_COLOR=black VITE_TEXT="Black Background" npx vite-inject-env inject -d build -o build-black

# with a blue background
VITE_COLOR=blue VITE_TEXT="Blue Background" npx vite-inject-env inject -d build -o build-blue

.env / dotenv

Sample usage with .env

.env files are supported. vite-inject-env will automatically detect environment variables in your .env file located in your root folder.

Note: Environment variables passed in through the command line will take precedence over .env variables.

Docker / CICD

Sample usage with Docker

FROM node:16.10-slim
COPY . /app
WORKDIR /app

RUN npm install

RUN \
VITE_COLOR= \
VITE_LOGO_URL= \
VITE_MAIN_TEXT= \
VITE_LINK_URL= \
npx vite-inject-env build npm run build

EXPOSE 8080

ENTRYPOINT \
VITE_COLOR=$VITE_COLOR \
VITE_LOGO_URL=$VITE_LOGO_URL \
VITE_MAIN_TEXT=$VITE_MAIN_TEXT \
VITE_LINK_URL=$VITE_LINK_URL \
npx vite-inject-env inject -d ./build \
&& npx http-server build

Note: There is no need to use the -o parameter in Docker.

Sample Projects

  1. Sample project
  2. .env sample
  3. Docker sample