-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathhelper.ts
70 lines (64 loc) · 1.8 KB
/
helper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {ParserOptions, ParserPlugin} from '@babel/parser';
/**
* determine if the file is a typescript (ts), javascript (js) otherwise returns undefined.
* @param filepath
* @returns 'js'|'ts' or undefined
*/
export const supportedFileType = (filePath: string): 'ts' | 'js' | undefined => {
if (filePath.match(/\.tsx?$/)) {
return 'ts';
}
if (filePath.match(/\.m?jsx?$/)) {
return 'js';
}
return undefined;
};
export const plugins: ParserPlugin[] = [
'asyncGenerators',
'bigInt',
'classPrivateMethods',
'classPrivateProperties',
'classProperties',
'doExpressions',
'dynamicImport',
'estree',
'exportDefaultFrom',
'exportNamespaceFrom', // deprecated
'functionBind',
'functionSent',
'importMeta',
'jsx',
'logicalAssignment',
'nullishCoalescingOperator',
'numericSeparator',
'objectRestSpread',
'optionalCatchBinding',
'optionalChaining',
'partialApplication',
'throwExpressions',
'topLevelAwait',
['decorators', {decoratorsBeforeExport: true}],
['pipelineOperator', {proposal: 'smart'}],
];
export const parseOptions = (filePath: string, strictMode = false): ParserOptions | null => {
const fileType = supportedFileType(filePath);
if (fileType === 'ts') {
return {plugins: [...plugins, 'typescript']};
}
const jsOptions: ParserOptions = {plugins: [...plugins, 'flow']};
if (fileType === 'js') {
return jsOptions;
}
// unexpected file extension, for backward compatibility, will use js parser
if (strictMode) {
throw new TypeError(`unable to find parser options for unrecognized file extension: ${filePath}`);
}
return jsOptions;
};