Search code examples
node.jsnpmnpm-package

How to merge two npm packages as one


I have created a new npm package. Let's say my new package name is my-package. I need to import bootstrap npm package into my-package. How to import Bootstrap package into my-package? Also I need to change some color variables in bootstrap package to match my-package. When I do npm install my-package it should install my-package and bootstarp package as one package. I don't want to install my-package and bootstrap package separately but install or merge both packages as my-package. Any suggestions and thanks.


Solution

  • This question sounds like it is rooted in the difference between dependencies and peerDependencies.

    In the package.json for the my-package package, you can define bootstrap as either a dependency or peerDependency.

    If bootstrap is included as a peerDependency, then it will require anyone who uses your package to also install bootstrap as well. This will result in their package tree looking like this:

    ➜  consumer npm ls
    consumer@1.0.0 /private/tmp/consumer
    ├── bootstrap@4.5.2
    ├── jquery@3.5.1
    ├── my-package@^1.0.0
    └── popper.js@1.16.1
    

    Note how the consuming project is required to have a dependency for not only my-package, but also bootstrap and all the bootstrap peer dependencies as well.

    To accomplish what you want, the package.json for the my-package lib should include those as its own dependencies. e.g.

    {
      "name": "my-package",
      "dependencies": {
        "bootstrap": "^4.5.2",
        "jquery": "^3.5.1",
        "popper.js": "^1.16.1"
      }
      ...
    }
    

    By doing this, any project that consumes my-package will be able to specify only my-package as a dependency and all nested dependencies will be grabbed as well. Here is what the dependency tree looks like with the above:

    ➜  consumer npm ls
    consumer@1.0.0 /private/tmp/consumer
    └─┬ my-package@1.0.0 -> /private/tmp/my-package
      ├── bootstrap@4.5.2
      ├── jquery@3.5.1
      └── popper.js@1.16.1
    

    As for changing the colors used for bootstrap, you can follow the theming documentation for the version you are using to accomplish this: https://getbootstrap.com/docs/4.5/getting-started/theming/