Search code examples
javascriptbabeljsbabel-loader

Babel Type for 'module.exports'


Im writing a function that uses babel.transform to detect exported modules such as default & named exports.

For the default and named exports I am using the following babel types for detection:

  • ExportDefaultDeclaration

  • ExportNamedDeclaration

But I want to support module.exports which is not detected by either type specified above.

I have tried the DeclareModuleExports type with no luck.

Anyone have any idea of what type I should be using?


Solution

  • There is no AST type for this. A good tool for exploring things like this is ASTExplorer. Here is an example for your code: http://astexplorer.net/#/gist/46c661d47a6e789437d197ba8d7b1ca8/559ef96e774151f76e2b0e7ff36dc9685d574939

    You would have to detect arbitrary accesses to a variable named module, and then look for properties named exports. In a Babel plugin for instance you could have a visitor that looked for

    MemberExpression(path) {
      if (
       path.get("object").isIdentifier({name: "module"}) &&
       path.get("property").isIdentifier({name: "exports"})
      ) {
        // whatever
      }
    },