UNPKG

@zohodesk/docs-builder

Version:

docs-builder is used to build your own docs

56 lines (46 loc) 1.88 kB
const parser = require('@babel/parser'); const traverse = require('@babel/traverse').default; const t = require('@babel/types'); const generate = require('@babel/generator').default; function importOptimiser(source) { const ast = parser.parse(source, { sourceType: 'module', plugins: ['jsx'] }); const importMap = new Map(); traverse(ast, { ImportDeclaration(path) { const node = path.node; const importPath = node.source.value; const namedSpecifiers = node.specifiers.filter((spec) => t.isImportSpecifier(spec)); const defaultSpecifier = node.specifiers.find((spec) => t.isImportDefaultSpecifier(spec)); if (namedSpecifiers.length > 0 || defaultSpecifier) { const namespaceIdentifier = path.scope.generateUidIdentifierBasedOnNode(t.identifier(importPath)).name; namedSpecifiers.forEach(spec => { importMap.set(spec.local.name, `${namespaceIdentifier}.${spec.local.name}`); }); if (defaultSpecifier) { importMap.set(defaultSpecifier.local.name, `${namespaceIdentifier}.default`); } const newImportDeclaration = t.importDeclaration( [t.importNamespaceSpecifier(t.identifier(namespaceIdentifier))], t.stringLiteral(importPath) ); path.replaceWith(newImportDeclaration); } }, ObjectProperty(path) { if (t.isIdentifier(path.node.value) && importMap.has(path.node.value.name)) { path.node.value = t.identifier(importMap.get(path.node.value.name)); } }, Identifier(path) { if (importMap.has(path.node.name) && !t.isObjectProperty(path.parent)) { path.replaceWith(t.identifier(importMap.get(path.node.name))); } } }); const transformedCode = generate(ast, {}, source).code; return transformedCode; } module.exports = importOptimiser;