npmmonoreponpm-workspaces

NPM Workspaces monorepo - share local package's distribution folder as root instead of the entire source files


Using NPM Workspaces, I'm sharing one package (components) with others (webapp1 and webapp2). Something like this:

root
  apps   
    webapp1
    webapp2
  packages
    components

Everything is working well, but everything inside components, include source code in the src folder is being shared. Since components' compiled output folder is dist, I'd like to only share that folder. This is how it looks in the root node_modules:

enter image description here

The problem is that when I need to import in webapp1 or webapp2, my import path has to include the dist folder. Here's the intellisense that I get from VS Code:

enter image description here

And this is how I import in webapp1 and webapp2:

import Center from '@mycompany/components/dist/Center'

While everything works, how can I set up my NPM Workspaces so that only the contents of the dist folder is shared in its root?

I've tried NPM's files and .npmignore inside the components folder to ignore everything except for the dist folder, but that doesn't seem to work. The main property in package.json for components is also set to point to dist/index.js:

"main": "dist/index.js"

Interestingly, if I want to import dist/index.js file, I can do it without dist:

import foo from '@mycompany/components'

...however, importing anything other than dist/index.js requires dist to be included in the path.


Solution

  • You should treat the packages folder as a collection of dist folders in your use case.

    In this scenario, you would move your packages/components/src folder somewhere else in your project and then build to packages/components instead of packages/components/dist

    root
      apps   
        webapp1
        webapp2
      packages
        components
      src
        components
    

    I have a similar setup in this tooling monorepo I created