npm – How to create a private npm?

Use case: You have your own React UI library project and you want to use UI components from this lib across other projects

React Native:
publish-your-react-native-package-to-npm
publish-your-first-react-native-npm

React Web:
publishing-a-react-package-to-npm

How to locally install your module project into your app?

Pack your module project

  • Open your module project and run
yarn pack

You will get a compressed file like myreactnativelib-v0.0.1.tgz

  • Open your React app project and run yarn add this compressed file
yarn add /Volumes/data/user/react-native-my-lib/myreactnativelib-v0.0.1.tgz

then, you can see module project is installed inside node_modules folder

How to reuse dependencies in app project for module project?

  • Use peerDependencies in your module project
  • peerDependencies are not included in built module
  • peerDependencies are dependencies that the host app is expected to provide
  • When to use peerDependencies?
    • If dependency that will almost certainly also be a core dependency of those other applications. Ex: React dependency
"peerDependencies": {
  "react": "^17.0.1",
  "react-dom": "^17.0.1"
}

How to specify peer dependencies version?

  • npm package version is set as semantic versioning: major.minor.patch
  • Use tilde (~) to allow newer patch, caret (^) to allow newer minor level versions of a package
  • Specify the versions of a peer dependency that our package can work with, rather than the version we’d prefer to use
// can work with react 16.8 to react 17
"peerDependencies": {
  "react": "16.8 - 17"
}

Why is it error when building module project?

  • When you use peer dependencies, npm will not install those dependencies
  • This leads to errors when you are running tests on your package
  • To void this, include the peer dependencies as dev dependencies
    That way, they will be available for local testing but will still be peer dependencies in the published npm module

Be the first to comment

Leave a Reply

Your email address will not be published.


*