Giter Site home page Giter Site logo

cross-var's Introduction

cross-var

NPM NPM

npm version npm license npm download npm download Package Quality Inline docs star this repo fork this repo

david dependency david devDependency david optionalDependency david peerDependency npms score Known Vulnerabilities

Overview

When using npm scripts it creates a lot of environment variables that are available for you to leverage when executing scripts.

If you'd like to take a look at all of the variables then you can run npm run env in your terminal.

> npm run env

npm_package_name=cross-var
npm_package_author_name=Elijah Manor
npm_package_version=1.0.0
... lots more ...

Now you can use those environment variables in your npm scripts by referencing them like the following

{
  "name": "World",
  "scripts": {
    "//": "The following only works on Mac OS X/Linux (bash)",
    "bash-script": "echo Hello $npm_package_name"
    "//": "The following only works on a Windows machine",
    "win-script": "echo Hello %npm_package_name%"
  }
}
> npm run bash-script

Hello World

However, this won't work on Windows... because it expects the variables to be surrounded by percent signs, so we can change our script just slightly.

cross-var to the Rescue!

The goal of cross-var is to let you use one script syntax to work either on a Mac OS X/Linux (bash) or Windows. Reference the Usage documention below on how to use cross-var in your scripts.

Usage

Simple Commands

{
  "version": "1.0.0",
  "config": {
    "port": "1337"
  },
  "scripts": {
    "prebuild": "cross-var rimraf public/$npm_package_version",
    "build:html": "cross-var jade --obj data.json src/index.jade --out public/$npm_package_version/",
    "server:create": "cross-var http-server public/$npm_package_version -p $npm_package_config_port",
    "server:launch": "cross-var opn http://localhost:$npm_package_config_port"
  }
}

Complex Commands

{
  "version": "1.0.0",
  "scripts": {
    "build:css": "cross-var \"node-sass src/index.scss | postcss -c .postcssrc.json | cssmin > public/$npm_package_version/index.min.css\"",
    "build:js": "cross-var \"mustache data.json src/index.mustache.js | uglifyjs > public/$npm_package_version/index.min.js\"",
  }
}

But What About!?!

Click on one of the following questions to reveal a detailed answer

Why don't you use `cross-env`? `cross-env` is great for scripts that need a particular environment variable set, but isn't intended to fix cross-environment issues when using variables inside an `npm script`
Why don't you use an external node file? That is a fine solution to this problem, but if you would rather stick to straight up `npm scripts`, then this is a good solution
Why don't you just use Windows 10 Ubuntu-based Bash shell? Yes, if you can do that... then great! Windows 10’s version 1607 update, dubbed the “Anniversary Update”, has [intergrated a great bash shell](https://msdn.microsoft.com/en-us/commandline/wsl/about) that should allow you to run Linux software directly on Windows without any changes.

However, if you want to support older Windows versions, then you might consider using cross-env or another approach to leverage environment variables in your scripts.

cross-var's People

Contributors

elijahmanor avatar hekard2l avatar vzwick 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

cross-var's Issues

`cross-replace` is a drop in replacement for this project...without the security problems and some aditional improvements

I looked at the other project that was created to replace this one, but it wasn't a drop in replacement. Also, it was using bun - which I'm not looking to experiment with quite yet - so I didn't want to modify that project to bring it to parity with this one...

cross-replace is a drop in replacement for this project.

https://www.npmjs.com/package/cross-replace

I also fixed a few of the issues in this project:

  • it doesn't break when variables have special characters
  • works with more than one variable in the same command
  • works in a folder whose name contains "src"
  • it supports the ${var} variable syntax

I also added some unit tests that run in a github workflow pipeline against MacOS, Linux, and Windows:

  • multiple variables are replaced
  • variables that aren't found are replaced with blanks
  • $var ${var} %var% replacements are all tested

Error if used before source command

I need to run a source command to load in environment variables before running the executable. Seems as though cross-var only works if it is placed directly before an executable. The following returns an error:

...
"start": "cross-var source $npm_package_config_devEnvtVars && meteor --settings $npm_package_config_devEnvtSettings --port $npm_package_config_portMeteor",
...

Removing cross-var resolves the error:

