Martin
Martin

Reputation: 242

Importing react module from /src not node_modules

I was using react rc-tree module in my project by importing it like this:

import Tree, { TreeNode } from 'rc-tree';

This worked fine. However after a while I wanted to make changes to the source code of rc-tree, so I cloned the source code from github into my ./src directory. i.e. I now have a directory called ./tree under my ./src directory. How do I call that code, rather than rc-tree in node_modules?

I have tried various import statements but nothing works.

Upvotes: 1

Views: 2594

Answers (3)

Martin
Martin

Reputation: 242

I couldn't get these suggestions to work, probably my fault... so I just moved the entire rc-tree sub directory from node_modules to under my source tree and called it "tree". I then made a sym-link from node_modules/rc-tree to the ./tree in my source tree.

I just import Tree, TreeNodes etc, like I am using the module, but really it's calling the copy of the code in ./tree.

It all seems to work. The only thing that is not so good is that because the code is now under ./src the linter prints many warnings about the code. Obviously it is not my code, and I would rather not hear about it, but I can live with this.

Upvotes: 0

Alireza
Alireza

Reputation: 2449

You should try to relative import your code. Think if you are in this path src/component/childComponent/ where you import your desire package and here you must use a relative path to the package which is inside src.

import Tree, { TreeNode } from '../../tree';

this .. indicates that you go backward inside your current path. In this example, it means to go up two directories (component and childComponent). here now you are addressing src directory you should write the rest of your path which is /tree.

I take look at rc-tree package and noticed it has been written with typescript. If your app doesn't support typescript you can't use source code of the package and you should build package first and then import build directory.

In case your app supports absolute paths you can easily use:

import Tree, { TreeNode } from 'src/tree';

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

Add .env file in root and add this line

NODE_PATH=src

Now import

import Tree, { TreeNode } from 'tree';

Upvotes: 1

Related Questions