It looks like there is a slightly more official way to do this facebook/create-react-app#476
Besides differences with Windows, importing from a symlink seems to break Jest. So probably better to use the NODE_PATH
method as described in the link above, rather than this.
So here's the problem, you're working in a file, let's say:
├── my-project
│ └── src
│ ├── cool-module
│ │ └── index.js
│ └── lib
│ ├── helpers.js
│ └── super-lib
│ └── lib-1.js <--- working in this file
And you want to import stuff from a parent directory. Typically you'd get a lot this going on:
import helpers from '../helpers'
import coolModule from '../../cool-module'
This is kind of gross and kind of brittle. As soon as you move some files around you might also have to update these relative import paths.
Wouldn't it be nice to have a shortcut to your project's src
directory that Webpack understands without changing any config? So you could do something like:
import helpers from '@/lib/helpers'
import coolModule from '@/cool-module'
Well, with the power of symlinks, you can! No need to add any plugins or update any Webpack config at all. Works with Create React App with zero changes without ejecting!
note: the following commands should be run from your project root, in this example from the my-project
directory
Create a node_modules
directory inside your src
directory, like so:
mkdir src/node_modules
Next create a symlink in src/node_modules/
pointing to its relative parent directory, which in this case is src
:
ln -s ../ src/node_modules/@
The symlink I'm creating is named @
, but you could use any valid character or symbol.
I often structure my larger React projects with a set of high-level submodules inside my src
directory, like:
├── my-project
│ └── src
│ ├── app
│ ├── submodule-1
│ ├── submodule-2
│ └── submodule-3
And then symlink @
to src/app
and @submodule-1
to src/submodule-1
, etc... Like:
├── my-project
│ └── src
│ └── node_modules
│ ├── @ -> ../app/
│ ├── @submodule-1 -> ../submodule-1/
│ ├── @submodule-2 -> ../submodule-2/
│ └── @submodule-3 -> ../submodule-3/
What I like about this symlink trick is that you're free to configure your project exactly the way you like wihtout adding another plugin or package, or updates to your Webpack config.
Instruction won't work on Windows, because command for creating symlinks is different.
Mac/Linux: ln -s ../ src/node_modules/@
Windows: mklink /d ../ src/node_modules/@
I think that's the only difference.