Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distributing NPM Scripts With A Package For Use By Project Installing It

I have moved all my linting configuration and related packages/plugins/presets (for prettier, stylelint, eslint, commitlint) out to an npm package. I then use this package in multiple projects and extend or merge over the config into local configuration files for the projects to ensure consistency and remove the need for installing and keeping my development dependencies up to date.

Alongside the config I have a number of useful npm scripts that run the linters and perform a variety of other development related functionality, for example:

"lint:prettier": "prettier 'src/**/*.{js,json}' --write",
"lint:eslint": "eslint 'src/**/*.js'",
"lint:compatibilityCheck": "eslint --print-config .eslintrc.js | eslint-config-prettier-check",
"lint": "npm run lint:compatibilityCheck && npm run lint:prettier && npm run lint:eslint"

These are currently duplicated across all my projects, but I'd like to distribute these scripts along with my shared package so they are defined in a single location. How should I do this?

like image 449
Undistraction Avatar asked Sep 10 '18 12:09

Undistraction


2 Answers

From npm blog, it seems that there are no "direct ways" to expose dev scripts in an npm package. The blog post suggests creating JavaScripts files that run your preferred scripts using shelljs module.

Example: assuming you want to expose lint:prettier": "prettier 'src/**/*.{js,json}' --write"

wrap the call inside bin/lintprettier.js:

#! /usr/bin/env node
var shell = require("shelljs");
const path = require("path")

process.env.PATH += (path.delimiter + path.join(process.cwd(), 'node_modules', '.bin'));
shell.exec("prettier 'src/**/*.{js,json}' --write");

Then add it to the exported console scripts in your package.json:

...
"bin": {
   "lint-prettier": "bin/lintprettier.js"
}
...

Finally, you can reuse your script in your project:

"scripts": {
   "build": "...",
   "lint:prettier": "lint-prettier"
 }
like image 81
Cristiano Avatar answered Oct 21 '22 13:10

Cristiano


One way you can do it is with Builder.

Builder allows you to ship npm scripts as NPM packages, and run them in any project in which you've installed that package containing the scripts.

In my use cases, I put all my build/test/lint scripts in an NPM package, then I install this one package in all of my other projects. Then in each project I can run the exact same commands.

Builder is not highly-maintained lately, but it is fairly stable, and I've used it with much success. The README is very thorough, and describes just about everything you need to know.

Cristiano's answer is nice too though, as going with that approach may let you be more in control of the solution implementation, whereas with Builder it is another project with its own implementation (and few issues).

like image 20
trusktr Avatar answered Oct 21 '22 13:10

trusktr