tleunen / babel-plugin-module-resolver

Custom module resolver plugin for Babel
MIT License
3.46k stars 205 forks source link

Location dependent alias? #267

Closed FezVrasta closed 6 years ago

FezVrasta commented 6 years ago

Hi, I'm trying to build several projects into a single bundle, the problem is that each of these projects have the NODE_PATH set to ./src so when I try to compile them all together they can't find their own modules because the NODE_PATH can't be different for each of the projects.

I was wondering if with this plugin there's any way to create roots that gets "activated" only if the requiring file is inside a given directory.

Example:

/apps
/apps/one
/apps/one/index.js
/apps/one/foo.js
/apps/two
/apps/two/index.js
/apps/two/bar.js
.babelrc
// one/index.js
import foo from 'foo.js';
// two/index.js
import bar from 'bar.js;

Is there any way to have foo.js resolve to /apps/one because the requiring file /apps/one/index.js is inside /apps/one, and do the same for the other?

fatfisz commented 6 years ago

There are three solutions I see (TL;DR I recommend the first one):

  1. Set the root option to 'apps' and add change foo.js to one/foo.js, etc. - I think this is the easiest and the least surprising way of working with the plugin.
  2. Set a separate .babelrc for each directory you have, with root pointing always at __dirname - this allows you to keep the paths intact at the tradeoff of having the config duplicated. It also makes it harder for the projects to reference each other unless you add a "fallback" root of apps (so [__dirname, 'apps']). In that case you'd be able to reference paths local to each project and the projects by name (we had this setup at Codility for some time, it messed IDEs up and we went with the solution described in 1.).
  3. Set root to ['apps/one', 'apps/two'] - then the path resolution algorithm will look for the files first in the apps/one directory and if it's not there then in the apps/two directory. I don't think this is ok for a few reasons: this introduces an unobvious order when resolving paths, also hides the problem when you remove a file in one dir and it's still available in another.

There might be other solutions but that was the best I could come up with given that info. Please let us know if this has helped you!

tleunen commented 6 years ago

A different babelrc file per directory with a custom pwd: 'babelrc' might also work here..

If each of them is considered as separate project, it could be good to have a specific babelrc file anyway.

FezVrasta commented 6 years ago

Thanks for the suggestions! I think we can close it then