In a React-Native project, I found that if your local package has a valid package.json file, you can import that like a module in node_modules without a relative path .
For example,
app/ # a React-Native project
|- any_folder_for_packages/
| |- foo/
| |- package.json
| |- index.js
|- src/
| |- bar/
| |- bar.js
|- ...
In this case, you can import the package foo in the bar.js using either:
// with a relative path
import foo from '../../any_folder_for_packages/foo';
or
// like a module (without a relative path)
import foo from 'foo';
The packager will try to find and use any local module which contains a package.json matching the requirement.
I have a local package which is not in the React-Native project, how can I import it
projects/
|- app/ # a React-Native project
| |- src/
| | |- bar/
| | |- bar.js # need to import the package foo as a module which is not in this project
| |- ...
|- other_paths/
|- foo/
|- package.json
|- index.js
I tried to use
// like a module (without a relative path)
import foo from 'foo';
but it failed to find the module.
How can I use react-native to find the package when packing for development or bundling for the production?
Answer given by @Plague doesn't work in react native. You have to configure your metro.config.js file to use a local package.
If Using Expo
In expo, metro.config.js file may not be visible, so in the root directory of your project, run this command;
npx expo customize metro.config.js
This will generate the file for you with some default configuration. Now to import any package, you have to modify two things here;
config.resolver.nodeModulesPaths, to include the package, and ;
config.watchFolders to keep a watch on the package.
In nutshell, metro.config.js file should be like this;
// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require("expo/metro-config");
const config = getDefaultConfig(__dirname);
const packagePath = "/full/path/to/package";
// here i added the packagePath to the list in the configuration to include it
config.resolver.nodeModulesPaths.push(packagePath);
// here i added the package again to another configuration key, to keep a watch on it if we make any changes.
config.watchFolders.push(packagePath);
module.exports = config;
That is it, but your code editor may report that module is not found, for that warning to remove, you can just run the command below;
npm install /path/to/package
BUT there is a problem with this
The dependencies in our package conflicts with that of main project.
So here is another way of installing a local package.
Using install-local
For this we don't need to make any changes to any file. We just need to install this package;
npm install install-local
And then install the local package using this;
npx install-local --save path/to/package
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With