babel 7 ignores files outside of current directory

Viewed 1307

Say I have following project structure (Well its more complex than below structure):

  • CommonComponents
    • CommonComponentA
    • CommonComponentB
    • package.json
    • webpack.config.js
    • .babelrc
  • ModuleA
    • ComponentC //import CommonComponentA
    • ComponentD
    • package.json
    • webpack.config.js
    • .babelrc
  • ModuleB
    • ComponentE //import CommonComponentB
    • ComponentF
    • package.json
    • webpack.config.js
    • .babelrc

I compile, bundle and utilize ModuleA and ModuleB separately. When I switched to babel 7, importing modules from CommonComponents directory stopped working. Babel ignores files which are outside current working directory and doesn't transpile them so webpack compilation fails complaining 'Unexpected token' at imported component.

From what I have understood so far, they have changed the way .babelrc lookup happens. I really can't wrap my head around the terms 'root', 'babelrcRoots', etc. Can someone explain what I will need to do in order to compile ModuleA and ModuleB succesfully from their respective working directory ?

1 Answers

Based on the real structure of your project (it is a monorepo setup with a root folder?) and the webpack config you are using, you can have several ways to solve this, one way could be by adding the include key on you babel loader rule on webpack configuration files, you will end up with something like this:

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      include: path.resolve(__dirname, '../CommonComponents'),
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
  ]
}

as stated before, this depends on your real project structure, but you can give it a try and check it works.

Related