-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(docz-utils): add exports parser to add to Playground scope
- Loading branch information
1 parent
99ebf82
commit 9c564d0
Showing
2 changed files
with
44 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import * as parser from '@babel/parser' | ||
import traverse from '@babel/traverse' | ||
import get from 'lodash/get' | ||
|
||
const fromDeclarations = (declarations: any = []) => | ||
Array.isArray(declarations) && declarations.length > 0 | ||
? declarations.map(declaration => get(declaration, 'id.name')) | ||
: [] | ||
|
||
const traverseOnExports = (fn: (path: any) => any[]) => (node: any) => { | ||
try { | ||
const ast = parser.parse(node.value, { | ||
sourceType: 'module', | ||
}) | ||
let populated: any[] = [] | ||
traverse(ast, { | ||
enter(path: any): void { | ||
if (path.isExportDeclaration()) { | ||
populated = populated.concat(fn(path)) | ||
return | ||
} | ||
}, | ||
}) | ||
return populated | ||
} catch (err) { | ||
return [] | ||
} | ||
} | ||
|
||
export const getExportsVariables = traverseOnExports(path => { | ||
const type = get(path, 'node.declaration.type') | ||
switch (type) { | ||
case 'VariableDeclaration': | ||
return fromDeclarations(get(path, 'node.declaration.declarations', [])) | ||
case 'FunctionDeclaration': | ||
const declaration = get(path, 'node.declaration', false) | ||
return fromDeclarations(declaration ? [declaration] : []) | ||
case 'Identifier': | ||
return get(path, 'node.declaration.name') | ||
default: | ||
console.error(`Unexpected export type ${type} in docz-utils/exports`) | ||
} | ||
}) |
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