Search code examples
reactjsbabeljscreate-react-app

Use Babel plugin that rewrites code after ejecting create-react-app


I created an empty app with create-react-app, ejected, and then added a Babel plugin which rewrites my code. The minimum repro is a plugin that takes:

import React from 'react';
App();

and converts it into:

import React from 'react';
export default () => <div />;

The code which you can test with astexplorer is:

module.exports = function testPlugin(babel) {
  return {
    visitor: {
      CallExpression(path) {
        var t = babel.types;
        var op = t.jSXOpeningElement(t.jSXIdentifier("div"), [], true);
        var el = t.jSXElement(op, null, []);
        var arrowFunctionExpression = t.arrowFunctionExpression([], el);
        path.parentPath.replaceWith(t.exportDefaultDeclaration(arrowFunctionExpression));
      }
    }
  };
};

That works with pretty much any boilerplate (when the plugin is added to the plugins section of the Babel config) except the ejected create-react-app. With it I get:

./src/App.js
Line 2:  'App' is not defined  no-undef

The plugin is definitely running because I can console.log and throw errors within it.

What's going on?


Solution

  • What's going on?

    That error is from ESLint, and ESLint runs on the original source code because it is a code formatting and verification tool. It has no way of knowing that you've written a Babel plugin to perform transformation at built time. All it knows is that you've got a variable named App in your code that isn't declared anywhere.

    Perhaps you could consider telling ESLint that App is a global, in the .eslintrc file, so that the no-undef rule will treat the variable as defined.