Skip to content

Commit

Permalink
Vue3: Add vite plugin for portable stories
Browse files Browse the repository at this point in the history
  • Loading branch information
yannbf committed Aug 29, 2024
1 parent 76dd5eb commit d6bd213
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 21 deletions.
5 changes: 5 additions & 0 deletions code/addons/vitest/src/postinstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@ const getVitestPluginInfo = (framework: string) => {
frameworkPluginCall = 'storybookSveltekitPlugin()';
}

if (framework === '@storybook/vue3-vite') {
frameworkPluginImport = "import { storybookVuePlugin } from '@storybook/vue3-vite/vite'";
frameworkPluginCall = 'storybookVuePlugin()';
}

return { frameworkPluginImport, frameworkPluginCall };
};

Expand Down
8 changes: 7 additions & 1 deletion code/frameworks/vue3-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"types": "./dist/preset.d.ts",
"require": "./dist/preset.js"
},
"./vite": {
"types": "./dist/vite.d.ts",
"require": "./dist/vite.js",
"import": "./dist/vite.mjs"
},
"./package.json": "./package.json"
},
"main": "dist/index.js",
Expand Down Expand Up @@ -74,7 +79,8 @@
"bundler": {
"entries": [
"./src/index.ts",
"./src/preset.ts"
"./src/preset.ts",
"./src/vite.ts"
],
"platform": "node"
},
Expand Down
14 changes: 14 additions & 0 deletions code/frameworks/vue3-vite/src/plugins/vue-template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Plugin } from 'vite';

export async function templateCompilation() {
return {
name: 'storybook:vue-template-compilation',
config: () => ({
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
}),
} satisfies Plugin;
}
8 changes: 2 additions & 6 deletions code/frameworks/vue3-vite/src/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { PluginOption } from 'vite';

import { vueComponentMeta } from './plugins/vue-component-meta';
import { vueDocgen } from './plugins/vue-docgen';
import { templateCompilation } from './plugins/vue-template';
import type { FrameworkOptions, StorybookConfig, VueDocgenPlugin } from './types';

const getAbsolutePath = <I extends string>(input: I): I =>
Expand All @@ -17,7 +18,7 @@ export const core: PresetProperty<'core'> = {
};

export const viteFinal: StorybookConfig['viteFinal'] = async (config, options) => {
const plugins: PluginOption[] = [];
const plugins: PluginOption[] = [templateCompilation()];

const framework = await options.presets.apply('framework');
const frameworkOptions: FrameworkOptions =
Expand All @@ -35,11 +36,6 @@ export const viteFinal: StorybookConfig['viteFinal'] = async (config, options) =
const { mergeConfig } = await import('vite');
return mergeConfig(config, {
plugins,
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
});
};

Expand Down
5 changes: 5 additions & 0 deletions code/frameworks/vue3-vite/src/vite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { templateCompilation } from './plugins/vue-template';

export const storybookVuePlugin = () => {
return [templateCompilation()];
};
31 changes: 21 additions & 10 deletions scripts/tasks/sandbox-parts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { executeCLIStep, steps } from '../utils/cli-step';
import { CODE_DIRECTORY, REPROS_DIRECTORY } from '../utils/constants';
import { exec } from '../utils/exec';
import { filterExistsInCodeDir } from '../utils/filterExistsInCodeDir';
import { addPreviewAnnotations, readMainConfig } from '../utils/main-js';
import { addPreviewAnnotations, readConfig } from '../utils/main-js';
import { updatePackageScripts } from '../utils/package-json';
import { findFirstPath } from '../utils/paths';
import { workspacePath } from '../utils/workspace';
Expand Down Expand Up @@ -378,6 +378,11 @@ const getVitestPluginInfo = (details: TemplateDetails) => {
frameworkPluginCall = 'storybookSveltekitPlugin()';
}

if (framework === '@storybook/vue3-vite') {
frameworkPluginImport = "import { storybookVuePlugin } from '@storybook/vue3-vite/vite'";
frameworkPluginCall = 'storybookVuePlugin()';
}

return { frameworkPluginImport, frameworkPluginCall };
};

