Created
November 27, 2018 12:53
-
-
Save muzea/a3ed3415ca495be401e11aed0d197d5b to your computer and use it in GitHub Desktop.
sample import info
This file contains hidden or 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
const glob = require('glob') | |
const { transformFileSync } = require('@babel/core') | |
const t = require('@babel/types') | |
const fileList = glob.sync(process.argv[2]) | |
const presets = [ | |
'@babel/preset-typescript' | |
] | |
const { ast } = transformFileSync(fileList[0], { ast: true, presets, babelrc: false }); | |
function getMapInfo(list) { | |
const ret = { | |
import: [], | |
export: [], | |
} | |
function findRef(name) { | |
const item = ret.import.find(importItem => importItem.name === name) | |
if (item) { | |
return `${item.source}|${item.orighName}` | |
} | |
return null | |
} | |
list.forEach((item) => { | |
if (t.isImportDeclaration(item)) { | |
item.specifiers.forEach((specify) => { | |
if (t.isImportDefaultSpecifier(specify)) { | |
ret.import.push({ | |
source: item.source.value, | |
name: specify.local.name, | |
orighName: 'default' | |
}) | |
} | |
if (t.isImportSpecifier(specify)) { | |
ret.import.push({ | |
source: item.source.value, | |
name: specify.local.name, | |
orighName: specify.imported.name | |
}) | |
} | |
if (t.isImportNamespaceSpecifier(specify)) { | |
ret.import.push({ | |
source: item.source.value, | |
name: specify.local.name, | |
orighName: '*' | |
}) | |
} | |
}) | |
} | |
// code | |
if (t.isExportDefaultDeclaration(item)) { | |
const exportItem = { | |
name: 'default' | |
} | |
if (t.isIdentifier(item.declaration)) { | |
const ref = findRef(item.declaration.name) | |
if (ref) { | |
exportItem.ref = ref | |
} | |
} | |
ret.export.push(exportItem) | |
} | |
if (t.isExportNamedDeclaration(item)) { | |
item.specifiers.forEach((specify) => { | |
if (t.isExportSpecifier(specify)) { | |
const exportItem = { | |
name: specify.exported.name, | |
} | |
const ref = findRef(specify.local.name) | |
if (ref) { | |
exportItem.ref = ref | |
} | |
ret.export.push(exportItem) | |
} | |
}) | |
} | |
}) | |
return ret | |
} | |
console.log(getMapInfo(ast.program.body)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment