Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the default test command for `npm init`?

I know I can do:

npm config set init.author.email [email protected]
npm config set init.license UNLICENSED

To set the defaults used to create a new package.json with npm init. But how can I set the default value for the test command? I've tried

npm config set init.scripts.test "mocha"

But it doesn't work. The npm docs don't seem to help.

Is there a list of all the init defaults?

like image 857
mikemaccana Avatar asked Jan 29 '16 11:01

mikemaccana


3 Answers

There is a list of all config defaults npm config list -l.

As you can see there isn't anything like init.scripts. But there is another way to do it. If you first npm install mocha and then npm init you will get a package.json like:

{
  "name": "asd",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "mocha": "^2.4.5"
  },
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "UNLICENSED"
}
like image 100
Roland Starke Avatar answered Sep 28 '22 11:09

Roland Starke


Although you can't (currently) configure default scripts via npm settings, you can customise the entire npm init output by providing your own init-module. The default is stored at ~/.npm-init.js - whatever you export becomes the result of running npm init.

To make this useful, you'd probably want to hijack the existing default npm init module, which lives in <your npm install directory>/node_modules/init.js. If you only care about providing a default test script, the simplest option is to use init-module, which provides a configuration parameter init-scripts-test.

like image 27
benvan Avatar answered Sep 28 '22 11:09

benvan


I was searching for a way to programmatically create a package.json with dynamically defined values. I noticed creating a package.json file before calling npm init -y works as expected.

// Require: fs
const fs = require('fs')

// Variables
const values = {
    "scripts": {
        "test": "mocha"
    }
    // as well as any other values you want
}

// Create package.json
fs.writeFileSync('package.json', values)

Running npm init -y after running the above code would generate a package.json with scripts.test = "mocha" defined.

If you're looking for a way to run npm init -y from within code as well, I recommend using shelljs: shell.exec('npm init -y').

like image 42
Zebiano Avatar answered Sep 28 '22 10:09

Zebiano