Skip to content

Commit

Permalink
Remove exports from mdx files
Browse files Browse the repository at this point in the history
  • Loading branch information
bodograumann committed Oct 31, 2023
1 parent 1919225 commit a2707cb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
7 changes: 0 additions & 7 deletions code/lib/codemod/src/transforms/__tests__/mdx-to-csf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,6 @@ test('extract esm into csf head code', () => {
# hello
export const args = { bla: 1 };
export const Template = (args) => <Button {...args} />;
<Meta of={FoobarStories} />
world {2 + 1}
Expand Down Expand Up @@ -412,8 +409,6 @@ test('duplicate story name', () => {
import { Button } from './Button';
import * as FoobarStories from './Foobar.stories';
export const Default = (args) => <Button {...args} />;
<Meta of={FoobarStories} />
<Story of={FoobarStories.Default_} />
Expand Down Expand Up @@ -502,8 +497,6 @@ test('kebab case file name', () => {
import { Kebab } from './my-component/some-kebab-case';
import * as SomeKebabCaseStories from './some-kebab-case.stories';
export const Template = (args) => <Kebab {...args} />;
<Meta of={SomeKebabCaseStories} />
<Story of={SomeKebabCaseStories.MuchKebab} />
Expand Down
23 changes: 23 additions & 0 deletions code/lib/codemod/src/transforms/mdx-to-csf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { babelParse, babelParseExpression } from '@storybook/csf-tools';
import { remark } from 'remark';
import type { Root } from 'remark-mdx';
import remarkMdx from 'remark-mdx';
import type { Parent } from 'unist';
import { SKIP, visit } from 'unist-util-visit';
import { is } from 'unist-util-is';
import type {
Expand Down Expand Up @@ -205,6 +206,7 @@ export function transform(source: string, baseName: string): [mdx: string, csf:
return [mdxProcessor.stringify(root), null];
}

cleanUpMdx(root);
addStoriesImport(root, baseName, storyNamespaceName);

const newStatements: t.Statement[] = [
Expand Down Expand Up @@ -335,6 +337,27 @@ function getEsmAst(root: Root) {
return file;
}

function cleanUpMdx(root: Root): void {
visit(root, ['mdxjsEsm'], (node: MdxjsEsm, index?: number, parent?: Parent) => {
// @ts-expect-error File is not yet exposed, see https://github.com/babel/babel/issues/11350#issuecomment-644118606
const file: BabelFile = new babel.File(
{ filename: 'info.path' },
{ code: node.value, ast: babelParse(node.value) }
);

file.path.traverse({
ExportDeclaration: (path) => path.remove(),
});
const code = recast.print(file.path.node).code.trim();
if (code === '') {
parent.children.splice(index, 1);
return index;
}
node.value = code;
return index + 1;
});
}

function addStoriesImport(root: Root, baseName: string, storyNamespaceName: string): void {
let found = false;

Expand Down

0 comments on commit a2707cb

Please sign in to comment.