-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #21859 from FezVrasta/patch-1
fix: allow Flow syntax in stories
- Loading branch information
1 parent
546d8bc
commit edbc72e
Showing
1 changed file
with
21 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |