Giter Club home page Giter Club logo

cross-env's Introduction

cross-env πŸ”€

Run scripts that set and use environment variables across platforms

🚨 NOTICE: cross-env still works well, but is in maintenance mode. No new features will be added, only serious and common-case bugs will be fixed, and it will only be kept up-to-date with Node.js over time. Learn more


Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct

The problem

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%.

This solution

cross-env makes it so you can have a single command without worrying about setting or using the environment variable properly for the platform. Just set it like you would if it's running on a POSIX system, and cross-env will take care of setting it properly.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev cross-env

WARNING! Make sure that when you're installing packages that you spell things correctly to avoid mistakenly installing malware

NOTE : Version 7 of cross-env only supports Node.js 10 and higher, to use it on Node.js 8 or lower install version 6 npm install --save-dev cross-env@6

Usage

I use this in my npm scripts:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}

Ultimately, the command that is executed (using cross-spawn) is:

webpack --config build/webpack.config.js

The NODE_ENV environment variable will be set by cross-env

You can set multiple environment variables at a time:

{
  "scripts": {
    "build": "cross-env FIRST_ENV=one SECOND_ENV=two node ./my-program"
  }
}

You can also split a command into several ones, or separate the environment variables declaration from the actual command execution. You can do it this way:

{
  "scripts": {
    "parentScript": "cross-env GREET=\"Joe\" npm run childScript",
    "childScript": "cross-env-shell \"echo Hello $GREET\""
  }
}

Where childScript holds the actual command to execute and parentScript sets the environment variables to use. Then instead of run the childScript you run the parent. This is quite useful for launching the same command with different env variables or when the environment variables are too long to have everything in one line. It also means that you can use $GREET env var syntax even on Windows which would usually require it to be %GREET%.

If you precede a dollar sign with an odd number of backslashes the expression statement will not be replaced. Note that this means backslashes after the JSON string escaping took place. "FOO=\\$BAR" will not be replaced. "FOO=\\\\$BAR" will be replaced though.

Lastly, if you want to pass a JSON string (e.g., when using ts-loader), you can do as follows:

{
  "scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS={\\\"module\\\":\\\"commonjs\\\"} node some_file.test.ts"
  }
}

