简体   繁体   中英

What is the right way to create separate npm modules and use them locally

I created a React Native component which lives in a different folder with its own package.json file, and I want to use it in another project

MyComponent is located in Workspace/MyComponent and as a few dependencies in package.json

  "dependencies": {
    "react-navigation": "^1.0.0-beta.11"
  },
  "peerDependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1"
  },
  "devDependencies": {
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1"
  }

I am currently in the development of MyComponent so I have run npm install in the repo, there is a node_modules folder.

My have linked MyComponent with MyApp which is located in Workspace/MyApp , using npm link

Although, when I run MyApp and try to use MyComponent , it complains about duplicated declaration, because react is in both MyComponent and MyApp , and they are linked.

If I remove the node_modules folder from MyComponent , react-navigation complains about react not defined.

In the ReactJS world, webpack for example allow to set the root with the preferred node_modules folder which is great.

module.exports = {
  ...
  resolve: {
    root: path.resolve(__dirname, 'node_modules'),
  }
  ...
}

I wish to do something similar so I don't have duplicated modules and can debug MyComponent in MyApp locally without reinstalling MyComponent for every single change. What is the best approach for me to achieve this?

Thanks

If this is something that will eventually be put in its own repo and then will be installed like any other component, I would probably just build it in the node_modules directory of the parent project. That would prevent you from having to run npm install for every little change.

You can also declare a dependency on a local file and then npm will install it in node_modules

  "dependencies": {
    "my-component": "file:app/components/my-component",
  }

So I have a component that I've built within my project that is referenced in my package.json file. When I run npm install this component is installed in the node_modules folder. That could help with the duplicate library declarations but it wouldn't solve the repeated use of npm install

Update: I just learned that npm 5 doesn't copy the files over to the node_modules folder. It now creates a symlink (basically, a virtual directory that points to the real one) to the code in your project.

This means you will not have to run npm install each time you change your code so it will likely be the best solution for you.

我找到了一个问题的解决方案,它被称为whackage https://github.com/FormidableLabs/whackage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM