node.jsnpmworkspacemonorepo

Npm workspaces - call workspace script from root package


I'm struggling with multiple npm packages in a root git repository with custom dev scripts to handle launch, compile, build and so on. Now I came across npm workspaces and wanted to use this stunning new feature in my following project structure but I can't get it to work:

projectx (root)
- package.json
- apps   
 -- backend
   -- src
   -- package.json (name: @projectx/backend, scripts: "dev":"ts-node or whatever")
 -- common
   -- src
   -- package.json (name: @projectx/common)
 -- frontend
   -- src
   -- package.json (name: @projectx/frontend, scripts: "dev":"webpack")

My root package.json contains:

    {
  "name": "packagex",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "private": "true",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "back:dev": "npm workspace @projectx/backend dev",
    "front:dev": "npm workspace @projectx/frontend dev",
    "dev": "run-p back:dev front:dev"
  },
  "workspaces": [
    "apps/*"
  ],
  "repository": {
    "type": "git",
    "url": "git_url"
  },
  "author": "me",
  "license": "ISC",
  "devDependencies": {
    "npm-run-all": "^4.1.5"
  }
}

And now I want to start backend and frontend with npm-run-all and the command on root: npm run dev which results in:

Screenshot of terminal output

And I also want to share the common package with backend and frontend, which should be possible in this case. Maybe anobody else is facing the same problem or has some ideas what I am doing wrong here.


Solution

  • Your "workspaces" property in package.json looks right. I'm using NPM Workspaces and it's working well, but it's still missing a lot of features so you need to wire things up yourself. I also don't think npm worksace is a command (but maybe for the future?), so here's a checklist to get it to work:

      "scripts": {
        "back:dev": "cd apps/backend && npm run dev",
        "front:dev": "cd apps/fontend && npm run dev",
        "dev": "npm-run-all build --parallel back:dev front:dev"
      }
    

    Then start it with npm run dev.

    Note, you may want to consider using start scripts instead of dev to shorten the command you need to type (e.g. npm start instead of npm run dev), but npm run dev will still be fine.