Pay special attention to the triple backslash (\\\) before the double quotes (") and the absence of single quotes ('). Both of these conditions have to be met in order to work both on Windows and UNIX.

cross-env vs cross-env-shell

The cross-env module exposes two bins: cross-env and cross-env-shell. The first one executes commands using cross-spawn, while the second one uses the shell option from Node's spawn.

The main use case for cross-env-shell is when you need an environment variable to be set across an entire inline shell script, rather than just one command.

For example, if you want to have the environment variable apply to several commands in series then you will need to wrap those in quotes and use cross-env-shell instead of cross-env.

{
  "scripts": {
    "greet": "cross-env-shell GREETING=Hi NAME=Joe \"echo $GREETING && echo $NAME\""
  }
}

The rule of thumb is: if you want to pass to cross-env a command that contains special shell characters that you want interpreted, then use cross-env-shell. Otherwise stick to cross-env.

On Windows you need to use cross-env-shell, if you want to handle signal events inside of your program. A common case for that is when you want to capture a SIGINT event invoked by pressing Ctrl + C on the command-line interface.

Windows Issues

Please note that npm uses cmd by default and that doesn't support command substitution, so if you want to leverage that, then you need to update your .npmrc to set the script-shell to powershell. Learn more here.

Inspiration

I originally created this to solve a problem I was having with my npm scripts in angular-formly. This made contributing to the project much easier for Windows users.

Other Solutions

  • env-cmd - Reads environment variables from a file instead
  • @naholyr/cross-env - cross-env with support for setting default values

Issues

Looking to contribute? Look for the Good First Issue label.

πŸ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

πŸ’‘ Feature Requests

This project is in maintenance mode and no new feature requests will be considered.

Learn more

Contributors ✨

Thanks goes to these people (emoji key):


Kent C. Dodds

πŸ’» πŸ“– πŸš‡ ⚠️

Ya Zhuang

πŸ”Œ πŸ“–

James Harris

πŸ“–

compumike08

πŸ› πŸ“– ⚠️

Daniel RodrΓ­guez Rivero

πŸ› πŸ’» πŸ“–

Jonas Keinholz

πŸ› πŸ’» ⚠️

Hugo Wood

πŸ› πŸ’» ⚠️

Thiebaud Thomas

πŸ› πŸ’» ⚠️

Daniel Rey LΓ³pez

πŸ’» ⚠️

Amila Welihinda

πŸš‡

Paul Betts

πŸ› πŸ’»

Turner Hayes

πŸ› πŸ’» ⚠️

Suhas Karanth

πŸ’» ⚠️

Sven

πŸ’» πŸ“– πŸ’‘ ⚠️

D. NicolΓ‘s Lopez Zelaya

πŸ’»

Johan Hernandez

πŸ’»

Jordan Nielson

πŸ› πŸ’» ⚠️

Jason Cooke

πŸ“–

bibo5088

πŸ’»

Eric Berry

πŸ”

MichaΓ«l De Boey

πŸ’»

Lauri Eskola

πŸ“–

devuxer

πŸ“–

Daniel

πŸ“–

This project follows the all-contributors specification. Contributions of any kind welcome!

Note: this was added late into the project. If you've contributed to this project in any way, please make a pull request to add yourself to the list by following the instructions in the CONTRIBUTING.md

LICENSE

MIT

cross-env's People

Contributors

allcontributors[bot] avatar amilajack avatar anaisbetts avatar apidcloud avatar bennycode avatar compumike08 avatar danielo515 avatar danreylop avatar devuxer avatar enzomartin avatar hgwood avatar inyono avatar jiangyuan avatar kentcdodds avatar lauriii avatar marcioj avatar markwoon avatar mastilver avatar michaeldeboey avatar naholyr avatar nkbt avatar nogsmpls avatar nolanlawson avatar sudo-suhas avatar thomasthiebaud avatar toddbluhm avatar turnerhayes avatar wopian avatar wtgtybhertgeghgtwtg avatar zhuangya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cross-env's Issues

Possible regression with 4.0.0, && operator have a strange behaviour

Hi

I'm running on windows 7 with node 7.7.3. I updated cross-env to 4.0.0 and migrate my npm scripts but one of my script doesn't work anymore. I tested this behavior with an empty project :

With cross-env 3.2.4 and the npm script :

 "greet": "cross-env MESSAGE=hello nodemon --exec \"echo %MESSAGE% && echo there is no problem \""

output :

$ cross-env MESSAGE=hello nodemon --exec "echo %MESSAGE% && echo there is no problem "
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `echo hello && echo there is no problem`
hello
there is no problem
[nodemon] clean exit - waiting for changes before restart

With cross-env 4.0.0 and the script :

"greet": "cross-env MESSAGE=hello nodemon --exec \"echo $MESSAGE && echo there is no problem \""

output :

$ cross-env MESSAGE=hello nodemon --exec "echo $MESSAGE & echo there is no problem "
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `echo hello`
hello
[nodemon] clean exit - waiting for changes before restart

Maybe I'm missing something ?

Read env variables from JSON file

Is there a way to make cross-env read env variables from a JSON file?

{
    "NODE_ENV": "DEBUG",
    "BING_KEY": "dd888c15-19c4-4eda-ab98-f24cea171abe",
    ...
}

Add yourself to the contributors table!

Hey contributors! I've just revamped the project to update it to the latest versions of things and tools. As part of this I added the all-contributors table that you can see here. There should be at least 18 people in that table. If you would like to be included, please open a PR to add yourself. You can do so by following these instructions

Escape double dot

Hey, I just tried out 4.0.0 and got an issue.

BREAKING CHANGE: You now must escape : to use it in a value of you don't want it to be swapped with ; on Windows

So I tried to escape this line (package.json):

"app": "cross-env MONGO_URL=mongodb://localhost:4000/database npm start"

to

"app": "cross-env MONGO_URL=mongodb\://localhost\:4000/database npm start"

But this is not valid JSON (vscode told me about an "Invalid escape character in string").
It seems like there are only some characters allowed to escape in JSON. Take a look at JSON.

Handle forward/backward slash for executing binaries

I made convert-slash-exec to be able to execute binaries regardless of which platform I was on (see link for details).

Would integrating this into cross-env be reasonable? Wrapping commands after command to handle all the various nuances/annoyances when working cross platform can build a quite long string ... Not to mention stuff like #23. Having one tool to handle these things would be great.

This might be out of scope, in which case a tool to wrap all of this functionality might be in place.

Get en variable value from inline command?

Can we assign env variables from command results?

In my package.json I have:

    "build": "cross-env PKG_VERSION=$(npm run version) ng build",
    "version": "node -p -e \"require('./package.json').version\""

Does this work on windows? (I only have a mac at hand for now)
Thanks

coss-env files with babel config

Hey @kentcdodds

I noticed there is a problem with running babel with cross-env on windows machine.

To replicate the problem create following directory structurue and follow further instruction.

.src/
  index.js
  index.spec.js

I want to run cross-env with BABEL_ENV and --ignore parms.
On MacOS

BABEL_ENV=cjs babel ./src -d lib --ignore '**/*.spec.js'

and equivalent on windows machine:

set BABEL_ENV=cjs && babel ./src -d lib --ignore '**/*.spec.js'

with cross-evn I should be able to use it in my package.json as below:

{ 
  scripts: {
    build-cjs: "cross-env BABEL_ENV=cjs babel ./src -d lib --ignore '**/*.spec.js'"
  }
}

If I run both windows and mac os commands directly from CLI level (sanity check) everything is ok on both platforms, however cross-env fails on windows machine not passing --ignore to babel and so .spec. files are parsed.

spawn NODE_PATH=. ENOENT

Running OS X 10.11.2, node v4.2.4, npm 2.4.12

{
  // ...
  "scripts": {
    // ...
    "dev": "cross-env NODE_PATH=. node server",
  },
  "dependencies": {
    // ...
    "cross-env": "1.0.5",
   // ...
  }
}

npm run dev throws the following error:

> cross-env NODE_PATH=. node server

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn NODE_PATH=. ENOENT
    at exports._errnoException (util.js:870:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at doNTCallback2 (node.js:441:9)
    at process._tickCallback (node.js:355:17)
    at Function.Module.runMain (module.js:469:11)
    at startup (node.js:136:18)
    at node.js:963:3

It does work with NODE_PATH=. node server, though. Also cross-env NODE_ENV=production works just fine.

How to use this to set multiple env variables

I don't get the test code. It uses an array to test multiple arguments.
But when using cross-env from within package.json how do I specify multiple args?

tried

cross-env NODE_ENV=production SERVER_ENV=staging
cross-env NODE_ENV=production,SERVER_ENV=staging

but it dies not set any of the variables.

OS X APPDATA

macOS env.APPDATA should be undefined, but cross-env created a 'undefined' string.

this could be better:

if (process.env.APPDATA) {
  envVars.APPDATA = process.env.APPDATA;
}

Breaking change if using in a js script

I was using cross-env with version 3.1.4 like this

const crossEnv = require('cross-env');
...
crossEnv(['node', 'bin/execute', ...argv._]);

I recently migrated to the latest version 3.2.3 and I had this error

TypeError: crossEnv is not a function

I finally found the error, I needed to change the import to

const crossEnv = require('cross-env').default;

It broke my build, so maybe more peoples are facing the same issue. Would it be possible to add some more documentation about it?

cross-env 3.0 failed running on node 0.12.7

Hello, just found latest version of cross-env is not able to startup with node v 0.12.7 on Linux.
Btw, same with cross-env@2 works fine.

Scanario:

  1. fetch lib from npm with npm install cross-env --save-dev
  2. run locally installed binary
johnny ~ $ node -v; ./node_modules/.bin/cross-env
v0.12.7
/home/johnny/node_modules/cross-env/dist/index.js:58
  var envVars = Object.assign({}, process.env);
                       ^
TypeError: undefined is not a function
    at getCommandArgsAndEnvVars (/home/johnny/node_modules/cross-env/dist/index.js:58:24)
    at crossEnv (/home/johnny/node_modules/cross-env/dist/index.js:22:35)
    at Object.<anonymous> (/home/johnny/node_modules/cross-env/bin/cross-env.js:3:19)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Bug when passing JSON string

Command ran using npm

cross-env TS_NODE_COMPILER_OPTIONS='{\"target\":\"es5\",\"module\":\"commonjs\"}' node test.js

test.js

const opts = process.env.TS_NODE_COMPILER_OPTIONS
console.log(opts)
console.log(typeof opts)
console.log('Try parse', JSON.parse(opts))

Expected:

{"target":"es5","module":"commonjs"}
string
Try parse { target: 'es5', module: 'commonjs' }

Result:

{target:es5,module:commonjs}
string
undefined:1
{target:es5,module:commonjs}
 ^

SyntaxError: Unexpected token t in JSON at position 1
    at Object.parse (native)
    at Object.<anonymous> (D:\Projects\cross-env-bug\test.js:5:31)

Tested on
Windows 10 x64
Node 6.6.0

Proper way of chaining commands when using cross-env

This isn't an issue, just a question.

I was running into an issue when trying to use cross-env to chain several npm scripts together.

    "dev": "npm run build:ui && npm run electron & npm run watch:ui",
    "electron": "cross-env NODE_ENV=development electron --debug .",
    "watch:ui": "cross-env NODE_ENV=development webpack --watch",
    "build:ui": "cross-env NODE_ENV=production webpack --progress --hide-modules",

Each of these commands (aside from dev) work as expected when run individually, but when I try to chain them with dev I get errors when other tools try to access the NODE_ENV variable. e.g.

function save(namespaces) {
  if (null == namespaces) {
    // If you set a process.env field to null or undefined, it gets cast to the
    // string 'null' or 'undefined'. Just delete instead.
    delete {"NODE_ENV":"production"}.DEBUG; // <- undefined property error
  } else {
    {"NODE_ENV":"production"}.DEBUG = namespaces; // <- unexpected token error
  }
}

I came to the repository and read your section on known limitations and understand that I shouldn't expect that environment variables set in one side of chained commands will not necessarily be set in the other side since each link is handled as a separate spawn process, but I thought having the variable declared in each step would negate that issue.

Is there a proper way of doing this kind of command chaining or do I always need to run the scripts from separate terminal calls?

Thanks!

support path variables with multiple values

NODE_PATH variable (as well as other environment variables) support multiple values (I.E. setting NODE_PATH=/home/usr:/home/lib ) .

However in windows the delimiter is a semicolon (;) and in other oses it's a colon (:) .

To support this cross-env needs to replace colons with semicolons in windows in the proper variables.

Currently I suggest adding a flag (-m) that denotes that the next environment variable should be processed (to prevent breaking backward compatibility).

Error: Cannot find module '../dist'

cross-env fails to run:

cross-env NODE_ENV=test mocha 

module.js:328
throw err;
^

Error: Cannot find module '../dist'
    at Function.Module._resolveFilename (module.js:326:15)
    at Function.Module._load (module.js:277:25)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/vlad/Development/actionhero/node_modules/cross-env/dist/bin/cross-env.js:4:1)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:442:10)
