Skip to content

Commit

Permalink
Add support for passing in sourceLoader options from the docs addon u…
Browse files Browse the repository at this point in the history
…sing the vite builder
  • Loading branch information
joshwooding committed Oct 30, 2022
1 parent f0555bb commit 73b9f2d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
19 changes: 15 additions & 4 deletions code/lib/builder-vite/src/plugins/source-loader-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,44 @@
import type { Plugin } from 'vite';
import sourceLoaderTransform from '@storybook/source-loader';
import MagicString from 'magic-string';
import type { StorybookConfig } from '@storybook/types';
import type { ExtendedOptions } from '../types';

const storyPattern = /\.stories\.[jt]sx?$/;
const storySourcePattern = /var __STORY__ = "(.*)"/;
const storySourceReplacement = '--STORY_SOURCE_REPLACEMENT--';

const mockClassLoader = (id: string) => ({
const mockClassLoader = (id: string, options: any) => ({
// eslint-disable-next-line no-console
emitWarning: (message: string) => console.warn(message),
resourcePath: id,
getOptions: () => ({}),
getOptions: () => ({ injectStoryParameters: true, inspectLocalDependencies: true, ...options }),
});

// HACK: Until we can support only node 15+ and use string.prototype.replaceAll
const replaceAll = (str: string, search: string, replacement: string) => {
return str.split(search).join(replacement);
};

export function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {
export async function sourceLoaderPlugin(config: ExtendedOptions): Promise<Plugin | Plugin[]> {
const { presets } = config;

const addons = await presets.apply('addons', [] as StorybookConfig['addons']);

const docsOptions =
// @ts-expect-error - not sure what type to use here
addons.find((a) => [a, a.name].includes('@storybook/addon-docs'))?.options ?? {};
if (config.configType === 'DEVELOPMENT') {
return {
name: 'storybook:source-loader-plugin',
enforce: 'pre',
async transform(src: string, id: string) {
if (id.match(storyPattern)) {
// @ts-expect-error - source loader doesn't have types
const code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);
const code: string = await sourceLoaderTransform.call(
mockClassLoader(id, docsOptions.sourceLoaderOptions),
src
);
const s = new MagicString(src);
// Entirely replace with new code
s.overwrite(0, src.length, code);
Expand Down
2 changes: 1 addition & 1 deletion code/lib/builder-vite/src/vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export async function pluginConfig(options: ExtendedOptions) {

const plugins = [
codeGeneratorPlugin(options),
sourceLoaderPlugin(options),
await sourceLoaderPlugin(options),
mdxPlugin(),
injectExportOrderPlugin,
stripStoryHMRBoundary(),
Expand Down

0 comments on commit 73b9f2d

Please sign in to comment.