Run a script (like postinstall) after npm installing a single package? - npm

I'm starting to play around with Snowpack. It takes a different approach from Webpack by bundling individual packages right after they're installed.
The "issue" is, when I install a package I have to first run npm install --save my-package and then I have to manually pack it with npx snowpack. The Snowpack docs mention that I can include a prepare script that would snowpack everything after running npm install but that doesn't apply to individual packages, just on a generic npm install of all dependencies in my package.json. As far as I can tell, this is the case for all npm hooks mentioned in the npm docs.
Is there any way I can automatically run a script whenever I install an individual package? The only way I can think of would be to overwrite the install script and add something to it. Are there any examples of this on GitHub or elsewhere?
Update: For clarification, I'd like to run npx snowpack every time I install a new package with --save but preferably not with --save-dev or without --save. This will never be different for any package. This will be specific to a certain repo/project, not global on my system.
It is not sufficient to run snowpack after simply running npm install as you would get by hooking into postinstall or release. Additionally, I want to make sure developers working on my project can use npm install --save newdep as they normally would and then snowpack will run. I do not want to require devs to use a custom named script.

Short answer: Unfortunately, npm does not provide any built-in feature(s) to meet your requirement.
Lifecycle hooks/scripts such as postinstall are invoked only when running the generic npm install command, and not when someone runs npm install --save <pkg_name> during the projects development phase.
Workaround: Consider customizing the logic of the npm install --save compound command by essentially overriding the npm command at the shell level.
The following solution, albeit a Bash one, describes how this custom logic can be actualized for a specific project(s). However, this solution is dependent on the following conditions:
Developers working on your project must have their the shell set to Bash when running the npm install --save compound command.
Developers working on your project will need to customize their Bash startup files, namely ~/.bashrc and possibly ~/.bash_profile.
The project directory, i.e. the project directory for which you want the custom logic to be effective, must contain a custom .bashrc file.
Bash Solution:
The following three steps are necessary to configure your project, and operating system(s), so that when a developer runs npm install --save <pkg_name> (or variations of it) the npx snowpack command is subsequently invoked.
Note: Points two and three (below) are the tasks developers need to carry out (once) to customize their Bash startup files.
The project specific .bashrc file:
Firstly create the following "project specific" .bashrc file in the root of your project directory, i.e. save it at the same level as where your projects package.json file resides:
/some/path/to/my-project/.bashrc
npm() {
local name_badge="\x1b[37;40mpostinstall\x1b[0m"
array_includes() {
local word=$1
shift
for el in "$#"; do [[ "$el" == "$word" ]] && return 0; done
}
log_warn_message() {
local cmd_name=$1 warn_badge warn_mssg
warn_badge="\x1b[30;43mWARN!\x1b[0m"
warn_mssg="${cmd_name} command not found. Cannot run npx snowpack."
echo -e "\n${name_badge} ${warn_badge} ${warn_mssg}" >&2
}
log_run_message() {
echo -e "\n${name_badge} Running pseudo postinstall hook."
}
if [[ $* == "install "* || $* == "i "* ]] && array_includes --save "$#"; then
# 1. Run the given `npm install --save ...` command.
command npm "$#"
# 2. Check whether the `npx` command exists globally.
command -v npx >/dev/null 2>&1 || {
log_warn_message npx
return 1
}
log_run_message
# 3. Run the pseudo "postinstall" command.
command npx snowpack
else
# Run all other `npm` commands as per normal.
command npm "$#"
fi
}
Note: For a better understanding of what this file does refer to the "Explanation" section below.
The ~/.bashrc file:
To make the custom logic, i.e. the npm function in the aforementioned .bashrc file, effective, it's necessary to configure Bash to read the aforementioned "project specific" .bashrc file. To configure this, add the following line of code to ~/.bashrc:
PROMPT_COMMAND='if [[ "$bashrc" != "$PWD" && "$PWD" != "$HOME" && -e .bashrc ]]; then bashrc="$PWD"; . .bashrc; fi'
Note: For a better understanding of what this line of code does refer to the "Explanation" section below.
The ~/.bash_profile file:
Typically your ~/.bash_profile contains the following line of code to load the ~/.bashrc file (or some variation of it):
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
If this is not present, then it must be added to ~/.bash_profile.
Additional info.
Setup/Configuration helpers:
Consider your developers utilizing the following two commands to aid configuration of their Bash startup files, as per the aforementioned steps two and three.
For step two, run the following command:
echo $'\n'"PROMPT_COMMAND='if [[ \"\$bashrc\" != \"\$PWD\" && \"\$PWD\" != \"\$HOME\" && -e .bashrc ]]; then bashrc=\"\$PWD\"; . .bashrc; fi'" >> ~/.bashrc
This will add the PROMPT_COMMAND=... line of code to the existing ~/.bashrc file, or create a new one if it doesn't already exist:
For step three, run the following command to append the line of code necessary in the ~/.bash_profile for loading the ~/.bashrc file:
echo $'\n'"if [ -f ~/.bashrc ]; then . ~/.bashrc; fi" >> ~/.bash_profile
Is my shell configured to Bash?
To check whether the shell is configured to Bash you can create a new session, i.e. create a new Terminal window and run:
echo $0
If it prints -bash then it's using Bash.
How do I configured my shell to Bash?
If echo $0 doesn't print -bash then you'll need to change the shell. To change it to Bash run:
chsh -s /bin/bash
Note: You'll need to create a new session for this change to become effective.
Explanation
The project specific .bashrc file:
This .bashrc file contains a shell function named npm. The body of this function contains the logic necessary to override the default npm install|i --save command.
The conditions specified in the if statement, i.e, the part that reads;
if [[ $* == "install "* || $* == "i "* ]] && array_includes --save "$#"; then
...
fi
essentially reads the $* special parameter to check whether the argument(s) passed to the npm function begin with either; install , or it's shorthand equivalent i , and whether the --save option/argument has been passed too.
To check for the existence of the --save argument we pass the $# special parameter to the array_includes function. We handle this argument differently because the position of the --save option may differ in the compound command. For instance, a user may install a package by running this;
# Example showing `--save` option at the end
npm install <pkg_name> --save
or this (or some other variation):
# Example showing `--save` option in the middle
npm i --save <pkg_name>
When the conditions specified in the if statement are met, i.e. they're true, we perform the following tasks in its body:
Run the given npm install --save ... command as-is via the line that reads:
command npm "$#"
Check whether the npx command exists globally via the part that reads:
command -v npx >/dev/null 2>&1 || {
log_warn_message npx
return 1
}
If the npx command is not available (globally) we warn the user that the npx snowpack command cannot be run, and return from the function early with an exit status of 1.
Note: My logic in this check assumes that you'll be installing npx globally. However if you're installing npm locally within your project then you'll need to change this logic. Perhaps by checking whether ./node_modules/.bin/npx exists instead. Or, you may be confident that npx command will always exists, therefore conclude that this check is unnecessary.
If the npx command exists globally we then run the pseudo "postinstall" command, i.e.
command npx snowpack
When the conditions specified in the if statement are NOT met, i.e. they're false, the user is essentially running any other npm command that is not npm install --save <pkg_name>. Therefore in the else branch we run the command as-is:
command npm "$#"
The ~/.bashrc file:
In section 5.2 Bash Variables of the "Bash Reference Manual" the PROMPT_COMMAND variable is described as follows:
PROMPT_COMMAND
If set, the value is interpreted as a command to execute before the printing of each primary prompt ($PS1).
So, this line of code (here it is again):
PROMPT_COMMAND='if [[ "$bashrc" != "$PWD" && "$PWD" != "$HOME" && -e .bashrc ]]; then bashrc="$PWD"; . .bashrc; fi'
loads the "project specific" .bashrc (if one exists), which in turn overrides the npm command with the npm function. This is what essentially provides a mechanism for overriding the npm install --save compound command for a specific project(s).
See this answer by #Cyrus for further explanation.