npm ERR! Test failed.  See above for more details.

Version: 3.2.1

Resolving vars in other vars

On master, cross-env MY_VAR=$MY_OTHER_VAR echo $MY_VAR on Windows results in this command: %MY_OTHER_VAR% echo %MY_VAR%, which is incorrect. #86 fixes this.

On next (i.e. with #86 merged), it results in echo %MY_VAR%, which is correct. However, in the spawned process, process.env.MY_VAR is %MY_OTHER_VAR%, which is not very useful, and I would expect it to be the value of MY_OTHER_VAR from the environment in which cross-env is run.

An easy solution would be to replace variables by their value instead of their platform-specific form (cross-var does this), but I'm not sure that's what we want. In this scenario, cross-env MY_VAR=$MY_OTHER_VAR echo $MY_VAR becomes echo <value of MY_OTHER_VAR>.

Another solution is replace variables by their value only in the part of the command that sets new variables. In this scenario, cross-env MY_VAR=$MY_OTHER_VAR echo $MY_VAR becomes echo %MY_VAR% like today but MY_VAR is properly set to <value of MY_OTHER_VAR>. I think this is better, but it requires more work as commandConvert needs to be split into two or cover the two cases.

What do you think?

Failes on installation

Type this

> npm install cross-env

And get this

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @vlsdatagroup/[email protected] No license field.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "cross-env"
npm ERR! node v7.6.0
npm ERR! npm  v4.1.2
npm ERR! path C:\Users\_\Projects\member-back\node_modules\cross-env\bin\cross-env.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall chmod

npm ERR! enoent ENOENT: no such file or directory, chmod 'C:\Users\_\Projects\member-back\node_modules\cross-env\bin\cross-env.js'
npm ERR! enoent ENOENT: no such file or directory, chmod 'C:\Users\_\Projects\member-back\node_modules\cross-env\bin\cross-env.js'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\_\Projects\member-back\npm-debug.log

Proxy all events

Currently only SIGINT is proxied to the resulting process, which runs into some limitations when using it with Docker (uses SIGTERM as well) and when sending other process signals, as they're not passed through to the process that gets spawned, resulting in sadness.

TypeError: Object function Object() { [native code] } has no method 'assign'

Hi,

I was trying to use cross-env, and had the following TypeError: (edited the folder for privacy reasons)

> [email protected] watch-js /parent_project_folder/static/js
> cross-env NODE_ENV=production watchify --extension=.jsx --extension=.js src/app.jsx -o build/build.js --debug --verbose


/parent_project_folder/static/js/node_modules/cross-env/dist/index.js:58
  var envVars = Object.assign({}, process.env);
                       ^
TypeError: Object function Object() { [native code] } has no method 'assign'
    at getCommandArgsAndEnvVars (/parent_project_folder/static/js/node_modules/cross-env/dist/index.js:58:24)
    at crossEnv (/parent_project_folder/static/js/node_modules/cross-env/dist/index.js:22:35)
    at Object.<anonymous> (/parent_project_folder/static/js/node_modules/cross-env/bin/cross-env.js:3:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3
npm ERR! weird error 8
npm ERR! not ok code 0

When running npm run watch-js I was trying to check if I correctly set the NODE_ENV variable to production, but got this error instead.

Debugging information:

$ node --version
v0.10.36
$ npm --version
1.3.6

Here's the package.json. I think that some of the devDependencies are not actually being used, in particular all babel, because I did not found a .babelrc file

    },                                                                                                                                                                                                                                         
    "scripts": {                                                                                                                                                                                                                               
      "start": "npm run build && serve .",                                                                                                                                                                                                     
      "build": "npm run build-js",                                                                                                                                                                                                             
      "watch": "node server.js",                                                                                                                                                                                                               
      "test": "npm run lint -s && npm run build",                                                                                                                                                                                              
      "build-js": "browserify --extension=.jsx --extension=.js src/app.jsx | uglifyjs > build/build.js",                                                                                                                                       
      "watch-js": "cross-env NODE_ENV=production watchify --extension=.jsx --extension=.js src/app.jsx -o build/build.js --debug --verbose",                                                                                                   
      "lint-eslint": "eslint .",                                                                                                                                                                                                               
      "lint-jscs": "jscs .",                                                                                                                                                                                                                   
      "lint": "npm run lint-eslint && npm run lint-jscs"                                                                                                                                                                                       
    },                                                                                                                                                                                                                                         
    "license": "MIT",                                                                                                                                                                                                                          
    "bugs": {                                                                                                                                                                                                                                  
      "url": "https://github.com/mgonto/react-browserify-spa-seed/issues"                                                                                                                                                                      
    },                                                                                                                                                                                                                                         
    "homepage": "https://github.com/mgonto/react-browserify-spa-seed",                                                                                                                                                                         
    "dependencies": {                                                                                                                                                                                                                          
      "bootstrap": "^3.3.0",                                                                                                                                                                                                                   
      "flux": "^2.0.1",                                                                                                                                                                                                                        
      "jwt-decode": "^1.1.0",                                                                                                                                                                                                                  
      "react": "^0.13",                                                                                                                                                                                                                        
      "react-addons": "*",                                                                                                                                                                                                                     
      "react-bootstrap": "",                                                                                                                                                                                                                   
      "react-chosen": "^0.3.8",                                                                                                                                                                                                                
      "react-intl": "~1.2.0",                                                                                                                                                                                                                  
      "react-mixin": "^1.1.0",                                                                                                                                                                                                                 
      "react-router": "^0.13.2",                                                                                                                                                                                                               
      "reqwest": "^1.1.5",                                                                                                                                                                                                                     
      "when": "^3.7.2",                                                                                                                                                                                                                        
      "underscore": "~1.8.3",                                                                                                                                                                                                                  
      "cross-env": "~3.1.3"                                                                                                                                                                                                                    
    },                                                                                                                                                                                                                                         
    "devDependencies": {                                                                                                                                                                                                                       
      "babelify": "^6.1.0",                                                                                                                                                                                                                    
      "browser-sync": "^2.1.6",                                                                                                                                                                                                                
      "browserify": "^8.0.3",                                                                                                                                                                                                                  
      "clean-css": "^3.1.9",                                                                                                                                                                                                                   
      "eslint": "^0.14.1",                                                                                                                                                                                                                     
      "rework": "^1.0.1",                                                                                                                                                                                                                      
      "rework-npm": "^1.0.0",                                                                                                                                                                                                                  
      "rework-npm-cli": "^0.1.1",                                                                                                                                                                                                              
      "serve": "^1.4.0",                                                                                                                                                                                                                       
      "uglify-js": "^2.4.15",                                                                                                                                                                                                                  
      "watchify": "^2.1.1",                                                                                                                                                                                                                    
      "babel": "~6.5.2",                                                                                                                                                                                                                       
      "webpack-bundle-tracker": "0.0.93",                                                                                                                                                                                                      
      "webpack": "~1.13.3",                                                                                                                                                                                                                    
      "babel-core": "~6.18.2",                                                                                                                                                                                                                 
      "babel-loader": "~6.2.7",                                                                                                                                                                                                                
      "babel-preset-es2015": "~6.18.0",                                                                                                                                                                                                        
      "babel-preset-react": "~6.16.0",                                                                                                                                                                                                         
      "webpack-dev-server": "~1.16.2",                                                                                                                                                                                                         
      "babel-plugin-transform-object-rest-spread": "~6.19.0"                                                                                                                                                                                   
    }

cross-env not working with webpack command?

I feel I may be implementing this incorrectly. The first command properly sets my NODE_ENV variable, however the second does not. What am I missing? Server.js provided below.

> cross-env NODE_ENV=production node server.js

Listening at localhost:3040 in production mode

As we can see, I'm now running in production mode, however if I add in the webpack command, which is noted in the example command on https://www.npmjs.com/package/cross-env, it doesn't work. (Note: NODE_ENV not found, defaulting to development)

> cross-env NODE_ENV=production webpack --config webpack.config.js && node server.js

Hash: ee27fe5be08b7d0e882f
Version: webpack 1.12.13
Time: 6720ms
                               Asset       Size  Chunks             Chunk Names
9c786af43b89a8223d3aadd741346079.png    10.5 kB          [emitted]
                           bundle.js    3.71 MB       0  [emitted]  main
                          index.html  662 bytes          [emitted]
   [0] multi main 52 bytes {0} [built]
    + 855 hidden modules
NODE_ENV not found, defaulting to development
Listening at localhost:3040 in dev mode

However, if I just use the following, everything works as expected:

> set NODE_ENV=production&& webpack --config webpack.config.js && node server.js

Hash: ee27fe5be08b7d0e882f
Version: webpack 1.12.13
Time: 6712ms
                               Asset       Size  Chunks             Chunk Names
9c786af43b89a8223d3aadd741346079.png    10.5 kB          [emitted]
                           bundle.js    3.71 MB       0  [emitted]  main
                          index.html  662 bytes          [emitted]
   [0] multi main 52 bytes {0} [built]
    + 855 hidden modules
Listening at localhost:3040 in production mode

Server.js

const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) {
    console.log('NODE_ENV not found, defaulting to development');
}

