Detecting in a babel plugin whether a file is a module or a script

51 Views Asked by At

I'm writing a babel plugin that adds a polyfill at the top of a module.

I'd like to use one strategy for EcmaScript modules, and assume otherwise that its a CommonJS module.

So I've got something like

module.exports = function moduleKeysBabelPlugin({ types: t }) {
  return {
    name: 'my plugin',
    visitor: {
      Program(path) {
        // TODO: If there's a top-level export do something else.
        // require('my-polyfiller/commonjs').polyfill(module, require);
        const polyfill = t.expressionStatement(
          t.callExpression(
            t.memberExpression(
              t.callExpression(
                t.identifier('require'),
                [ t.stringLiteral('my-polyfiller/commonjs') ]),
              t.identifier('polyfill')),
            [ t.identifier('module'), t.identifier('require') ]));
        path.unshiftContainer('body', polyfill);
      },
    },
  };
};

which lets me handle CommonJS.

How would I express the

// TODO: If there's a top-level export do something else.

part?

I could visit and see if I see any Export*Declaration, but that seems too late to be useful.

I could try and walk the children but that doesn't seem very visitorish.

Is this a job for separate enter and exit steps?

Program: {
  enter() {
    sawTopLevelExports = false
  },
  exit(path) {
    if (sawTopLevelExports) {
      ...
    } else {
      ...
    }
  }
}

?

What's the idiomatic way to do this in Babel?

0

There are 0 best solutions below