Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markerikson/b725f4cb51e63582fec56cf2635a362d to your computer and use it in GitHub Desktop.
Save markerikson/b725f4cb51e63582fec56cf2635a362d to your computer and use it in GitHub Desktop.
babel-plugin-reexport-named-as-default
// This file totally hacked together from https://github.com/jfeldstein/babel-plugin-export-default-module-exports
module.exports = ({types : t}) => ({
visitor: {
Program: {
exit (path) {
if (path.BABEL_PLUGIN_EXPORT_DEFAULT_MODULE_EXPORTS) {
return
}
let hasExportDefault = false
let hasExportNamed = false
let namedExports = []
path.get('body').forEach((path) => {
if (path.isExportDefaultDeclaration()) {
hasExportDefault = true
return
}
if (path.isExportNamedDeclaration()) {
if (path.node.specifiers.length === 1 && path.node.specifiers[0].exported.name === 'default') {
hasExportDefault = true
} else {
hasExportNamed = true
const {declarations} = path.node.declaration
const [firstDeclaration = {}] = declarations
namedExports.push(firstDeclaration.id.name)
}
return
}
})
if (!hasExportDefault && hasExportNamed) {
const objectProperties = namedExports.map (name => t.objectProperty(
t.identifier(name),
t.identifier(name),
false, true
))
const objDeclaration = t.variableDeclaration("const",
[t.variableDeclarator(
t.identifier("namedExports"),
t.objectExpression(objectProperties)
)]
)
const exportDefaultDeclaration = t.exportDefaultDeclaration(
t.identifier("namedExports")
)
path.pushContainer("body", [
objDeclaration,
exportDefaultDeclaration
])
}
path.BABEL_PLUGIN_EXPORT_DEFAULT_MODULE_EXPORTS = true
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment