How do I set the default test command for `npm init`? - node.js

I know I can do:
npm config set init.author.email me#mycompany.com
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?

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"
}

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.

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').

npm config set init ... will create a default configuration for all future projects that will be initialized - if you want to just set a few values once - simply use a shellscript to write some values prior to npm init like so:
echo '{"version":"0.1.0","license":"UNLICENSED","private":true,"scripts":{"test":"npx jest"}}' > "./package.json" && npm init -y

Related

Npm workspaces - call workspace script from root package

I'm struggling with multiple npm packages in a root git repository with custom dev scripts to handle launch, compile, build and so on. Now I came across npm workspaces and wanted to use this stunning new feature in my following project structure but I can't get it to work:
projectx (root)
- package.json
- apps
-- backend
-- src
-- package.json (name: #projectx/backend, scripts: "dev":"ts-node or whatever")
-- common
-- src
-- package.json (name: #projectx/common)
-- frontend
-- src
-- package.json (name: #projectx/frontend, scripts: "dev":"webpack")
My root package.json contains:
{
"name": "packagex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": "true",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"back:dev": "npm workspace #projectx/backend dev",
"front:dev": "npm workspace #projectx/frontend dev",
"dev": "run-p back:dev front:dev"
},
"workspaces": [
"apps/*"
],
"repository": {
"type": "git",
"url": "git_url"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"npm-run-all": "^4.1.5"
}
}
And now I want to start backend and frontend with npm-run-all and the command on root: npm run dev which results in:
And I also want to share the common package with backend and frontend, which should be possible in this case. Maybe anobody else is facing the same problem or has some ideas what I am doing wrong here.
npm#7.7.0 added a way to call scripts from child packages/workspaces, here are some examples based on your original:
Running a script named "dev" in all workspaces located under apps/backend:
npm run dev -w apps/backend
Running a script named "dev" in all workspaces:
npm run dev --ws
Running a script named "dev" in a package named #projectx/frontend:
npm run dev -w #projectx/frontend
More info:
Related CHANGELOG entry: https://github.com/npm/cli/releases/tag/v7.7.0
Docs: https://docs.npmjs.com/cli/v7/commands/npm-run-script#workspaces-support
Blog post: https://dev.to/ruyadorno/npm-workspaces-npm-run-and-exec-1lg0
Your "workspaces" property in package.json looks right. I'm using NPM Workspaces and it's working well, but it's still missing a lot of features so you need to wire things up yourself. I also don't think npm worksace is a command (but maybe for the future?), so here's a checklist to get it to work:
Make sure you're using Node 15+ and NPM 7+
Set all package.json to "private": true,
Delete all package-lock.json inside of your project, go to the root, then npm install. It should generate one root level package-lock.json that contains all dependencies for your workspaces
Since you're using npm-run-all, add this to your scripts:
"scripts": {
"back:dev": "cd apps/backend && npm run dev",
"front:dev": "cd apps/fontend && npm run dev",
"dev": "npm-run-all build --parallel back:dev front:dev"
}
Then start it with npm run dev.
Note, you may want to consider using start scripts instead of dev to shorten the command you need to type (e.g. npm start instead of npm run dev), but npm run dev will still be fine.
In root package.json you can also add short name for each package:
"scripts": {
"api": "npm --workspace=#app/api run",
}
#app/api is a name in package.json
And run scripts in ./packages/api folder from root like so:
npm run api lint
npm run api dev
I think you wish to:
keep scripts and dependencies separate (thus the 4 package.json files), for ease of maintenance
May I suggest a work-around without workspaces that might do what you're after:
{
...
"scripts": {
"//back:dev": "npm workspace #projectx/backend dev",
"back:dev": "npm --prefix apps/backend dev",
"//front:dev": "npm workspace #projectx/frontend dev",
"front:dev": "npm --prefix apps/frontend dev",
"dev": "run-p back:dev front:dev"
},
"//workspaces": [
"apps/*"
],
"devDependencies": {
"#local/back": "file:apps/backend",
"#local/front": "file:apps/frontend",
"npm-run-all": "^4.1.5"
}
}
The npm --prefix runs npm scripts in another folder than the current one.
The #local/back dependencies are not necessary for that, but I've found such useful if eg. a package depends on another. You might use that trick to reach for the common by:
"dependencies": {
"#local/common": "file:../common"
}
I wished a week ago that workspaces would offer a better solution, but didn't find any benefit over the above mechanisms.
I would also like workspaces to:
only expose those files in the files entry of the particular package.json (now, all are shown)
only allow import to paths in the exports of the particular package.json, if it has one
See
NPM Workspaces monorepo - share local package's distribution folder as root instead of the entire source files

How to use .ENV variables when publishing npm package

How do I inject my environment variable into the final build that gets published to npm?
I'm using the dotenv package and that works great locally. However when I do npm publish, the env variable is gone since it just runs the file in the main property of the package.json.
Some relevant fields from package json:
"main": "./lib/index.js",
"typings": "./lib/index.d.ts",
"files": [
"lib",
".env"
],
"scripts": {
"start" : "tsc && node -r dotenv/config ./lib/index.js"
},
"bin" : {
"run-app" : "./lib/index.js"
},
"dependencies": {
"dotenv": "^8.2.0",
}
.gitignore:
# OSX
.DS_Store
node_modules
notes.MD
lib
.env
I tried to inject my env variable by passing it to my start script and also call the .config() method on dotenv inside the code. Either way the env variable ends up undefined when running my package using npx.
What am I doing wrong?

npm config not being updated inside the same npm script

Let's say I have this npm script:
"test": "npm config set email test#test.com && npm config get email"
After running npm run test I don't see email updated.
Similarly if create bash script like so:
npm config set email test#test.com
npm config get email
and add it to npm script, it still works the same way.
This might be a bash issue, I'm a very new to bash.
Is there a way to make it work - meaning to set the config values and use them in the script?
I think the issue is a bit more complicated. Consider this:
c:\cygwin64\home\qbolec\baro>npm config set email old#email.com
c:\cygwin64\home\qbolec\baro>npm run test
> baro#1.0.0 test c:\cygwin64\home\qbolec\baro
> echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test#test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email
'before'
init.author.email=qbolec#gmail.com
email=old#email.com
'after'
init.author.email=qbolec#gmail.com
email=test#test.com
'get'
old#email.com
c:\cygwin64\home\qbolec\baro>npm config get email
test#test.com
c:\cygwin64\home\qbolec\baro>cat package.json
{
"name": "baro",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test#test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email"
},
"author": "Jakub Łopuszański <qbolec#gmail.com>",
"license": "ISC"
}
It looks like the .npmrc file is actually changed by the npm config set immediately, and the change is permanent, but not available for reading through npm config get. However, I don't know how to overcome this.

Passing variables from NPM Scripts to Webpack

I have a production build with Webpack that uses node's process.env to set environment variables:
webpack.prod.babel.js:
const DefinePlugin = new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
API_URL: JSON.stringify('https://myprodurl.com'),
},
});
packge.json:
"scripts: {
"build:prod": "webpack"
}
It's working fine, but I need something different.
I need to set the production url as variable in the NPM Script.
So, instead of this:
npm run build:prod
I need this:
npm run build:prod --URL https://myprodurl.com
How about defining your environment variable in the command line, like:
URL=https://myprodurl.com npm run build:prod
I tested this with a simple script and was able to print out the URL.
"scripts": {
"test": "./myTest.js"
},
myTest.js:
#!/usr/local/bin/node
'use strict'
console.log(process.env.URL);
console.log('Done!');
then:
$ URL=https://whatever.com npm run test
> my-test#1.0.0 test /Test/my-test
> ./myTest.js
https://whatever.com
Done!
EDIT: As mentioned by #RyanZim, see the following for Windows: https://github.com/kentcdodds/cross-env
(disclaimer: I don't use Windows and have never tried this lib)

How to set environment variables from within package.json?

How to set some environment variables from within package.json to be used with npm start like commands?
Here's what I currently have in my package.json:
{
...
"scripts": {
"help": "tagove help",
"start": "tagove start"
}
...
}
I want to set environment variables (like NODE_ENV) in the start script while still being able to start the app with just one command, npm start.
Set the environment variable in the script command:
...
"scripts": {
"start": "node app.js",
"test": "NODE_ENV=test mocha --reporter spec"
},
...
Then use process.env.NODE_ENV in your app.
Note: This is for Mac & Linux only. For Windows refer to the comments.
Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to #mikekidder for the suggestion in one of the comments here.
From documentation:
{
"scripts": {
"build": "cross-env NODE_ENV=production OTHERFLAG=myValue webpack --config build/webpack.config.js"
}
}
Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.
Ultimately, the command that is executed (using spawn) is:
webpack --config build/webpack.config.js
The NODE_ENV environment variable will be set by cross-env
I just wanted to add my two cents here for future Node-explorers. On my Ubuntu 14.04 the NODE_ENV=test didn't work, I had to use export NODE_ENV=test after which NODE_ENV=test started working too, weird.
On Windows as have been said you have to use set NODE_ENV=test but for a cross-platform solution the cross-env library didn't seem to do the trick and do you really need a library to do this:
export NODE_ENV=test || set NODE_ENV=test&& yadda yadda
The vertical bars are needed as otherwise Windows would crash on the unrecognized export NODE_ENV command. I don't know about the trailing space, but just to be sure I removed them too.
Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) && in your script command before starting your app.
Example .env file:
VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break
Example index.js:
console.log('Test', process.env.VAR_A, process.env.VAR_B);
Example package.json:
{
...
"scripts": {
"start": "node index.js",
"env-linux": "export $(cat .env | xargs) && env",
"start-linux": "export $(cat .env | xargs) && npm start",
"env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
"start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",
}
...
}
Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start" -- so there is some redundancy in the scripts.
For a test you can see the env variables by running npm run env-linux or npm run env-windows, and test that they make it into your app by running npm run start-linux or npm run start-windows.
Try this on Windows by replacing YOURENV:
{
...
"scripts": {
"help": "set NODE_ENV=YOURENV && tagove help",
"start": "set NODE_ENV=YOURENV && tagove start"
}
...
}
#luke's answer was almost the one I needed! Thanks.
As the selected answer is very straightforward (and correct), but old, I would like to offer an alternative for importing variables from a .env separate file when running your scripts and fixing some limitations to Luke's answer.
Try this:
::: .env file :::
# This way, you CAN use comments in your .env files
NODE_PATH="src/"
# You can also have extra/empty lines in it
SASS_PATH="node_modules:src/styles"
Then, in your package json, you will create a script that will set the variables and run it before the scripts you need them:
::: package.json :::
scripts: {
"set-env": "export $(cat .env | grep \"^[^#;]\" |xargs)",
"storybook": "npm run set-env && start-storybook -s public"
}
Some observations:
The regular expression in the grep'ed cat command will clear the comments and empty lines.
The && don't need to be "glued" to npm run set-env, as it would be required if you were setting the variables in the same command.
If you are using yarn, you may see a warning, you can either change it to yarn set-env or use npm run set-env --scripts-prepend-node-path && instead.
Different environments
Another advantage when using it is that you can have different environment variables.
scripts: {
"set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
"set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}
Please, remember not to add .env files to your git repository when you have keys, passwords or sensitive/personal data in them!
UPDATE: This solution may break in npm v7 due to npm RFC 21
CAVEAT: no idea if this works with yarn
npm (and yarn) passes a lot of data from package.json into scripts as environment variables. Use npm run env to see them all. This is documented in https://docs.npmjs.com/misc/scripts#environment and is not only for "lifecycle" scripts like prepublish but also any script executed by npm run.
You can access these inside code (e.g. process.env.npm_package_config_port in JS) but they're already available to the shell running the scripts so you can also access them as $npm_... expansions in the "scripts" (unix syntax, might not work on windows?).
The "config" section seems intended for this use:
"name": "myproject",
...
"config": {
"port": "8010"
},
"scripts": {
"start": "node server.js $npm_package_config_port",
"test": "wait-on http://localhost:$npm_package_config_port/ && node test.js http://localhost:$npm_package_config_port/"
}
An important quality of these "config" fields is that users can override them without modifying package.json!
$ npm run start
> myproject#0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port
Serving on localhost:8010
$ npm config set myproject:port 8020
$ git diff package.json # no change!
$ cat ~/.npmrc
myproject:port=8020
$ npm run start
> myproject#0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port
Serving on localhost:8020
See npm config and yarn config docs.
It appears that yarn reads ~/.npmrc so npm config set affects both, but yarn config set writes to ~/.yarnrc, so only yarn will see it :-(
For a larger set of environment variables or when you want to reuse them you can use env-cmd.
As a plus, the .env file would also work with direnv.
./.env file:
# This is a comment
ENV1=THANKS
ENV2=FOR ALL
ENV3=THE FISH
./package.json:
{
"scripts": {
"test": "env-cmd mocha -R spec"
}
}
This will work in Windows console:
"scripts": {
"setAndStart": "set TMP=test&& node index.js",
"otherScriptCmd": "echo %TMP%"
}
npm run aaa
output:
test
See this answer for details.
suddenly i found that actionhero is using following code, that solved my problem by just passing --NODE_ENV=production in start script command option.
if(argv['NODE_ENV'] != null){
api.env = argv['NODE_ENV'];
} else if(process.env.NODE_ENV != null){
api.env = process.env.NODE_ENV;
}
i would really appreciate to accept answer of someone else who know more better way to set environment variables in package.json or init script or something like, where app bootstrapped by someone else.
use git bash in windows. Git Bash processes commands differently than cmd.
Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use: $ENV_VAR and on windows you use %ENV_VAR%. - cross-env doc
{
...
"scripts": {
"help": "tagove help",
"start": "env NODE_ENV=production tagove start"
}
...
}
use dotenv package to declare the env variables
For single environment variable
"scripts": {
"start": "set NODE_ENV=production&& node server.js"
}
For multiple environment variables
"scripts": {
"start": "set NODE_ENV=production&& set PORT=8000&& node server.js"
}
When the NODE_ENV environment variable is set to 'production' all devDependencies in your package.json file will be completely ignored when running npm install. You can also enforce this with a --production flag:
npm install --production
For setting NODE_ENV you can use any of these methods
method 1: set NODE_ENV for all node apps
Windows :
set NODE_ENV=production
Linux, macOS or other unix based system :
export NODE_ENV=production
This sets NODE_ENV for current bash session thus any apps started after this statement will have NODE_ENV set to production.
method 2: set NODE_ENV for current app
NODE_ENV=production node app.js
This will set NODE_ENV for the current app only. This helps when we want to test our apps on different environments.
method 3: create .env file and use it
This uses the idea explained here. Refer this post for more detailed explanation.
Basically, you create a .env file and run some bash scripts to set them on the environment.
To avoid writing a bash script, the env-cmd package can be used to load the environment variables defined in the .env file.
env-cmd .env node app.js
method 4: Use cross-env package
This package allows environment variables to be set in one way for every platform.
After installing it with npm, you can just add it to your deployment script in package.json as follows:
"build:deploy": "cross-env NODE_ENV=production webpack"
{
...
"scripts": {
"start": "ENV NODE_ENV=production someapp --options"
}
...
}
Most elegant and portable solution:
package.json:
"scripts": {
"serve": "export NODE_PRESERVE_SYMLINKS_MAIN=1 && vue-cli-service serve"
},
Under windows create export.cmd and put it somewhere to your %PATH%:
#echo off
set %*
If you:
Are currently using Windows;
Have git bash installed;
Don't want to use set ENV in your package.json which makes it only runnable for Windows dev machines;
Then you can set the script shell of node from cmd to git bash and write linux-style env setting statements in package.json for it to work on both Windows/Linux/Mac.
$ npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
Although not directly answering the question I´d like to share an idea on top of the other answers. From what I got each of these would offer some level of complexity to achieve cross platform independency.
On my scenario all I wanted, originally, to set a variable to control whether or not to secure the server with JWT authentication (for development purposes)
After reading the answers I decided simply to create 2 different files, with authentication turned on and off respectively.
"scripts": {
"dev": "nodemon --debug index_auth.js",
"devna": "nodemon --debug index_no_auth.js",
}
The files are simply wrappers that call the original index.js file (which I renamed to appbootstrapper.js):
//index_no_auth.js authentication turned off
const bootstrapper = require('./appbootstrapper');
bootstrapper(false);
//index_auth.js authentication turned on
const bootstrapper = require('./appbootstrapper');
bootstrapper(true);
class AppBootStrapper {
init(useauth) {
//real initialization
}
}
Perhaps this can help someone else
Running a node.js script from package.json with multiple environment variables:
package.json file:
"scripts": {
"do-nothing": "set NODE_ENV=prod4 && set LOCAL_RUN=true && node ./x.js",
},
x.js file can be as:
let env = process.env.NODE_ENV;
let isLocal = process.env.LOCAL_RUN;
console.log("ENV" , env);
console.log("isLocal", isLocal);
You should not set ENV variables in package.json. actionhero uses NODE_ENV to allow you to change configuration options which are loaded from the files in ./config. Check out the redis config file, and see how NODE_ENV is uses to change database options in NODE_ENV=test
If you want to use other ENV variables to set things (perhaps the HTTP port), you still don't need to change anything in package.json. For example, if you set PORT=1234 in ENV and want to use that as the HTTP port in NODE_ENV=production, just reference that in the relevant config file, IE:
# in config/servers/web.js
exports.production = {
servers: {
web: function(api){
return {
port: process.env.PORT
}
}
}
}
In addition to use of cross-env as documented above, for setting a few environment variables within a package.json 'run script', if your script involves running NodeJS, then you can set Node to pre-require dotenv/config:
{
scripts: {
"eg:js": "node -r dotenv/config your-script.js",
"eg:ts": "ts-node -r dotenv/config your-script.ts",
"test": "ts-node -r dotenv/config -C 'console.log(process.env.PATH)'",
}
}
This will cause your node interpreter to require dotenv/config, which will itself read the .env file in the present working directory from which node was called.
The .env format is lax or liberal:
# Comments are permitted
FOO=123
BAR=${FOO}
BAZ=Basingstoke Round About
#Blank lines are no problem
Note : In order to set multiple environment variable, script should goes like this
"scripts": {
"start": "set NODE_ENV=production&& set MONGO_USER=your_DB_USER_NAME&& set MONGO_PASSWORD=DB_PASSWORD&& set MONGO_DEFAULT_DATABASE=DB_NAME&& node app.js",
},

Resources