Import local packages as modules not in the React-Native project

Viewed 4737

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.

The question

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?

1 Answers

You will need to make your application aware of it through your root package.json files.

Confirm the new local module has a basic package.json configured.

For example:

{
  "name": "foo", 
  "version": "0.0.1"
}

Ensure the package has an index.js and that it has something exported or export default.

For example, at the bottom of the index.js:

export default foo;

Then, simply save the package as a project dependency in your root module to via NPM. To do this and install it automatically into your node_modules you can use this command.

npm install --save file:other_paths/foo

note make sure you have the correct relative path from your general project package.json to your new module package.json.

Example, in this case it would be:

app/                          # a React-Native project root
  |- other_paths/  
  |   |- foo/
  |      |- package.json      # new module package json
  |      |- index.js
  |- src/
  |   |- bar/
  |       |- bar.js
  |- package.json             # project package json

If set up correctly you should then be able reference the module anywhere in your project without relative path.

import Foo from 'foo';

Related