Create-react-app: Solving the `../../../` problem.

Created on 30 Nov 2017  路  6Comments  路  Source: facebook/create-react-app

Is it possible to support importing local modules relative to the root directory (or something along those lines) without ejecting? In other words, go from this:

import bar from '../../../foo/bar';

to this:

import bar from 'foo/bar'; // or '@foo/bar', or '@bar', or what have you

I have done this before with create-react-native-app after ejecting by using the babel-plugin-module-resolver.

This can also be accomplished using Webpack aliases.

question

Most helpful comment

NODE_PATH doesn't seem like the right solution, as it's very sensitive to local environments.

Is there a reason why paths.appSrc isn't added to resolve as a default source path? That seems like a much better solution that provides absolute paths out of the box, and isn't fragile based on user environment/configuration.

All 6 comments

Well, you can create a .env file on the root of your project and make the NODE_PATH point to the src folder (or wherever you have your code) all you'll have to do is write:

NODE_PATH=src

CRA will read your .env file without ejecting.

@Timer Was this closed because using NODE_PATH, which some would consider confusing or an anti-pattern, is really the only way to accomplish this?

Yes, NODE_PATH is the only way without ejecting.
If you'd like more context/information on this topic, feel free to search for previous issues.

image

@Timer I had already searched through the issues! ... with the wrong query. I'll be damned: #2188

NODE_PATH doesn't seem like the right solution, as it's very sensitive to local environments.

Is there a reason why paths.appSrc isn't added to resolve as a default source path? That seems like a much better solution that provides absolute paths out of the box, and isn't fragile based on user environment/configuration.

Until CRA supports providing alias, I'm going with with adding an symlink inside node_modules/.
I'm fairly fine with adding a single alias @: src, so I ended up adding this to packages.json:

"postinstall": "ln -sf ../src node_modules/@"
Was this page helpful?
0 / 5 - 0 ratings

Related issues

wereHamster picture wereHamster  路  3Comments

oltsa picture oltsa  路  3Comments

alleroux picture alleroux  路  3Comments

alleroux picture alleroux  路  3Comments

fson picture fson  路  3Comments