Created
February 3, 2018 23:24
-
-
Save parshap/cfb17c1db124b48ee5512f2c56f023c8 to your computer and use it in GitHub Desktop.
Get a module's default export from a Babel AST
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 t = require('babel-types'); | |
const assert = require('assert'); | |
/** | |
* Is `module.exports` expression | |
*/ | |
const isModuleExportsMemberExpression = (node) => { | |
t.assertMemberExpression(node); | |
t.assertIdentifier(node.object); | |
assert.equal(node.object.name, 'module'); | |
t.assertIdentifier(node.property); | |
assert.equal(node.property.name, 'exports'); | |
}; | |
/** | |
* Get a simple module's default export. The expected form of the module is: | |
* | |
* module.exports = { ... } | |
* | |
*/ | |
const getModuleExport = (node) => { | |
// Assert sure the file is simply `module.exports = { ... }` | |
t.assertFile(node); | |
t.assertProgram(node.program); | |
assert.equal(node.program.body.length, 1); | |
t.assertExpressionStatement(node.program.body[0]) | |
t.assertAssignmentExpression(node.program.body[0].expression); | |
assert(isModuleExportsMemberExpression(node.program.body[0].expression.left)); | |
// Return the exported object | |
return node.program.body[0].expression.right; | |
}; |
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 traverse = require('babel-traverse').default; | |
const t = require('babel-types'); | |
const assert = require('assert'); | |
/** | |
* Is `module.exports` expression. | |
*/ | |
const isModuleExportsMemberExpression = (node) => { | |
t.assertMemberExpression(node); | |
t.assertIdentifier(node.object); | |
assert.equal(node.object.name, 'module'); | |
t.assertIdentifier(node.property); | |
assert.equal(node.property.name, 'exports'); | |
}; | |
/** | |
* Get a simple module's default export. The expected form of the module is: | |
* | |
* module.exports = { ... } | |
* | |
*/ | |
const getModuleExport = (node) => { | |
let node; | |
traverse(node, { | |
AssignmentExpression(path) { | |
if (isModuleExportsMemberExpression(path.node.left)) { | |
node = path.node.right; | |
} | |
} | |
}); | |
return node; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two different ways of doing this -- is there a better way?