From 33101b267300282629848b3c6a6849b0043e9230 Mon Sep 17 00:00:00 2001 From: Michael Shilman Date: Fri, 21 Apr 2023 11:35:04 +0800 Subject: [PATCH] Merge pull request #22190 from storybookjs/shilman/21703-csf-improve-error CSF: Improve error message for bad default export --- code/lib/csf-tools/src/CsfFile.test.ts | 13 +++++++++++++ code/lib/csf-tools/src/CsfFile.ts | 14 +++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/code/lib/csf-tools/src/CsfFile.test.ts b/code/lib/csf-tools/src/CsfFile.test.ts index e54a063c0249..6250ea1c3696 100644 --- a/code/lib/csf-tools/src/CsfFile.test.ts +++ b/code/lib/csf-tools/src/CsfFile.test.ts @@ -548,6 +548,19 @@ describe('CsfFile', () => { ).toThrow('CSF: missing default export'); }); + it('bad meta', () => { + expect(() => + parse( + dedent` + const foo = bar(); + export default foo; + export const A = () => {}; + export const B = () => {}; + ` + ) + ).toThrow('CSF: default export must be an object'); + }); + it('no metadata', () => { expect(() => parse( diff --git a/code/lib/csf-tools/src/CsfFile.ts b/code/lib/csf-tools/src/CsfFile.ts index b7b3a07412f3..bfc9716e425b 100644 --- a/code/lib/csf-tools/src/CsfFile.ts +++ b/code/lib/csf-tools/src/CsfFile.ts @@ -105,9 +105,9 @@ export interface CsfOptions { } export class NoMetaError extends Error { - constructor(ast: t.Node, fileName?: string) { + constructor(message: string, ast: t.Node, fileName?: string) { super(dedent` - CSF: missing default export ${formatLocation(ast, fileName)} + CSF: ${message} ${formatLocation(ast, fileName)} More info: https://storybook.js.org/docs/react/writing-stories/introduction#default-export `); @@ -272,6 +272,14 @@ export class CsfFile { self._metaNode = metaNode; self._parseMeta(metaNode, parent); } + + if (self._metaStatement && !self._metaNode) { + throw new NoMetaError( + 'default export must be an object', + self._metaStatement, + self._fileName + ); + } }, }, ExportNamedDeclaration: { @@ -435,7 +443,7 @@ export class CsfFile { }); if (!self._meta) { - throw new NoMetaError(self._ast, self._fileName); + throw new NoMetaError('missing default export', self._ast, self._fileName); } if (!self._meta.title && !self._meta.component) {