$ cross-var source $npm_package_config_devEnvtVars && meteor --settings $npm_package_config_devEnvtSettings --port $npm_package_config_portMeteor 
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: spawn source ENOENT
    at exports._errnoException (util.js:1022:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
    at onErrorNT (internal/child_process.js:359:16)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Module.runMain (module.js:607:11)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:535:3
error Command failed with exit code 1.
...
"start": "source $npm_package_config_devEnvtVars && meteor --settings $npm_package_config_devEnvtSettings --port $npm_package_config_portMeteor",
...

Support `${}` syntax

Hello,

Thanks for this great tool, it is a lifesaver.
However, I noticed that you only understand variables with the traditional notation $varname, but there are many many times where the specific notation (not sure how to call it) is needed in order to concatenate variables and other stuff. I'm talking about ${varname}

Thanks in advance

Crashes with version 1.0.3

When executing a simple script like the following yarn throws a "ReferenceError: Unknown plugin "transform-runtime"" on execution. Im using yarn version 0.27.5 on macOS but I've seen the same problem with npm and Windows.

{
	"scripts": {
		"cross": "cross-var echo $npm_package_version"
        }
       [..]
}

The complete error is

~/D/P/d/w/s/m/webapp develop ❯ yarn cross                                                                                                                                             ✭ ✚ ✱
yarn cross v0.27.5
$ cross-var echo $npm_package_version
/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

ReferenceError: Unknown plugin "transform-runtime" specified in "/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/regenerator-transform/package.json" at 0, attempted to resolve relative to "/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/regenerator-transform" (While processing preset: "/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-preset-es2015/lib/index.js")
    at /Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
    at Array.map (<anonymous>)
    at Function.normalisePlugins (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at compile (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-register/lib/node.js:103:45)
    at loader (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-register/lib/node.js:144:14)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/benke/Documents/Projects/destimo/war/src/main/webapp/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
error Command failed with exit code 1.

Handling platform specific delimiters

This isn't necessarily an issue, but it'd be nice to handle platform specific delimiters for environment variables that contain a list of entries.

$PATH and $NODE_PATH are examples of entry lists. NODE_PATH documentation.

On Windows the delimiter is ; (semicolon) and is : (colon) on most other platforms.

Would there be a clean way to replace : with ; on Windows without disrupting users that actually want to insert : on Windows?

Only works for the first variable

I have a script like this:

"scripts": {
    "build": "cross-var npm run clean --project=$npm_config_project && webpack --progress -p --config $npm_config_project/webpack.prod.js",
    "clean": "cross-var rimraf $npm_config_project/build"
  }

When I run 'npm run build --project=my-project' it gives this error:
Error: Cannot find module '......\$npm_config_project\webpack.prod.js'
However, if I remove
npm run clean --project=$npm_config_project &&
from the script so that the build script is:
"build": "cross-var webpack --progress -p --config $npm_config_project/webpack.prod.js"
it works without any error.

Is it because cross-var only works for the first variable in the script?

Doesn´t work with two or more variables

I´m trying to make this command works, but I can´t:
"accessibility:local": "cross-var \"axe http://localhost:$npm_package_config_localport --timeout=120 --save accessibility-test-results.json --tags $npm_package_config_axeconfiguration\""

I´ve tried without double quotes before axe and it´s the same.

Some workaround guys? Thanks!

Deprecated Babel pacakge used

I see babel-preset-es2015 is one of the dependency, but its deprecated now, can we have the alternative package used here ?

Dependency upgrade

Hi,

I find this project pretty helpful.
Is there any plan to upgrade the dependencies?

Regards

Ignore a variable

Hi,

In an NPM script, cross-var erases the $f variable in a for loop:

"rollup": "cross-var \"for f in $npm_package_config_js_folder/*.js; do rollup $f --format iife --dir temp/rollup --no-strict; done && cat temp/rollup/*.js > temp/script.rollup.js\""

How to make it ignore $f?

Thanks!

reducing dependencies

I've just realized there are ~134 indirect dependencies.
Is there any chance to reduce that number?

$NODE and $NODE_DEBUG_OPTION get commingled

Given the environment

$ echo $NODE
C:\Program Files\nodejs\node.exe

$ echo $NODE_DEBUG_OPTION
--debug-brk-59757 --expose-debug-as=v8debug

If I create a task that runs

cross-var echo NODE_DEBUG_OPTION=$NODE_DEBUG_OPTION

it comes back with

NODE_DEBUG_OPTION=C:\Program Files\nodejs\node.exe_DEBUG_OPTION

As you can see, the process that plugs the variables in is replacing the $NODE part of $NODE_DEBUG_OPTION with the contents of $NODE.

Unable to use in a folder whose name contains "src"

If I try to run a simple command like yarn cross-var ls it gives me this error:

E:\Dropbox\Programming\src\node_modules\babel-core\lib\transformation\file\options\option-manager.js:328
        throw e;
        ^

ReferenceError: Unknown plugin "transform-runtime" specified in "E:\\Dropbox\\Programming\\src\\node_modules\\regenerato
r-transform\\package.json" at 0, attempted to resolve relative to "E:\\Dropbox\\Programming\\src\\node_modules\\regenera
tor-transform" (While processing preset: "E:\\Dropbox\\Programming\\src\\node_modules\\babel-preset-es2015\\lib\\index.j
s")
    at E:\Dropbox\Programming\src\node_modules\babel-core\lib\transformation\file\options\option-manager.js:180:17
    at Array.map (native)
    at Function.normalisePlugins (E:\Dropbox\Programming\src\node_modules\babel-core\lib\transformation\file\options\opt
ion-manager.js:158:20)
    at OptionManager.mergeOptions (E:\Dropbox\Programming\src\node_modules\babel-core\lib\transformation\file\options\op
tion-manager.js:234:36)
    at OptionManager.init (E:\Dropbox\Programming\src\node_modules\babel-core\lib\transformation\file\options\option-man
ager.js:368:12)
    at compile (E:\Dropbox\Programming\src\node_modules\babel-register\lib\node.js:103:45)
    at loader (E:\Dropbox\Programming\src\node_modules\babel-register\lib\node.js:144:14)
    at Object.require.extensions.(anonymous function) [as .js] (E:\Dropbox\Programming\src\node_modules\babel-register\l
ib\node.js:154:7)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)

If I rename the folder to anything without src in the name, the command works fine.

Cannot find module './_arrayEach' on windows

I am successfully using cross-var on a mac, however, running the same command on a windows 10 machine gives me this error

This is the simplest thing to do to replicate (extract from package.json):

 "devDependencies": {
    "concurrently": "^6.2.0",
    "cross-var": "^1.1.0",
    "dotenv-cli": "^4.0.0",
    "if-env": "^1.0.4"
  },
  "scripts": {
    ...
    "start": "cross-var",
    ...
  }
yarn start

and the error:

c:\src\simple-app>yarn start
yarn run v1.22.10
$ cross-var
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module './_arrayEach'
Require stack:
- c:\src\simple-app\node_modules\lodash\_baseClone.js
- c:\src\simple-app\node_modules\lodash\cloneDeep.js
- c:\src\simple-app\node_modules\babel-register\lib\node.js
- c:\src\simple-app\node_modules\cross-var\index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (c:\src\simple-app\node_modules\lodash\_baseClone.js:2:17)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'c:\\src\\simple-app\\node_modules\\lodash\\_baseClone.js',
    'c:\\src\\simple-app\\node_modules\\lodash\\cloneDeep.js',
    'c:\\src\\simple-app\\node_modules\\babel-register\\lib\\node.js',
    'c:\\src\\simple-app\\node_modules\\cross-var\\index.js'
  ]
}
error Command failed with exit code 1.

