You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
2.2 KiB
67 lines
2.2 KiB
"use strict"; |
|
|
|
Object.defineProperty(exports, "__esModule", { |
|
value: true |
|
}); |
|
exports.default = splitExportDeclaration; |
|
|
|
var _t = require("@babel/types"); |
|
|
|
const { |
|
cloneNode, |
|
exportNamedDeclaration, |
|
exportSpecifier, |
|
identifier, |
|
variableDeclaration, |
|
variableDeclarator |
|
} = _t; |
|
|
|
function splitExportDeclaration(exportDeclaration) { |
|
if (!exportDeclaration.isExportDeclaration()) { |
|
throw new Error("Only export declarations can be split."); |
|
} |
|
|
|
const isDefault = exportDeclaration.isExportDefaultDeclaration(); |
|
const declaration = exportDeclaration.get("declaration"); |
|
const isClassDeclaration = declaration.isClassDeclaration(); |
|
|
|
if (isDefault) { |
|
const standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration; |
|
const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope; |
|
let id = declaration.node.id; |
|
let needBindingRegistration = false; |
|
|
|
if (!id) { |
|
needBindingRegistration = true; |
|
id = scope.generateUidIdentifier("default"); |
|
|
|
if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) { |
|
declaration.node.id = cloneNode(id); |
|
} |
|
} |
|
|
|
const updatedDeclaration = standaloneDeclaration ? declaration : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]); |
|
const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]); |
|
exportDeclaration.insertAfter(updatedExportDeclaration); |
|
exportDeclaration.replaceWith(updatedDeclaration); |
|
|
|
if (needBindingRegistration) { |
|
scope.registerDeclaration(exportDeclaration); |
|
} |
|
|
|
return exportDeclaration; |
|
} |
|
|
|
if (exportDeclaration.get("specifiers").length > 0) { |
|
throw new Error("It doesn't make sense to split exported specifiers."); |
|
} |
|
|
|
const bindingIdentifiers = declaration.getOuterBindingIdentifiers(); |
|
const specifiers = Object.keys(bindingIdentifiers).map(name => { |
|
return exportSpecifier(identifier(name), identifier(name)); |
|
}); |
|
const aliasDeclar = exportNamedDeclaration(null, specifiers); |
|
exportDeclaration.insertAfter(aliasDeclar); |
|
exportDeclaration.replaceWith(declaration.node); |
|
return exportDeclaration; |
|
} |