Import components outside the root folder with babel

Viewed 767

I have multiple projects in react in a monorepo: app1 app2 app3, and each app is built with webpack and babel.

I want to create a shared directory with shared components between the apps, so I created in the monorepo another directory shared.

( I executed in each project npm i ../shared )

But when I import componets from shared inside one the of the apps, babel throws an exception: Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation. If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

NOTE: if I import simple functions from shared it works, only when importing components it does not work.

What configuration can I add so I can create a shared directory with shared components?

The .babelrc file I have in each app looks like this

{
   "presets": [
    [
        "@babel/preset-env",
        {
            "targets": {
                "browsers": ["chrome >= 50"]
            },
            "useBuiltIns": "usage",
            "corejs": 3
        }
    ],
    "@babel/preset-react",
    "@babel/preset-typescript"
    ],
    "plugins": ["@babel/plugin-syntax-jsx", "@babel/plugin-transform-react-jsx", "@babel/plugin-transform-runtime"]
}
2 Answers

It appears, this is more of a webpack and less of a babel problem. The error pops up, because your babel-loader is not configured correctly.

When adding "external folders/modules" to your build, you usually want to do (or at least check) the following:

  1. Add the shared folder's src folder to your babel-loader's include (if it is not already included)
    • -> This makes sure, things get babel'ed nicely, and your preset-react will actually work).
    • -> Make sure not to include too much (e.g. never include any node_modules folder in its entirety, or things will slow down abysmally).
  2. You might also have to add the shared folder to your babel-loader's babelrcRoots, because else, it will ignore its .babelrc.js file (if it is different from your babel-loader's default config), and thus only use default settings, ignoring your preset-react.
  3. Often times, you also need to add the shared folder's src folder to your webpack.config's resolve.modules:
    • -> This allows webpack to do it's resolve magic inside that folder as well.
    • If it has its own node_modules, also add that to resolve.modules.
    • For more info on this particular issue, see here.
Related