mirror of
https://github.com/storybookjs/storybook.git
synced 2025-04-08 07:52:07 +08:00
Naive implementation of local vite plugin to replace vite-plugin-externals
This commit is contained in:
parent
d9cdbc159a
commit
9642d04f28
38
code/lib/builder-vite/src/plugins/externals-plugin.ts
Normal file
38
code/lib/builder-vite/src/plugins/externals-plugin.ts
Normal 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();
|
||||
},
|
||||
};
|
||||
}
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user