Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow Flow syntax in stories #21859

Merged
merged 7 commits into from
Apr 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
};