Picci
Picci

Reputation: 17762

Load an npm package from local directory without copying unnecessary files/folders such as node_modules

Let's imagine I have to develop an npm package, my-package, which needs to be imported and used by my-project.

While developing my-package I need to install and use other packages from npm. At the end of the development of my-package, I bundle all the relevant files in the dist directory. Since I do not want to have all the files in the node_modules folder as part of the package published, I specify in .gitignore (or .npmignore) to exclude node_modules folder. So the final structure of the folder of my-package looks something like

my-package
  dist
    ... // all the code of the package to be distributed
  node_modules
    ... // all the node modules
  src
    ... // all source files
  package.json
  .gitignore

Now I publish my-package on npm repository and then import it in my-project, with the command npm i my-package.

As a result of such import, the structure of the directory hosting my-project is something like

my-project
   ...  // stuff
   node_modules
      my-package
         dist
           ... // all the code of the package to be distributed
         src
           ... // all source files
         package.json

As expected, no node_modules folder is imported under my-package folder.

Since I am the developer of both my-package and my-project, during development I would like to import my-package from the local path with a command which could look like

npm -i ../my-package

If I proceed like this, the result I see is that all the files and folders stored under my-package directory are copied under the node_modules folder of my-project, i.e. .gitignore (or .npmignore) exclusions are not considered. The net result is a structure such as

my-project
   ...  // stuff
   node_modules
      my-package
         dist
           ... // all the code of the package to be distributed
         node_modules
           ... // all stuff imported by my-package
         src
           ... // all source files
         package.json
         ...  // any other file under my-package

Is there a way to install from local path only the relevant files of my-package as it happens if the package is installed from the npm repository?

Upvotes: 8

Views: 5401

Answers (1)

Alfrex92
Alfrex92

Reputation: 6778

We had the same problem today. We figure it out by adding to the package.json of the local package

“build”: “yarn run clean && yarn build-components && yarn pack”

And then to the project that is using the local package we added to the dependencies of the package.json

“yourpackage”: “file:../your-tgz.tgz”,

hope it helps

Note: if you are using yarn you might have problems with the cache.

Upvotes: 4

Related Questions