With newer versions of Snowpack (>=2) you can run snowpack dev and it will watch your npm_modules folder for new modules to build.

I think the best bet would be to create a new script that performs the desired action. Something along the following lines in your package.json:
{
"scripts": {
"snowpack-install" : "npm install --save && npx snowpack"
}
}
Correction
You can actually use the postinstall option in package.json. The postinstall will run "AFTER the package is installed". This would look something like the following:
{
"scripts": {
"postinstall" : "npx snowpack"
}
}

Related

How do I know the script options in a npm package?

For example, I installed tailwind CSS via npm by npm init && npm install tailwindcss. After that, I make a script in package.json like "build-css": "tailwindcss build src/styles.css -o public/styles.css"(I just copy-paste it from stuckoverflow). Now focus on -o, how a developer knows there is a -o option available for tailwind. I checked node-module/tailwindcss/script/build.js but there is no such thing that I currently understand( I mean, I found 0 clue). Pls give light on it. Do we have some standardization or unwritten rule that creator of npm package follow?
The scripts field in your package.json defines commands that are run with npm run in the context of npm. This allows you to use the command-line interface that are provided by different npm packages, without installing them globally. Many of these CLIs also expose a --help flag, or a help command.
To run the CLI from a npm package not installed globally, you may need to use npx. In your case, you can run:
npx tailwindcss
which tells you that there is a help command that gives you more information.
$ npx tailwindcss
tailwindcss 2.1.2
Usage:
tailwind <command> [options]
Commands:
help [command] More information about the command.
init [file] Creates Tailwind config file. Default: tailwind.config.js
build <file> [options] Compiles Tailwind CSS file.
If you are comfortable reading the source code in your node_modules folder, you can also find more information about these commands and the code that runs. To find where the CLI is defined, you can check node_modules/tailwindcss/package.json, which defines a bin key. In this case, it shows that the tailwindcss command comes from lib/cli.js. While the code is transformed, you can poke around and find lib/cli/commands/build.js, which contains the options for the build command.
const options = [{
usage: '-o, --output <file>',
description: 'Output file.'
}, {
usage: '-c, --config <file>',
description: 'Tailwind config file.'
}, {
usage: '--no-autoprefixer',
description: "Don't add vendor prefixes using autoprefixer."
}];
If the package is open source, you may be able to find the original, untransformed source online. In Tailwind's case, they have a Github repo where you can view the raw source for the build command.

