Last active
November 7, 2021 05:06
-
-
Save furryablack/c1348c7062a1346b4b6fe22c1dd6ff8c to your computer and use it in GitHub Desktop.
Vite, loadEnv, process.env[VARS] in the vite.config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
loadProcessEnv function is setting process.env vars accessible in the vite.config and parse process.env vars. | |
(string process.env.FLAG="true" => boolean process.env.FLAG=true) | |
*/ | |
// @file: .env | |
VITE_NEED_MINIFY=true | |
// @file: load-process-env.ts | |
import {loadEnv} from 'vite'; | |
function parseEnvironmentVariable(variable: string) { | |
try { | |
return JSON.parse(variable); | |
} catch (err) { | |
return variable.toString(); | |
} | |
} | |
export function loadProcessEnv(mode: string, evnsFolder: string = 'ABSOLUTE PATH TO FOLDER WHERE ENVS IS') { | |
// It makes the process.env.PROD/ENV for the web-tooling context (like import.meta.env.PROD/ENV) | |
process.env.PROD = process.env.NODE_ENV === 'production' ? 'true' : 'false'; | |
process.env.DEV = process.env.NODE_ENV === 'development' ? 'true' : 'false'; | |
process.env = { | |
...process.env, | |
...Object.entries(loadEnv(mode, evnsFolder)).reduce((acc, [key, value]) => ({ | |
...acc, | |
[key]: parseEnvironmentVariable(value), | |
}), {}), | |
}; | |
} | |
// @file: vite.config.ts | |
import {defineConfig} from 'vite'; | |
import * as PATHS from './paths'; | |
import {loadProcessEnv} from './load-process-env'; | |
export default defineConfig(({mode}) => { | |
loadProcessEnv(mode, PATHS.PROJECT_ROOT); | |
return { | |
// ... | |
build: { | |
// Boolean(true|false) instead of Boolean("true"|"false") | |
minify: Boolean(process.env.VITE_NEED_MINIFY) ?? 'esbuild', | |
}, | |
// ... | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment