Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

package.json scripts that work with npm and yarn?

I am using npm as a build tool and so in my package.json, and some of my scripts depend on other scripts:

{
  "test": "npm run lint && mocha"
}

This hardcodes the npm package manager into package.json. How can make this approach to expressing dependencies work with both npm and yarn?

like image 686
mjs Avatar asked Jan 14 '17 08:01

mjs


People also ask

Does yarn work with package json?

Every yarn package must have a package. json file which yarn looks for in order to identify the package. This file configures the behavior of yarn while it is running inside that package. Yarn uses a yarn.

Can we have both npm and yarn together?

In my project, I have used both npm and yarn. For example, one of the modules did not install properly with npm, so I used yarn to install that module. For many other I used npm. All in the same project.

How do I run a script in a package json using yarn?

yarn run [script] [<args>] Running this command will execute the script named "test" in your package. json . You can pass additional arguments to your script by passing them after the script name. Running this command will execute jest -o --watch .

Can npm install yarn packages?

The Yarn maintainers recommend installing Yarn globally by using the NPM package manager, which is included by default with all Node. js installations. Use the -g flag with npm install to do this: sudo npm install -g yarn.


2 Answers

The $npm_execpath environment variable refers to the build tool, so just replace npm with the $npm_execpath:

{
  "test": "$npm_execpath run lint && mocha"
}

Both npm test and yarn test will work, and will use the appropriate build tool.

like image 139
mjs Avatar answered Oct 26 '22 07:10

mjs


While mjs' answer is great, there's also a small package that is purported to work on all environments including Windows: https://www.npmjs.com/package/yarpm

To use in a project, run yarn add yarpm --dev / npm i -D yarpm and then just use yarpm in your scripts like this:

{
  "test": "yarpm run lint && mocha"
}

As the package README notes, you just need to make sure your commands would be suitable for passing through to either yarn or npm: you cannot use arguments/flags that only work on one package manager.

like image 35
Tim Malone Avatar answered Oct 26 '22 07:10

Tim Malone