Within my Angular app , and while building it , i ve to catch the app version , which is inside my package.json file and copy it to another file which would be not a json file.
My package.json file :
{
"name": "my app",
"author": "ME",
"version": "0.1.3",
"scripts": {
"ng": "ng",
"start": "ng serve --public-host --port 4222 http://localhost:4222/",
"build": "ng build",
"sync-version": "sync-json -v --property version --source package.json projects/cockpit-tools/package.json && sync-json -v --property version --source package.json projects/cockpit-tools-demo/src/assets/configuration/properties.json",
"sync-custom": "shx node -p -e \"require('./package.json').version\"",
"copy-version":"MY_COMMAND"
...
}
My target file is properties file whih looks like this , and which is located in same path of package.json (this file is used in another level of automation , that's why i can't change it)
app-infos.properties
project.version=0.0.0
project.author=ME
My purpose is to write a command line task script which i may run to synchronize / copy the version from package.json to the project.version property inside my target file.
I ve tried an npm library called sync-version , but that works only when the target is a json file
I ve tried also to do it with shell command line within the shx package. also that didn't work as expected.
i ve also tried some node.js tricks (require ...) but the problem persists
i need to find a way to do it with the simpliest way and not be obliged to install some linux tools or similar(jq or other) , since this would run in some CI CD contexts , so that would rather to be as native and as generic as possible.
Suggestions ?
A classic DevOps situation :)
CI/CD usually happens on linux envs.
You will probably have plain shell/bash.
Try extractinf the version to a variable:
myVersion=`grep 'version:' package.json | awk '{print $2}'`
then replacing it in the apps-info:
sed -i "s/0.0.0/$myVersion/" apps-info.properties
We can make ot more generic by always pulling the last version instead of 0.0.0,
but i think you should have a place holder like 0.0.0
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",
},
I am reading the data from an API and downloading a file. I want to save the same file in public folder of react application.
this.state = {
fileDownloadUrl: null,
fileName: '',
};
below is the method.
downLoadFile(e) {
e.preventDefault();
axios
.get(
'http://localhost:8080/file_download/en'
)
.then((res) => {
var output = res.data;
const blob = new Blob([output]);
const fileDownloadUrl = URL.createObjectURL(blob);
this.setState({ fileDownloadUrl: fileDownloadUrl }, () => {
this.dofileDownload.click();
URL.revokeObjectURL(fileDownloadUrl);
this.setState({ fileDownloadUrl: '' });
});
});
}
code for downloading the file.
<a
className="hidden"
download={this.state.fileName + '.json'}
href={this.state.fileDownloadUrl}
ref={(e) => (this.dofileDownload = e)}
>
download it
</a>
Is there anyway I can modify the code so that file can be saved in the public folder of react application. later this file will be used for translation.
There's no way to automatically download a file and save it in a specific location on your hard disk from a frontend app running inside a browser. The users of your app will decide how the file is saved based on their browser settings.
If you're trying to achieve that kind of thing, then that's wrong and you should consider another approach.
It's not possible because this poses a security risk.
Most of the OS will defaults the download to download folder.
Pure browser-JavaScript is not be able to get information about the user's filesystem. The default download path might also contain sensible information, which is risky.
To sum up the question, the challenge is to fetch or otherwise produce certain static file assets for React to consume.
As other answers pointed out, it's impossible to do from React itself. I'd add, if it were possible, that would be inefficient, unsafe and insecure.
Architecturally, it's best to create a file-generating script and run it before the React application's build step.
I'm using such setup myself. For example, if you checked my package.json I've got scripts:
{
"scripts": {
"--------- BUILD ---------": "",
"build": "npm run ops && run-s build:*",
"build:remix": "remix build",
"build:css": "npm run generate:css",
"--------- DEV ---------": "",
"dev": "npm run ops && run-p dev:*",
"dev:remix": "cross-env NODE_ENV=development remix dev",
"dev:css": "npm run generate:css -- --watch",
"generate:css": "sass styles:app/styles app/components",
"format": "prettier --write .",
"--------- TEST ---------": "",
"start:mocks": "cross-env NODE_ENV=production node --require ./mocks --require dotenv/config ./build/server.js",
"test": "vitest run --coverage",
"test:e2e:dev": "start-server-and-test dev http://localhost:3000 \"cypress open\"",
"pretest:e2e:run": "npm run build",
"test:e2e:run": "cross-env PORT=8811 start-server-and-test start:mocks http://localhost:8811 \"cypress run\"",
"--------- LINT ---------": "",
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
"typecheck": "tsc -b && tsc -b cypress",
"validate": "run-p \"test -- --run\" lint typecheck test:e2e:run",
"--------- OPS ---------": "",
"ops": "run-p ops:*",
"ops:static": "node ./ops/extract-static-data.mjs",
"ops:search": "node ./ops/extract-search.mjs",
"ops:rss": "node ./ops/extract-rss.mjs"
}
}
notice how ops group of scripts is triggered before the React build step. I generate static fresh files:
lump of all h2 heading strings for aside to set currently active anchor
all MDX front matter lump of all articles for rendering MDX outside normal routes (article lists, search etc.)
the final HTML of RSS feed; I render HTML with all remark goodies such as syntax titles, syntax highlighting and typography
compile the search data file and index file (for warm starts) for fuse.js
I'd fetch locales this way too: npm-triggered script would fetch and atomically save a file straight into /public/.
It's done during build-time rather than runtime to simplify the setup and lower the server bill. I disagree with Mr. Dodds in this aspect; more so, runtime libraries such as mdx-bundler don't even support pure ESM, so actually, runtime-oriented approaches often don't even work. For example, if you take the same Mr. Dodds' blog, it doesn't have the current anchor tracking in single posts or site-wide search or automated typography processing.
PS. Interestingly, if you look at the static site generators, 11ty lets you fetch extra sources from the 11ty config itself, that's where you would fetch the locales of yours on 11ty.
The Problem
Trying to lint an old React application that has 30+ console.logs() throughout the code base. I setup a linter and code formatter, ESLint and Prettier respectively.
This setup works great and it shows me where the console.logs() are in the source. But, the --fix flag for ESLint does not remove the logs. Is there any way to automatically remove console.logs()? I've seen articles on how to do this via webpack to prevent the logs from going into production, however, I would like to remove these earlier in a pre-commit or pre-push hook for instance.
What I've Tried
I tried setting up a script using gulp-strip-debug. It fails with an assertion error. When I changed the src path from './src/**.js' to './**.js' I do not get the assertion error but nothing happens.
Learned about this from Jun711 blog. The "How to remove console log from your JavaScript files programmatically?" blog post.
Gulpfile
gulpfile.js: root of project directory
const gulp = require('gulp');
const stripDebug = require('gulp-strip-debug');
gulp.task(
'strip-debug',
() =>
gulp
.src('./src/**.js') // input file path
.pipe(stripDebug()) // execute gulp-strip-debug
.pipe(gulp.dest('./')) // output file path
);
Package.json
{
"name": "end-the-pandemic",
"version": "1.0.0",
"dependencies": {
"shelter-in-place": "11.5.20",
"stay-home": "11.5.21",
"who-is-still-voting-for-trump": "11.3.20",
"seriously-why": "2.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"lint": "eslint '*/**/*.js' --quiet --fix",
"clean": "gulp strip-debug",
"test": "react-scripts test",
"eject": "react-scripts eject",
},
...
Terminal
yarn clean
Output
AssertionError [ERR_ASSERTION]: Task function must be specified
Obviously, I could have done a search and deleted most of them manually with the time I spent writing this question but for future reference, is there anyway to do this with a command? I would like to put yarn clean in a pre-commit hook if possible.
You could make this trick it would be good in this case
if (env === 'production') {
console.log = function () {};
}
this will overwrite the real log function into an empty one
make sure you add it at the top of your react app
Another solution
there is a package called babel-plugin-transform-remove-console could help you
after installing it from npm
npm install babel-plugin-transform-remove-console
after installing create a .babelrc file in your project root dir
and add this line to it
{
"plugins": ["transform-remove-console"]
}
Is it possible to get what package.json script has been called in NodeJS code?
My package.json file contains a script that builds the application:
{
"name": "notes-app",
"version": "0.0.1",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build && node server.js"
},
etc, etc...
Can I then write in my server.js file an if statement like:
if (script === 'build') {
// Do something
}
Is there a way of knowing what script was called when starting the app. I would start this using the command npm run build. Also I'm using windows if that would make any difference.
I agree with yury, you must be detecting this for a reason, and maybe a more fit solution lies in that context.
However, when this is important (like for system administration) it is usually done by setting an environment variable in the scripts section and then testing process.env in the node js.