Is there's a command for yarn to install a subfolder?

Background:
We are using yarn in this project and we don't want to write our package.json scripts with a mix of npm/yarn commands.
I have a root directory which contains a few subfolders.
Each holds a different service.
I want to create a script in the root folder that npm install each of the services, one by one.
Question:
Do you know what would be the yarn alternative to npm install <folder>?
I'm looking for something like this psuedo command: yarn <folder>
You could use --cwd there is a git issue about this :
yarn --cwd "your/path" script
You can also use cd :
cd "your/path" && yarn script
To run yarn install on every subdirectory you can do something like:
"scripts": {
...
"install:all": "for D in */; do yarn --cwd \"${D}\"; done"
}
where
install:all is just the name of the script, you can name it whatever you please
D Is the name of the directory at the current iteration
*/ Specifies where you want to look for subdirectories. directory/*/ will list all directories inside directory/ and directory/*/*/ will list all directories two levels in.
yarn -cwd install all dependencies in the given folder
You could also run several commands, for example:
for D in */; do echo \"Installing stuff on ${D}\" && yarn --cwd \"${D}\"; done
will print "Installing stuff on your_subfolder/" on every iteration.
To run multiple commands in a single subfolder:
cd your/path && yarn && yarn some-script

PKGBUILD with make all

