Skip to content

Commit

Permalink
Merge pull request #21859 from FezVrasta/patch-1
Browse files Browse the repository at this point in the history
fix: allow Flow syntax in stories
  • Loading branch information
valentinpalkovic authored and shilman committed May 3, 2023
1 parent 546d8bc commit edbc72e
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions code/lib/csf-tools/src/babelParse.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
import * as parser from '@babel/parser';
import * as babelParser from '@babel/parser';
import * as recast from 'recast';
import type { ParserOptions } from '@babel/parser';

function parseWithFlowOrTypescript(source: string, parserOptions: babelParser.ParserOptions) {
const flowCommentPattern = /^\s*\/\/\s*@flow/;
const useFlowPlugin = flowCommentPattern.test(source);

const parserPlugins: babelParser.ParserOptions['plugins'] = useFlowPlugin
? ['flow']
: ['typescript'];

// Merge the provided parserOptions with the custom parser plugins
const mergedParserOptions = {
...parserOptions,
plugins: [...parserOptions.plugins, ...parserPlugins],
};

return babelParser.parse(source, mergedParserOptions);
}

export const parserOptions: ParserOptions = {
sourceType: 'module',
// FIXME: we should get this from the project config somehow?
plugins: ['jsx', 'typescript', 'decorators-legacy', 'classProperties'],
plugins: ['jsx', 'decorators-legacy', 'classProperties'],
tokens: true,
};

export const babelParse = (code: string) => {
return recast.parse(code, {
parser: {
parse(source: string) {
return parser.parse(source, parserOptions);
return parseWithFlowOrTypescript(source, parserOptions);
},
},
});
};

export const babelParseExpression = (code: string) => {
return parser.parseExpression(code, parserOptions);
return babelParser.parseExpression(code, parserOptions);
};

0 comments on commit edbc72e

Please sign in to comment.