From 9642d04f28ec38f48cbd89a4f70a48f6890d1c0b Mon Sep 17 00:00:00 2001 From: "charles.gruenais" Date: Thu, 19 Jan 2023 23:57:34 +0100 Subject: [PATCH] Naive implementation of local vite plugin to replace vite-plugin-externals --- .../src/plugins/externals-plugin.ts | 38 +++++++++++++++++++ code/lib/builder-vite/src/vite-config.ts | 3 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 code/lib/builder-vite/src/plugins/externals-plugin.ts diff --git a/code/lib/builder-vite/src/plugins/externals-plugin.ts b/code/lib/builder-vite/src/plugins/externals-plugin.ts new file mode 100644 index 00000000000..574ffc1365f --- /dev/null +++ b/code/lib/builder-vite/src/plugins/externals-plugin.ts @@ -0,0 +1,38 @@ +import { init, parse } from 'es-module-lexer'; +import MagicString from 'magic-string'; +import { globals } from '@storybook/preview/globals'; + +type SingleGlobalName = keyof typeof globals; + +export async function externalsPlugin() { + await init; + return { + name: 'storybook:externals-plugin', + enforce: 'post', + async transform(code: string, id: string) { + const globalsList = Object.keys(globals) as SingleGlobalName[]; + if (globalsList.every((glob) => !code.includes(glob))) return undefined; + + const [imports] = parse(code); + const src = new MagicString(code); + imports.forEach(({ n: path, ss: startPosition, se: endPosition }) => { + const packageName = path as SingleGlobalName | undefined; + const packageAndDelimiters = new RegExp(`.${packageName}.`); + if (packageName && globalsList.includes(packageName)) { + src.update( + startPosition, + endPosition, + src + .slice(startPosition, endPosition) + .replace('import ', 'const ') + .replace(' as ', ': ') + .replace(' from ', ' = ') + .replace(packageAndDelimiters, globals[packageName]) + ); + } + }); + + return src.toString(); + }, + }; +} diff --git a/code/lib/builder-vite/src/vite-config.ts b/code/lib/builder-vite/src/vite-config.ts index 316d970189a..aa1b2572fc7 100644 --- a/code/lib/builder-vite/src/vite-config.ts +++ b/code/lib/builder-vite/src/vite-config.ts @@ -18,6 +18,7 @@ import { mdxPlugin, stripStoryHMRBoundary, } from './plugins'; +import { externalsPlugin } from './plugins/externals-plugin'; export type PluginConfigType = 'build' | 'development'; @@ -91,7 +92,7 @@ export async function pluginConfig(options: Options) { } }, }, - viteExternalsPlugin(globals, { useWindow: false, disableInServe: true }), + await externalsPlugin(), ] as PluginOption[]; // TODO: framework doesn't exist, should move into framework when/if built