Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vite: Support environment variables in viteFinal define config #19905

Merged
merged 6 commits into from
Nov 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion code/lib/builder-vite/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { build as viteBuild } from 'vite';
import { commonConfig } from './vite-config';

import type { ExtendedOptions } from './types';
import { sanitizeEnvVars } from './envs';

export async function build(options: ExtendedOptions) {
const { presets } = options;
Expand All @@ -15,5 +16,5 @@ export async function build(options: ExtendedOptions) {

const finalConfig = await presets.apply('viteFinal', config, options);

await viteBuild(finalConfig);
await viteBuild(await sanitizeEnvVars(options, finalConfig));
}
53 changes: 33 additions & 20 deletions code/lib/builder-vite/src/envs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { stringifyEnvs } from '@storybook/core-common';

import type { UserConfig } from 'vite';
import type { UserConfig as ViteConfig } from 'vite';
import type { Builder_EnvsRaw } from '@storybook/types';
import type { ExtendedOptions } from './types';

// Allowed env variables on the client
const allowedEnvVariables = [
Expand All @@ -19,29 +19,42 @@ const allowedEnvVariables = [
* Customized version of stringifyProcessEnvs from @storybook/core-common which
* uses import.meta.env instead of process.env and checks for allowed variables.
*/
export function stringifyProcessEnvs(raw: Builder_EnvsRaw, envPrefix: UserConfig['envPrefix']) {
export function stringifyProcessEnvs(raw: Builder_EnvsRaw, envPrefix: ViteConfig['envPrefix']) {
const updatedRaw: Builder_EnvsRaw = {};
const envs = Object.entries(raw).reduce(
(acc: Builder_EnvsRaw, [key, value]) => {
// Only add allowed values OR values from array OR string started with allowed prefixes
if (
allowedEnvVariables.includes(key) ||
(Array.isArray(envPrefix) && !!envPrefix.find((prefix) => key.startsWith(prefix))) ||
(typeof envPrefix === 'string' && key.startsWith(envPrefix))
) {
acc[`import.meta.env.${key}`] = JSON.stringify(value);
updatedRaw[key] = value;
}
return acc;
},
{
// Default fallback
'process.env.XSTORYBOOK_EXAMPLE_APP': '""',
const envs = Object.entries(raw).reduce((acc: Builder_EnvsRaw, [key, value]) => {
// Only add allowed values OR values from array OR string started with allowed prefixes
if (
allowedEnvVariables.includes(key) ||
(Array.isArray(envPrefix) && !!envPrefix.find((prefix) => key.startsWith(prefix))) ||
(typeof envPrefix === 'string' && key.startsWith(envPrefix))
) {
acc[`import.meta.env.${key}`] = JSON.stringify(value);
updatedRaw[key] = value;
}
);
return acc;
}, {});
// support destructuring like
// const { foo } = import.meta.env;
envs['import.meta.env'] = JSON.stringify(stringifyEnvs(updatedRaw));

return envs;
}

// Sanitize environment variables if needed
export async function sanitizeEnvVars(options: ExtendedOptions, config: ViteConfig) {
const { presets } = options;
const envsRaw = await presets.apply<Promise<Builder_EnvsRaw>>('env');
let { define } = config;
if (Object.keys(envsRaw).length) {
// Stringify env variables after getting `envPrefix` from the config
const envs = stringifyProcessEnvs(envsRaw, config.envPrefix);
define = {
...define,
...envs,
};
}
return {
...config,
define,
} as ViteConfig;
}
14 changes: 0 additions & 14 deletions code/lib/builder-vite/src/vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import type {
} from 'vite';
import viteReact from '@vitejs/plugin-react';
import { isPreservingSymlinks, getFrameworkName } from '@storybook/core-common';
import type { Builder_EnvsRaw } from '@storybook/types';
import { stringifyProcessEnvs } from './envs';
import {
codeGeneratorPlugin,
injectExportOrderPlugin,
Expand Down Expand Up @@ -38,7 +36,6 @@ export async function commonConfig(
options: ExtendedOptions,
_type: PluginConfigType
): Promise<ViteInlineConfig> {
const { presets } = options;
const configEnv = _type === 'development' ? configEnvServe : configEnvBuild;

const { config: userConfig = {} } = (await loadConfigFromFile(configEnv)) ?? {};
Expand All @@ -64,17 +61,6 @@ export async function commonConfig(

const config: ViteConfig = mergeConfig(userConfig, sbConfig);

// Sanitize environment variables if needed
const envsRaw = await presets.apply<Promise<Builder_EnvsRaw>>('env');
if (Object.keys(envsRaw).length) {
// Stringify env variables after getting `envPrefix` from the config
const envs = stringifyProcessEnvs(envsRaw, config.envPrefix);
config.define = {
...config.define,
...envs,
};
}

return config;
}

Expand Down
4 changes: 3 additions & 1 deletion code/lib/builder-vite/src/vite-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createServer } from 'vite';
import { commonConfig } from './vite-config';
import type { ExtendedOptions } from './types';
import { getOptimizeDeps } from './optimizeDeps';
import { sanitizeEnvVars } from './envs';

export async function createViteServer(options: ExtendedOptions, devServer: Server) {
const { presets } = options;
Expand All @@ -27,5 +28,6 @@ export async function createViteServer(options: ExtendedOptions, devServer: Serv
};

const finalConfig = await presets.apply('viteFinal', config, options);
return createServer(finalConfig);

return createServer(await sanitizeEnvVars(options, finalConfig));
}
14 changes: 4 additions & 10 deletions code/lib/core-common/src/utils/envs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,10 @@ export const stringifyEnvs = (raw: Record<string, string>): Record<string, strin
}, {});

export const stringifyProcessEnvs = (raw: Record<string, string>): Record<string, string> => {
const envs = Object.entries(raw).reduce<Record<string, string>>(
(acc, [key, value]) => {
acc[`process.env.${key}`] = JSON.stringify(value);
return acc;
},
{
// Default fallback
'process.env.XSTORYBOOK_EXAMPLE_APP': '""',
}
);
const envs = Object.entries(raw).reduce<Record<string, string>>((acc, [key, value]) => {
acc[`process.env.${key}`] = JSON.stringify(value);
return acc;
}, {});
// FIXME: something like this is necessary to support destructuring like:
//
// const { foo } = process.env;
Expand Down