0

I'm using Babel to package my module but I'm running into a problem with React dependency. Since some version of React, it's no longer required to explicitly import it to use JSX, and my formatter config takes full advantage of that by stripping unnecessary import statements. This works just fine in my webpack build.

However, when I use Babel to produce dist folder for the package, I end up with code like this

var colored = function colored(text, color) {
  return text != null && /*#__PURE__*/React.createElement("span", {
    className: "color-".concat(color)
  }, text);
};

This obviously uses React, but it's not imported anywhere! And as expected, it crashes on runtime.

My babel config:

{
  "presets": [
    [
      "react-app",
      {
        "absoluteRuntime": false
      }
    ]
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./src"],
        "alias": {
          "@": "./src"
        }
      }
    ],
    [
      "babel-plugin-transform-remove-imports",
      {
        "test": "\\.(css|scss)$"
      }
    ],
    [
      "@babel/plugin-transform-typescript",
      {
        "allowDeclareFields": true
      }
    ]
  ]
}
NODE_ENV=production babel src --out-dir dist --copy-files --extensions \".ts,.tsx\" --config-file ./babel-build.config.json
riv
  • 6,846
  • 2
  • 34
  • 63

1 Answers1

0

Adding "runtime": "automatic" to react-app preset fixed it. Though I'm not sure why I have to specify it in both my custom config file used for babel CLI, and in the package.json (it seems package.json overrides custom config?)

riv
  • 6,846
  • 2
  • 34
  • 63
  • If babel is anything like prettier, there will be an order it uses to pick a configuration. Its likely that if its listed in Package.json, that is the config babel will use, even if you have a config file elsewhere. Jest is much the same. Either or, you only need one configuration, so either remove the babel.config or the babel listing in your Package.json. There is also a plugin for a react preset which you could replace your preset with. ```{ "presets": [ ["@babel/preset-react", { "runtime": "automatic" }] ] }``` – Vayne Valerius Jun 06 '23 at 12:04
  • If you change the preset to what I've suggested, you can stop importing React from 'react' in your files too. https://stackoverflow.com/questions/64656055/react-refers-to-a-umd-global-but-the-current-file-is-a-module/76365716#76365716 – Vayne Valerius Jun 06 '23 at 12:07