Adam Arold
Adam Arold

Reputation: 30528

How to configure Babel to properly work with multiple folders?

I have been using Babel for a while now and it properly converts my ES Next code to the dist folder with this command:

babel src --out-dir dist --source-maps --copy-files

So far I had all my Javascript code in src, but now I want to move my React views to the views folder next to src. I modified the Babel CLI call to this:

babel src views --out-dir dist --source-maps --copy-files

Now my problem is that while the files are compiled properly none of the imports are. For example in my file Navigation.js I have this import:

import Permissions from "../src/utils/permissions";

and this will get converted into

var _permissions = _interopRequireDefault(require("../src/utils/permissions"));

after Babel runs.

How do I configure Babel to fix the imports when I'm working with multiple source directories?

Upvotes: 1

Views: 2282

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10676

I'm not sure babel can accomplish this on its own. Its a great tool for transpiling, but think of it as a relentlessly faithful translator. It will transpile your code, but will not reinterperet your import statements based on your desired output locations and relationships, as far as I know. So you have 2 options:

  1. If using babel only, maintain the relationships between files in your source code and desired output. For example, if you want all files in /src and src/views to end up on the same level in dist, then you might want to have a folder structure like this:
/src
  - /src
  - /views

The naming here is a little redundant, I know. But with babel src/src src/views --out-dir dist --source-maps --copy-files, all your files will be transpiled to the same level in /dist, and the import relationships will all stay correct.

  1. Use a build tool. Webpack is an even more robust tool, which itself often employs babel. Webpack is smart enough to re-write your import statements in the bundled code based on how you configure it. The question How to create multiple output paths in Webpack config is well answered. Webpack is a world unto itself, but is powerful enough to accomplish what you want, if you know how to use it.

I'm hoping someone will come along and tell me I'm wrong and that there is some perfect-for-this-scenario-rewrite-imports-babel-plugin that does the job. Here's hoping. Otherwise I think you have to restructure, or dive into webpack.

Upvotes: 1

Related Questions