I am trying to write a PKGBUILD for the AUR right now for a github project consisting of several sub applications.
So basically the CMake file of this project just runs a make to make && make install the sub applications.
These are my build and package steps:
build() {
cd "$srcdir/$_gitname"
[[ -d build ]] && rm -r build
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=/opt/od ..
}
package() {
cd "${_gitname}/build"
sudo make all
}
My problem is now that everything works except:
makepkg -i is never asking for sudo rights during build (therefore I had to add sudo in front of the make all)
When asking for installing, makepkg does not recognize the size of the package. Therefore the package does also not uninstall when running packman -R packagename
I cannot change the CMake file though, because the project is not mine and all the different subapplications belong together and if I try make && make install them separately I get a bunch of errors that they are depending each other.
The package function cannot install into the root hierarchy. Instead, makepkg is intended to install into the pkgdir under a fakeroot, where the pkgdir replicates the actual root directory structure. See ArchWiki/Creating Packages.
You can do this by adding DESTDIR="$pkgdir/" to the make options in your package function.
When pacman is invoked on the created package, it will copy the files over into the real root hierarchy.
As an exmaple
package()
{
cd "$pkgname"
DESTDIR="$pkgdir" cmake --install out
}
This will install things to $pkgdir, and then packaged to zst file.

How do I run an npm script of a dependent package

I have a package that itself has a script in its package.json that I would like to be able to run in my top-level project. This package is one of my top-level projects dependencies. I'm looking for a way to directly or indirectly call the dependency packages script.
Let us assume the module name I'm working with is named foo and the script I want to run is updateFooData.
I tried using the syntax npm run-script <package> <...> to run it, but this appears to be deprecated functionality as I can't find it in the current official documentation but I see it in other (very old) search results.
npm run-script foo updateFooData
# npm ERR! missing script: foo
I also looked into the npm api and while npm.commands.run-script(args, callback) will do what I want, I can't figure out how to load the module into npm
{
...
"scripts":{
"foo:updateFooData": "node --eval \"... ??; npm.commands.run-script('updateFooData', callback)\""
}
}
npm run foo:updateFooData
# Obviously fails
The only thing I've found that works so far is to CD into the submodule directory and run npm from there. This is not the preferred solution for me.
cd node_modules/foo
npm run updateFooData
I ran into this trying to run the updatedb script for geoip-lite. You should use the npm explore command which will spawn a new shell in a dependencies' directory.
So for your use case, try npm explore foo -- npm run updateFooData
Note:
This isn't a very good idea. You have no guarantee which node_modules folder module will be installed in as NPM will attempt to optimise space by installing shared packages at the highest level possible. – #superluminary
Something I've found that does work:
If the script you are running runs a script file, you can look at the path of the file it's running and run the script using a require:
# if node_modules/foo/package.json looks like this
{
"scripts": {
"updateFooData":"scripts/updateFooData.js"
}
}
# then package.json can look like this
{
"scripts": {
"foo:updateFooData":"node --eval \"require('foo/scripts/updateFooData.js')\""
}
}
# or package.json can look like this
{
"scripts": {
"foo:updateFooData":"node node_modules/foo/scripts/updateFooData.js"
}
}
# and you can run it like this
npm run foo:updateFooData
I don't like this solution because it only works if the npm script you are running is a file. It won't apply in all

surpress output of single line, multi command Makefile recipe

I would like to surpress the output of certain commands in my Makefile
For instance I have a target, stagel
stagel:
cd scripts && npm list body-parser || npm install body-parser
node scripts/app.js
I'd like to surpress the output of first line in the target.
I tried, #cd scripts && npm list body-parser || npm install body-parser, but I still got the output. I also tried appending # to each npm command, but got, #npm: command not found
I think this command is not right:
cd scripts && npm list body-parser || npm install body-parser
This says, "run cd scripts: if the cd works, run npm list body-parser and if the cd fails, run npm install body-parser". I don't know what you're trying to do for sure but I suspect what you want to say is, "first cd scripts, then run npm list body-parser and if that fails run npm install body-parser". To do that you'll need something like this:
cd scripts && { npm list body-parser || npm install body-parser; }
It's not clear what you mean by "supporess the output of first line". Do you mean, you don't want make to print out the command line it is running? Or do you mean, you don't want the output from the command to be shown?
If the former then your attempt #cd ... will do that. Since you weren't happy with that I can only assume you mean the latter.
Make does not have anything to say about the output that commands you run generate. If you want to suppress that output you have to do it yourself, using normal shell redirection operations. For example:
stagel:
cd scripts && { npm list body-parser || npm install body-parser; } >/dev/null
node scripts/app.js