Continue maintaining this project

Dear @elijahmanor,

Thank you for this lib which is used by hundreds of other libs! Would you please consider continuing maintaining this project? Or at least allow some one from the community to maintain it?

I've just ran across this weird bug of 'src' folders (src was a great great parent of the cwd) which took a couple of exhausting hours to just figure out that the problem was lying in cross-var which was used in a tiny dependency that I've never worked with!

Thanks.

Exit code transmission (1.0.3)

cross-var "false"; echo $? returns 0, while false; echo $? returns 1
Was this intended ?
I thought cross-var would transmit the underlying command exit code but it doesn't seems so.

Thanks for this very useful package, by the way !

Throws stderr maxBuffer exceeded error for some commands

Version

npm: 3.10.10
cross-var: 1.0.3
OS: Win 10

Steps

  • Create a npm command which will output lot of logs file, like a highly verbose webpack build
  • Use cross-var to run this command
  • The following error will be thrown, and no output will be generated while the command is being executed.
exec error: Error: stderr maxBuffer exceeded

Expected
cross-var should pipe the output to console to prevent buffer from exceeding.

Usage as dependency in apps that also use babel

Ran into an odd issue today while using cross-var on Mac with an app that uses babel and webpack. Basically, when using a cross-var command in an npm script, we were getting an error originating from babel-preset-env. Which was odd because the npm script that we were running doesn't have anything to do with babel. After trying many things, we disabled the use of cross-var in that script and it then worked fine.

Looking at the source for cross-var, it appears that the main index.js file uses babel-require in order to do transpiling inline. My theory is that because cross-var depends on babel-register for inline transpiling, it was picking up our babel config and the presets being used by cross-var weren't matching what we used in the app.

Long story short, the fix is to transpile before publishing so that cross-var plays nicer with other babel consumers. Submitting a PR for this shortly. Nice side effect is removing dependency on babel from the installed package.

Error if you have any environment var set with key name having special chars

At the index.js file, there the normalize function iterate through all user's environment vars and create the following regex const regex = new RegExp(\$${ key }|%${ key }%, "ig" ); using each of them.
As a sample on my OS I have an entry for Notepad++ as a key. the plus sign, a special regex char, breaks the code at this time.

The solution is to replace all special chars inside the keys with it preceded by the scape slash.

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.