|
| 1 | +import { env as loadEnv } from "@dotenv-run/core"; |
| 2 | +import { Plugin } from "vite"; |
| 3 | +import { viteEnvPrefixToPrefix } from "./mapper.js"; |
| 4 | +import { sanitizeOptions, ViteDotenvRunOptions } from "./options.js"; |
| 5 | +import replace from "@rollup/plugin-replace"; |
| 6 | +import { DEFAULT_ENV_FILES } from "./constants.js"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Vite plugin to load environment variables from .env files using `@dotenv-run/core`. |
| 10 | + * |
| 11 | + * This plugin seamlessly integrates with Vite by automatically deriving the root, |
| 12 | + * prefix and environment options from Vite's `envDir`, `envPrefix` and `mode`, |
| 13 | + * ensuring a more cohesive experience. |
| 14 | + * |
| 15 | + * @param {ViteDotenvRunOptions} [options] - Options for configuring the plugin. |
| 16 | + * See {@link ViteDotenvRunOptions} for more details. |
| 17 | + * |
| 18 | + * @returns {Plugin} Vite plugin object that enhances the Vite configuration. |
| 19 | + * |
| 20 | + * @example |
| 21 | + * // Usage in a Vite config file |
| 22 | + * import dotenvRun from 'vite-plugin-dotenv-run'; |
| 23 | + * |
| 24 | + * export default { |
| 25 | + * envDir: '../..', |
| 26 | + * envPrefix: ['VITE_', 'CUSTOM_'], |
| 27 | + * plugins: [ |
| 28 | + * dotenvRun(), |
| 29 | + * ], |
| 30 | + * }; |
| 31 | + */ |
| 32 | +const dotenvRun = (options?: ViteDotenvRunOptions): Plugin => { |
| 33 | + options = sanitizeOptions(options); |
| 34 | + const files = options?.files ?? DEFAULT_ENV_FILES; |
| 35 | + |
| 36 | + return { |
| 37 | + name: "vite-plugin-dotenv-run", |
| 38 | + config: (config, configEnv) => { |
| 39 | + const prefix = viteEnvPrefixToPrefix(config.envPrefix); |
| 40 | + |
| 41 | + const { full } = loadEnv({ |
| 42 | + files, |
| 43 | + prefix, |
| 44 | + root: config.envDir, |
| 45 | + environment: configEnv.mode, |
| 46 | + ...options, |
| 47 | + }); |
| 48 | + |
| 49 | + return { |
| 50 | + ...config, |
| 51 | + ...replace({ |
| 52 | + preventAssignment: true, |
| 53 | + values: full, |
| 54 | + }), |
| 55 | + }; |
| 56 | + }, |
| 57 | + }; |
| 58 | +}; |
| 59 | + |
| 60 | +export { dotenvRun, ViteDotenvRunOptions }; |
| 61 | +export default dotenvRun; |
0 commit comments