kentcdodds / nps-utils

Utilities for http://npm.im/nps (npm-package-scripts)
https://doclets.io/kentcdodds/nps-utils/master
MIT License
101 stars 23 forks source link

Helpers for multi-packages #22

Closed mikecann closed 6 years ago

mikecann commented 6 years ago

Hey guys.

Firstly thanks for all the hard work, this is a great tool.

I thought you or others might find this helpful when dealing with multi-package situations (think lerna or yarn workspaces) which are becoming more and more popular these days.

In your root package-scripts.js:

const utils = require('nps-utils');
const series = utils.series;

const importPackage = (package) => {
  var scripts = require("./packages/"+package+"/package-scripts.js");
  var replace = (obj, prefix) => {
    var retObj = {};
    for(var key in obj) {

      if (typeof obj[key] === "string")
        retObj[key] = series("cd packages/"+package, "yarn start "+prefix+key);
      else
        retObj[key] = Object.assign({}, replace(obj[key], key+"."));
    }
    return retObj;
  }
  return replace(scripts.scripts, "");
}

module.exports = {
  scripts: {
    client: importPackage("client"),
    server: importPackage("server"),
    shared: importPackage("shared"),
  }
}

This then makes all your sub-package scripts available at the top level.

So now you can just type yarn start client.build or yarn start server.test without having to cd in there first.

Obviously this assumes that you are running nps on all your sub-packages too.

Probably this could be vastly improved to:

kentcdodds commented 6 years ago

Hi @mikecann, Thanks for the issue. I think this is a great little helper method and I'd be happy to accept a pull request to add it :)

Thanks!

mikecann commented 6 years ago

Hi Kent,

Id love to do a PR, not exactly sure when im going to find time, but ill try :)