Expand Down Expand Up @@ -414,7 +419,6 @@ export async function setupVitest(details: TemplateDetails, options: PassedOptio
${isVue ? 'import * as vueAnnotations from "../src/stories/renderers/vue3/preview.js"' : ''}
const annotations = setProjectAnnotations([
{ tags: ['vitest'] },
rendererDocsAnnotations,
projectAnnotations,
coreAnnotations,
Expand All @@ -424,7 +428,7 @@ export async function setupVitest(details: TemplateDetails, options: PassedOptio
${isVue ? 'vueAnnotations,' : ''}
])
beforeAll(annotations.beforeAll!)`
beforeAll(annotations.beforeAll)`
);

await writeFile(
Expand Down Expand Up @@ -461,13 +465,11 @@ export async function setupVitest(details: TemplateDetails, options: PassedOptio
}
resolve: {
preserveSymlinks: true,
${isVue ? "alias: { vue: 'vue/dist/vue.esm-bundler.js' }," : ''}
},
test: {
name: "storybook",
pool: "threads",
include: [
// we need to set the path like this because svelte-kit overrides the root path so this makes it work in all sandboxes
"src/**/*.{story,stories}.?(c|m)[jt]s?(x)",
"template-stories/**/*.{story,stories}.?(c|m)[jt]s?(x)",
],
Expand All @@ -488,7 +490,6 @@ export async function setupVitest(details: TemplateDetails, options: PassedOptio
name: "chromium",
provider: "playwright",
headless: true,
screenshotFailures: false,
},
setupFiles: ["./.storybook/vitest.setup.ts"],
environment: "happy-dom",
Expand All @@ -503,8 +504,7 @@ export async function setupVitest(details: TemplateDetails, options: PassedOptio

packageJson.scripts = {
...packageJson.scripts,
vitest:
'vitest --pass-with-no-tests --reporter=default --reporter=hanging-process --test-timeout=5000',
vitest: 'vitest --reporter=default --reporter=hanging-process --test-timeout=5000',
};

// This workaround is needed because Vitest seems to have issues in link mode
Expand Down Expand Up @@ -562,7 +562,7 @@ export const addStories: Task['run'] = async (
const cwd = sandboxDir;
const storiesPath = await findFirstPath([join('src', 'stories'), 'stories'], { cwd });

const mainConfig = await readMainConfig({ cwd });
const mainConfig = await readConfig({ cwd });
const packageManager = JsPackageManagerFactory.getPackageManager({}, sandboxDir);

// Ensure that we match the right stories in the stories directory
Expand Down Expand Up @@ -709,7 +709,7 @@ export const addStories: Task['run'] = async (

export const extendMain: Task['run'] = async ({ template, sandboxDir, key }, { disableDocs }) => {
logger.log('📝 Extending main.js');
const mainConfig = await readMainConfig({ cwd: sandboxDir });
const mainConfig = await readConfig({ cwd: sandboxDir });

if (key === 'react-vite/default-ts') {
addRefs(mainConfig);
Expand Down Expand Up @@ -787,6 +787,17 @@ export const extendMain: Task['run'] = async ({ template, sandboxDir, key }, { d
await writeConfig(mainConfig);
};

export const extendPreview: Task['run'] = async ({ template, sandboxDir }) => {
logger.log('📝 Extending preview.js');
const previewConfig = await readConfig({ cwd: sandboxDir, fileName: 'preview' });

if (template.expected.builder.includes('vite')) {
previewConfig.setFieldValue(['tags'], ['vitest']);
}

await writeConfig(previewConfig);
};

export async function setImportMap(cwd: string) {
const packageJson = await readJson(join(cwd, 'package.json'));

Expand Down
3 changes: 3 additions & 0 deletions scripts/tasks/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const sandbox: Task = {
install,
addStories,
extendMain,
extendPreview,
init,
addExtraDependencies,
setImportMap,
Expand Down Expand Up @@ -120,6 +121,8 @@ export const sandbox: Task = {

await extendMain(details, options);

await extendPreview(details, options);

await setImportMap(details.sandboxDir);

logger.info(`✅ Storybook sandbox created at ${details.sandboxDir}`);
Expand Down
8 changes: 4 additions & 4 deletions scripts/utils/main-js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ import slash from 'slash';

import { getInterpretedFile } from '../../code/core/src/common';
import type { ConfigFile } from '../../code/core/src/csf-tools';
import { readConfig } from '../../code/core/src/csf-tools';
import { readConfig as csfReadConfig } from '../../code/core/src/csf-tools';

export async function readMainConfig({ cwd }: { cwd: string }) {
export async function readConfig({ fileName = 'main', cwd }: { fileName?: string; cwd: string }) {
const configDir = join(cwd, '.storybook');
if (!existsSync(configDir)) {
throw new Error(
`Unable to find the Storybook folder in "${configDir}". Are you sure it exists? Or maybe this folder uses a custom Storybook config directory?`
);
}

const mainConfigPath = getInterpretedFile(resolve(configDir, 'main'));
return readConfig(mainConfigPath);
const mainConfigPath = getInterpretedFile(resolve(configDir, fileName));
return csfReadConfig(mainConfigPath);
}

export function addPreviewAnnotations(mainConfig: ConfigFile, paths: string[]) {
Expand Down

0 comments on commit d6bd213

Please sign in to comment.