Skip to content

Commit

Permalink
fix: write envConfig template in generateBundle hook (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukashass committed Mar 31, 2022
1 parent 6776360 commit 5b07ca2
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions src/envConfig.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import fs from 'fs';
import path from 'path';
import type { Plugin, ResolvedConfig } from 'vite';
import type { Plugin } from 'vite';

export function createEnvConfigContent(variables: string[], template: boolean): string {
let templateContent = '';
Expand All @@ -26,14 +24,9 @@ export interface EnvConfigOptions {
}

export function envConfig(userOptions: Partial<EnvConfigOptions> = {}): Plugin {
let config: ResolvedConfig;
return {
name: 'vite-plugin-env-config',

configResolved(resolvedConfig) {
config = resolvedConfig;
},

configureServer(server) {
const envConfigContent = createEnvConfigContent(userOptions.variables || [], false);

Expand All @@ -52,12 +45,13 @@ export function envConfig(userOptions: Partial<EnvConfigOptions> = {}): Plugin {
});
},

closeBundle() {
generateBundle() {
const templateContent = createEnvConfigContent(userOptions.variables || [], true);

const TEMPLATE_PATH = path.join(config.root, config.build.outDir, 'env-config.template.js');
fs.mkdirSync(path.dirname(TEMPLATE_PATH), { recursive: true });
fs.writeFileSync(TEMPLATE_PATH, templateContent, 'utf8');
this.emitFile({
type: 'asset',
fileName: 'env-config.template.js',
source: templateContent,
});
},

transformIndexHtml(html) {
Expand Down

0 comments on commit 5b07ca2

Please sign in to comment.