new WebpackDevServer(webpack(config), {
  hot: true,
  historyApiFallback: true
}).listen(3040, 'localhost', function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log(`Listening at localhost:3040 in ${isProduction ? 'production' : 'dev'} mode`);
});

require(...) is not a function

@kentcdodds
cross-env fails to run:

/private/var/www/ndsm/ndsm-web/webapp/node_modules/cross-env/dist/bin/cross-env.js:4
require('../')(process.argv.slice(2));
^

TypeError: require(...) is not a function
at Object. (/private/var/www/ndsm/ndsm-web/webapp/node_modules/cross-env/dist/bin/cross-env.js:4:15)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3`

Handle platform-specific list delimiters

For more context: elijahmanor/cross-var#3

Variables like $PATH or $NODE_PATH contain lists of items that are separated by ; in Windows and : in Unix. If would be good if cross-env handled this transparently.

Previous proposed solution: $: is converted to : on Unix, ; on Windows.
Example:

  • Input: PATH=$PATH$:lib npm start
  • Output (Win): PATH=%PATH%;lib npm start
  • Output (Unix): PATH=$PATH:lib npm start

The drawback is that syntax is a bit confusing, it looks like the variable is $PATH$.

Alternate solution: : in the value of a variable is converted to ; on Windows, ; is converted to : on Unix. To put the literal : or ; values, escape with a backslash (\:, \;).
Example:

  • Input: PATH=$PATH:lib GREET=Hello\:you npm start
  • Output (Win): PATH=%PATH%;lib GREET=Hello:you npm start
  • Output (Unix): PATH=$PATH:lib GREET=Hello:you npm start

Note that this would technically be a breaking change, and such a semver major release.

run npm sub-commands

Hello,

I think it is worth mentioning that you can use cross-env to run npm scripts with different variables set.

I know that you can not do

    "parentScript": "cross-env GREET='Joe' ",
    "childScript": "npm run parentScript && echo Hello $GEET"

But if you want to split a command into several ones, or separate the environment variables from the actual command execution, you can do it this way:

    "parentScript": "cross-env GREET='Joe' npm run childScript",
    "childScript": "echo Hello $GEET"

So instead of run the childScript you run the parent. This is quite useful for launching the same command with different env variables or when the environment variables are too long to have everything in one line.

Regards

Behavior with environment variables defined "outside of" cross-env

While trying to find a solution to write npm scripts command lines using npm variables (e.g. npm_package_name), I found that cross-env doesn't see to recognize them, as if only variables defined using cross-env would be recognized.

For instance, with a package.json file containing:

"name": "my-nice-app",
scripts: {
    "cross_env": "cross-env echo $npm_package_name"
}

This results in the following on Windows (with Windows cmd, CygWin bash or VSCode bash):

$ npm run cross_env
%npm_package_name%

where I would expect it to echo my-nice-app.
Is it a known and accepted limitation or a bug?

add appveyor badge

I would do it myself, but it has a unique value that only the owner @kentcdodds can look up in settings. For example, a project of mine is Build status where my project key is v4eagpd8k731oyul

Extend to allow running local node in windows/linux

A number of projects want to avoid version problems by using their local copy of node. So an entry might be
"scripts": {
"clean": "../../node_modules/.bin/rimraf build"
}

Unfortunately this fails on windows because although

"scripts": {
"clean": "rimraf build"
}

picks up rimraf.cmd, if you specify the path explicitly, it doesn't. So it occured to me that if cross-env could do this, it might make everything better:

"scripts": {
"clean": "cross-env PATH=$(npm bin);$PATH rimraf build"
}

stdio doesn't appear to be getting written to

Following the examples from nyc (https://github.com/istanbuljs/nyc#user-content-use-with-babel-plugin-istanbul-for-es6es7es2015-support), I set up my package.json file to look like this:

test: cross-env NODE_ENV=test nyc mocha --compilers js:babel-register --recursive \"test/**/*.js\"

This command would fail and not give any Error so I couldn't really tell what was happening.

When I removed the cross-env command, as in:

test: nyc mocha --compilers js:babel-register --recursive \"test/**/*.js\"

I saw that some previous refactoring had changed a path to a file and an import was breaking.

Error: Cannot find module '../../../../../shared/components/genericTable/GenericTableCellText'

I'm sure I'm just doing something dumb, but it appears that cross-env is eating that error when it gets called (being cross-env spawns the process). I cannot find anything in the README or looking through the code to prevent this, so not sure what I am doing wrong...

how could you compile the cource code?

Hello,I found that the source code is written in ES6,but there is no tool and configuration exist to compile it.
So,I would like to ask how could you compile it automatically.

It seems that cross-env NODE_ENV=something doesn't work

Hi,
i use cross-env on my mac.
I've tried it with node v6.3.1 and v5.12.0, but it seems that it doesn't work well.
After launching

$ ./node_modules/.bin/cross-env NODE_ENV=development

and

$ printenv

i can't see NODE_ENV.

But, if i try to set it with

$ export NODE_ENV=development

works fine.

Maybe there are some breaking changes?

Commits Incorrectly Fail Due To linebreak-style Issues On Windows When Git Config core.autocrlf = true

I forked your repository to commit a small change, which I intended to contribute back to your repo via pull request. However, after I made the change using my Windows computer and attempted to commit by running npm run commit and answering the commitizen prompts, the commit failed to complete due to lint errors in a number of files which I never even touched. Specifically, the linebreak-style lint rule was complaining that a number of files had CRLF linebreak characters instead of LF characters. I completely understand why this check is in place, as Windows editors often silently convert LF to CRLF, and if left unchecked this can cause problems for other systems (not to mention strange behavior from Git itself) if those changed linebreak characters get committed back into the repository and pushed to the remote.

However, in my case I have the global git config flag core.autocrlf (see documentation) set to true on my Windows machine (it applies to all repositories on my machine). This resolves the linebreak character issue by causing Git to automatically covert LF characters to CRLF in my working directory when checking out files from the repository, and then automatically converting CRLF back to LF when file changes are staged to the index (and subsequently committed to the repository). This ensures that the repository always has LF characters, while also enabling Windows users who set core.autocrlf to true to have CRLF used instead in the files in their working directories.

Unfortunately, the way you currently have your lint rules configured, every time someone tries to commit it checks the linebreak characters in every file in the working directory, even if that file is not staged to be committed. This is causing all of my commit attempts to fail, as even though the files which I changed and staged to be committed have the correct LF linebreak characters (as core.autocrlf=true converted 'CRLF' back to 'LF' in those files when I staged them), your lint check is still detecting the CRLF characters in all of the other files in my working directory, even though I never made changes to them and did not stage them (those files have CRLF characters because core.autocrlf=true converted LF to CRLF when the files were checked out into my working directory).

I would suggest changing your lint checks for linebreak-style to only be run on whatever is currently staged in the index, instead of on every file in the working directory, if that is possible. Otherwise, anyone on a Windows machine who has their global Git config for core.autocrlf set to true will never be able to commit (setting core.autocrlf to true on Windows machines is best practice, as it prevents Git from ever committing CRLF characters into the repo accidentally).

screenshot1

no env has been set after I run cross-env

i have add a script in package json as below
"dev": "cross-env NODE_ENV=development nodemon ./server/server.dev.js --watch server --watch build --watch config ",

but process.env.NODE_ENV returns undefined in node program.
Is there anything wrong in my script.

i have also run cross-env in terminal. But i still got undefined.

robindeMacBook-Pro:20170109_11602_1 robin$ cross-env NODE_ENV=dev
robindeMacBook-Pro:20170109_11602_1 robin$ node
> process.env.NODE_ENV
undefined
>

Add conditional equality checking

Add conditional basic equality match checking to be able compose script hooks to only run when certain environment criteria are met.

{
  "scripts": {
    "postinstall": "cross-env NODE_ENV==development && npm run build"
  }
}
  • ==
  • !=

Perhaps this should be a separate module argv-get-env to match up with argv-set-env.

Suggestion: support reading environment variables from a file.

A few ideas for this:

cross-env TEST
cross-env ./env.json

In the first example cross-env would see a single argument with no equals sign and look for a "VAR": "VAL" mapping somewhere (e.g., in package.json under config.environments, similar to how ghooks looks for hook definitions under config.ghooks).

In the second example cross-env would see a relative path to a file and require that. This file would just be a simple "VAR": "VAL" listing in a single object. YAML is tempting here, but probably very unnecessary.

Both of these options would allow for more easily reusable environments and promote shorter script strings when lots of environment variables are used (or even just long environment variables).

If pattern matching against the argument is too shaky, we can always implement a flag or two:

cross-env -e TEST
cross-env -f ./env.json

Support for variables in complex statements

Due to a recent feature (Convert environment vars) the cross-var package can almost be deprecated. The one thing the library could support that cross-env does not yet (to my understanding) is complex statements.

The API for complex statements is to wrap the contents in a string so that all the variables can be replaced and then executed. What do you all think of this API and would it fit well with cross-env? If this type of feature was added to cross-env then cross-var shouldn't be needed anymore.

{
  "version": "1.0.0",
  "config": {
    "port": "1337"
  },
  "scripts": {
    "simple1": "cross-var rimraf public/$npm_package_version",
    "simple2": "cross-var http-server public/$npm_package_version -p $npm_package_config_port",
    "complex": "cross-var \"node-sass src/index.scss | postcss -c .postcssrc.json | cssmin > public/$npm_package_version/index.min.css\""
  }
}

Support setting env variables for all scripts at one time?

So a common use case is that developers want to to always set a certain env variables for all scripts. For instance, the handy NODE_PATH variable that let's developers get rid of relative requires in their scripts.

Currently, if we want to set this, we have to do it in each of the individual npm scripts like so:

"scripts": {
   "test": "cross-env NODE_PATH=./es6 mocha"
   "something": "cross-env NODE_PATH=./es6 node blah.js"
   ...
}

But it would be super handy if we could just do in one place like so:

"cross-env": {
   "NODE_PATH": "./es6"
},
"scripts": {
   "test": "mocha"
   "something": "node blah.js"
   ...
}

I've looked into npm and I actually don't see any great way to support this, but there might be. It would be awesome IMO in any case though. What are your thoughts Kent? Both on feasibility and desirability?

Error: Cannot find module './command'

Hi there! I see that a new update to your module was published to NPM about 5 mins ago, but it seems to have completely broken our CI build process and unit tests :(

We have the following setup within package.json which runs our unit tests:

{
  "scripts": {
    "test": "scripts/test.sh"
  }
}

...and our scripts/test.sh reads as follows:

#!/usr/bin/env bash

TEST_TYPE='unit'
[ -n "$1" ] && TEST_TYPE="$1"

NODE_ENV='development'
[ -n "$2" ] && NODE_ENV="$2"

KARMA_CONFIG='karma.'$TEST_TYPE'.conf.js'

cross-env NODE_ENV=$NODE_ENV karma start build/$KARMA_CONFIG --single-run --test-type $TEST_TYPE

When we run npm run test now we get the following error right away now:

> scripts/test.sh

module.js:341
    throw err;
    ^

Error: Cannot find module './command'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/paul/dev/clones/app-activations-ui/node_modules/cross-env/dist/index.js:13:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)

npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/Cellar/node5/5.12.0/bin/node" "/usr/local/bin/npm" "run" "test"
npm ERR! node v5.12.0
npm ERR! npm  v3.8.6
npm ERR! code ELIFECYCLE
npm ERR! [email protected] test: `scripts/test.sh`
npm ERR! Exit status 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.