Naive implementation of local vite plugin to replace vite-plugin-externals

This commit is contained in:
charles.gruenais 2023-01-19 23:57:34 +01:00
parent d9cdbc159a
commit 9642d04f28
2 changed files with 40 additions and 1 deletions

View File

@ -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();
},
};
}

View File

@ -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