How to prepend text to a file as an npm script command - package.json

I'm writing a bookmarklet. I need to prepend "javascript:" to the compiled, minified JavaScript. I'm looking for a way to accomplish this using an NPM package.json script.
{
"scripts": {
"oar:transpile-typescript": "tsc --target es6 --lib dom,es6 ./OarBookmarklet/Oar.ts",
"oar:minify-javascript": "jsmin -o ./OarBookmarklet/oar.min.js ./OarBookmarklet/oar.js",
"oar:prepend-javascript": "[??? prepend `javascript:` to minified JavaScript ???]",
"oar": "run-s oar:transpile-typescript oar:minify-javascript oar:prepend-javascript",
"build": "run-s oar"
}
}

For a cross-platform solution utilize node.js and it's builtin fs.readFileSync(...) and fs.writeFileSync(...). This way it doesn't matter which shell your npm script runs in (sh, cmd.exe, bash, bash.exe, pwsh, ... )
To achieve this consider either of the following two solutions - they're essentially the same just different methods of application.
Solution A. Using a separate node.js script
Create the following script, lets save it as prepend.js in the root of the project directory, i.e. at the same level as where package.json resides.
prepend.js
const fs = require('fs');
const filepath = './OarBookmarklet/oar.min.js';
const data = fs.readFileSync(filepath);
fs.writeFileSync(filepath, 'javascript:' + data);
package.json
Define the oar:prepend-javascript npm script in package.json as follows::
"scripts": {
...
"oar:prepend-javascript": "node prepend",
...
},
Note: Above node.js invokes the script and performs the required task. If you choose to save prepend.js in a different directory than the aforementioned then ensure you define the correct path to it, i.e. "oar:prepend-javascript": "node ./some/other/path/to/prepend.js"
Solution B. Inline the node.js script in package.json
Alternatively, you can inline the content of prepend.js in your npm script, therefore negating the use of a separate .js file.
package.json
Define the oar:prepend-javascript script in package.json as follows:
"scripts": {
...
"oar:prepend-javascript": "node -e \"const fs = require('fs'); const fp = './OarBookmarklet/oar.min.js'; const d = fs.readFileSync(fp); fs.writeFileSync(fp, 'javascript:' + d);\""
...
},
Note: Here the nodejs command line option -e is utilized to evaluate the inline JavaScript.

If this is running on something Unix-like then:
(printf 'javascript:' ; cat ./OarBookmarklet/oar.min.js) > ./OarBookmarklet/oar.bm.min.js
should do the job.
Edit in response to OP's comment:
My execution environment is Windows, ...
In that case you should be able to use:
(set /p junk="javascript:" <nul & type ./OarBookmarklet/oar.min.js) > ./OarBookmarklet/oar.bm.min.js
The set /p ... <nul weirdness is a way to get some text sent to stdout without a newline being appended to it.

Related

pass command line argument in vscode test runner script (index.ts)

Scenario:
script in package.json file looks like:
"test": "node ./out/test/runTest.js"
this runTest.js then calls test runner script src/test/suite/index.ts . Source of this file is : https://code.visualstudio.com/api/working-with-extensions/testing-extension
In the index.ts, it uses source like:
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
Here, glob is pointing to the src files to consider for test run.
Question:
For specific reason, I don't want to test all files using regex like: glob('**/**.test.js'
I want to test specific file and I want to pass it by my test script in package.json file.
For ex: I want
"test": "node ./out/test/runTest.js Filename"
And glob() in index.ts file will consider only this Filename for execution.
I need some help in this regards.
Thanks again
The way to pass arguments from npm scripts inside package.json is via environment variables. The syntax is slightly different depending on the platform. The example below is for Windows.
"test": "set FileName=foo.js&node ./out/test/runTest.js"
The argument and the value is now awailable inside runTest.js in process.env
console.log(process.env.FileName); //foo.js
In the src/test/suite/index.ts open your package.json file and search for the "test" script line and parse it for the arguments.
Edit
I needed something similar and added a file: test-arguments.txt next to index.js or maybe in .vscode folder if you use typescript.
Inside index.js I open the file and parse the arguments. I allow lines to be commented with #.
By adding this test-arguments.txt file to .gitignore I don't have to modify package.json and my team members can have different arguments.

Node v15.5.0 doesn't read command line flags [duplicate]

The scripts portion of my package.json currently looks like this:
"scripts": {
"start": "node ./script.js server"
}
...which means I can run npm start to start the server. So far so good.
However, I would like to be able to run something like npm start 8080 and have the argument(s) passed to script.js (e.g. npm start 8080 => node ./script.js server 8080). Is this possible?
npm 2 and newer
It's possible to pass args to npm run since npm 2 (2014). The syntax is as follows:
npm run <command> [-- <args>]
Note the -- separator, used to separate the params passed to npm command itself, and the params passed to your script.
With the example package.json:
"scripts": {
"grunt": "grunt",
"server": "node server.js"
}
here's how to pass the params to those scripts:
npm run grunt -- task:target // invokes `grunt task:target`
npm run server -- --port=1337 // invokes `node server.js --port=1337`
Note: If your param does not start with - or --, then having an explicit -- separator is not needed; but it's better to do it anyway for clarity.
npm run grunt task:target // invokes `grunt task:target`
Note below the difference in behavior (test.js has console.log(process.argv)): the params which start with - or -- are passed to npm and not to the script, and are silently swallowed there.
$ npm run test foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test -- foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -- -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '-foobar']
$ npm run test -- --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '--foobar']
The difference is clearer when you use a param actually used by npm:
$ npm test --help // this is disguised `npm --help test`
npm test [-- <args>]
aliases: tst, t
To get the parameter value, see this question. For reading named parameters, it's probably best to use a parsing library like yargs or minimist; nodejs exposes process.argv globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).
You asked to be able to run something like npm start 8080. This is possible without needing to modify script.js or configuration files as follows.
For example, in your "scripts" JSON value, include--
"start": "node ./script.js server $PORT"
And then from the command-line:
$ PORT=8080 npm start
I have confirmed that this works using bash and npm 1.4.23. Note that this work-around does not require GitHub npm issue #3494 to be resolved.
You could also do that:
In package.json:
"scripts": {
"cool": "./cool.js"
}
In cool.js:
console.log({ myVar: process.env.npm_config_myVar });
In CLI:
npm --myVar=something run-script cool
Should output:
{ myVar: 'something' }
Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_ variables? I'm also using better-npm-run, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar, try process.env.npm_config_myvar
jakub.g's answer is correct, however an example using grunt seems a bit complex.
So my simpler answer:
- Sending a command line argument to an npm script
Syntax for sending command line arguments to an npm script:
npm run [command] [-- <args>]
Imagine we have an npm start task in our package.json to kick off webpack dev server:
"scripts": {
"start": "webpack-dev-server --port 5000"
},
We run this from the command line with npm start
Now if we want to pass in a port to the npm script:
"scripts": {
"start": "webpack-dev-server --port process.env.port || 8080"
},
running this and passing the port e.g. 5000 via command line would be as follows:
npm start --port:5000
- Using package.json config:
As mentioned by jakub.g, you can alternatively set params in the config of your package.json
"config": {
"myPort": "5000"
}
"scripts": {
"start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},
npm start will use the port specified in your config, or alternatively you can override it
npm config set myPackage:myPort 3000
- Setting a param in your npm script
An example of reading a variable set in your npm script. In this example NODE_ENV
"scripts": {
"start:prod": "NODE_ENV=prod node server.js",
"start:dev": "NODE_ENV=dev node server.js"
},
read NODE_ENV in server.js either prod or dev
var env = process.env.NODE_ENV || 'prod'
if(env === 'dev'){
var app = require("./serverDev.js");
} else {
var app = require("./serverProd.js");
}
As of npm 2.x, you can pass args into run-scripts by separating with --
Terminal
npm run-script start -- --foo=3
Package.json
"start": "node ./index.js"
Index.js
console.log('process.argv', process.argv);
I had been using this one-liner in the past, and after a bit of time away from Node.js had to try and rediscover it recently. Similar to the solution mentioned by #francoisrv, it utilizes the npm_config_* variables.
Create the following minimal package.json file:
{
"name": "argument",
"version": "1.0.0",
"scripts": {
"argument": "echo \"The value of --foo is '${npm_config_foo}'\""
}
}
Run the following command:
npm run argument --foo=bar
Observe the following output:
The value of --foo is 'bar'
All of this is nicely documented in the npm official documentation:
https://docs.npmjs.com/using-npm/config
Note: The Environment Variables heading explains that variables inside scripts do behave differently to what is defined in the documentation. This is true when it comes to case sensitivity, as well whether the argument is defined with a space or equals sign.
Note: If you are using an argument with hyphens, these will be replaced with underscores in the corresponding environment variable. For example, npm run example --foo-bar=baz would correspond to ${npm_config_foo_bar}.
Note: For non-WSL Windows users, see #Doctor Blue's comments below... TL;DR replace ${npm_config_foo} with %npm_config_foo%.
Use process.argv in your code then just provide a trailing $* to your scripts value entry.
As an example try it with a simple script which just logs the provided arguments to standard out echoargs.js:
console.log('arguments: ' + process.argv.slice(2));
package.json:
"scripts": {
"start": "node echoargs.js $*"
}
Examples:
> npm start 1 2 3
arguments: 1,2,3
process.argv[0] is the executable (node), process.argv[1] is your script.
Tested with npm v5.3.0 and node v8.4.0
Most of the answers above cover just passing the arguments into your NodeJS script, called by npm. My solution is for general use.
Just wrap the npm script with a shell interpreter (e.g. sh) call and pass the arguments as usual. The only exception is that the first argument number is 0.
For example, you want to add the npm script someprogram --env=<argument_1>, where someprogram just prints the value of the env argument:
package.json
"scripts": {
"command": "sh -c 'someprogram --env=$0'"
}
When you run it:
% npm run -s command my-environment
my-environment
If you want to pass arguments to the middle of an npm script, as opposed to just having them appended to the end, then inline environment variables seem to work nicely:
"scripts": {
"dev": "BABEL_ARGS=-w npm run build && cd lib/server && nodemon index.js",
"start": "npm run build && node lib/server/index.js",
"build": "mkdir -p lib && babel $BABEL_ARGS -s inline --stage 0 src -d lib",
},
Here, npm run dev passes the -w watch flag to babel, but npm run start just runs a regular build once.
For PowerShell users on Windows
The accepted answer did not work for me with npm 6.14. Neither adding no -- nor including it once does work. However, putting -- twice or putting "--" once before the arguments does the trick. Example:
npm run <my_script> -- -- <my arguments like --this>
Suspected reason
Like in bash, -- instructs PowerShell to treat all following arguments as literal strings, and not options (E.g see this answer). The issues seems to be that the command is interpreted one time more than expected, loosing the '--'. For instance, by doing
npm run <my_script> -- --option value
npm will run
<my_script> value
However, doing
npm run <my_script> "--" --option value
results in
<my_script> "--option" "value"
which works fine.
This doesn't really answer your question but you could always use environment variables instead:
"scripts": {
"start": "PORT=3000 node server.js"
}
Then in your server.js file:
var port = process.env.PORT || 3000;
I've found this question while I was trying to solve my issue with running sequelize seed:generate cli command:
node_modules/.bin/sequelize seed:generate --name=user
Let me get to the point. I wanted to have a short script command in my package.json file and to provide --name argument at the same time
The answer came after some experiments. Here is my command in package.json
"scripts: {
"seed:generate":"NODE_ENV=development node_modules/.bin/sequelize seed:generate"
}
... and here is an example of running it in terminal to generate a seed file for a user
> yarn seed:generate --name=user
> npm run seed:generate -- --name=user
FYI
yarn -v
1.6.0
npm -v
5.6.0
Note: This approach modifies your package.json on the fly, use it if you have no alternative.
I had to pass command line arguments to my scripts which were something like:
"scripts": {
"start": "npm run build && npm run watch",
"watch": "concurrently \"npm run watch-ts\" \"npm run watch-node\"",
...
}
So, this means I start my app with npm run start.
Now if I want to pass some arguments, I would start with maybe:
npm run start -- --config=someConfig
What this does is: npm run build && npm run watch -- --config=someConfig. Problem with this is, it always appends the arguments to the end of the script. This means all the chained scripts don't get these arguments(Args maybe or may not be required by all, but that's a different story.). Further when the linked scripts are called then those scripts won't get the passed arguments. i.e. The watch script won't get the passed arguments.
The production usage of my app is as an .exe, so passing the arguments in the exe works fine but if want to do this during development, it gets problamatic.
I couldn't find any proper way to achieve this, so this is what I have tried.
I have created a javascript file: start-script.js at the parent level of the application, I have a "default.package.json" and instead of maintaining "package.json", I maintain "default.package.json". The purpose of start-script.json is to read default.package.json, extract the scripts and look for npm run scriptname then append the passed arguments to these scripts. After this, it will create a new package.json and copy the data from default.package.json with modified scripts and then call npm run start.
const fs = require('fs');
const { spawn } = require('child_process');
// open default.package.json
const defaultPackage = fs.readFileSync('./default.package.json');
try {
const packageOb = JSON.parse(defaultPackage);
// loop over the scripts present in this object, edit them with flags
if ('scripts' in packageOb && process.argv.length > 2) {
const passedFlags = ` -- ${process.argv.slice(2).join(' ')}`;
// assuming the script names have words, : or -, modify the regex if required.
const regexPattern = /(npm run [\w:-]*)/g;
const scriptsWithFlags = Object.entries(packageOb.scripts).reduce((acc, [key, value]) => {
const patternMatches = value.match(regexPattern);
// loop over all the matched strings and attach the desired flags.
if (patternMatches) {
for (let eachMatchedPattern of patternMatches) {
const startIndex = value.indexOf(eachMatchedPattern);
const endIndex = startIndex + eachMatchedPattern.length;
// save the string which doen't fall in this matched pattern range.
value = value.slice(0, startIndex) + eachMatchedPattern + passedFlags + value.slice(endIndex);
}
}
acc[key] = value;
return acc;
}, {});
packageOb.scripts = scriptsWithFlags;
}
const modifiedJSON = JSON.stringify(packageOb, null, 4);
fs.writeFileSync('./package.json', modifiedJSON);
// now run your npm start script
let cmd = 'npm';
// check if this works in your OS
if (process.platform === 'win32') {
cmd = 'npm.cmd'; // https://github.com/nodejs/node/issues/3675
}
spawn(cmd, ['run', 'start'], { stdio: 'inherit' });
} catch(e) {
console.log('Error while parsing default.package.json', e);
}
Now, instead of doing npm run start, I do node start-script.js --c=somethis --r=somethingElse
The initial run looks fine, but haven't tested thoroughly. Use it, if you like for you app development.
I find it's possible to just pass variables exactly as you would to Node.js:
// index.js
console.log(process.env.TEST_ENV_VAR)
// package.json
...
"scripts": { "start": "node index.js" },
...
TEST_ENV_VAR=hello npm start
Prints out "hello"
From what I see, people use package.json scripts when they would like to run script in simpler way. For example, to use nodemon that installed in local node_modules, we can't call nodemon directly from the cli, but we can call it by using ./node_modules/nodemon/nodemon.js. So, to simplify this long typing, we can put this...
...
scripts: {
'start': 'nodemon app.js'
}
...
... then call npm start to use 'nodemon' which has app.js as the first argument.
What I'm trying to say, if you just want to start your server with the node command, I don't think you need to use scripts. Typing npm start or node app.js has the same effort.
But if you do want to use nodemon, and want to pass a dynamic argument, don't use script either. Try to use symlink instead.
For example using migration with sequelize. I create a symlink...
ln -s node_modules/sequelize/bin/sequelize sequelize
... And I can pass any arguement when I call it ...
./sequlize -h /* show help */
./sequelize -m /* upgrade migration */
./sequelize -m -u /* downgrade migration */
etc...
At this point, using symlink is the best way I could figure out, but I don't really think it's the best practice.
I also hope for your opinion to my answer.
Separate your arguments using -- from the script and add all the required arguments, we can later access them by index.
npm run start -- myemail#gmail.com 100
You can get params in node using
const params = process.argv.slice(2);
console.log(params);
Output
['myemail#gmail.com', '100']
I know there is an approved answer already, but I kinda like this JSON approach.
npm start '{"PROJECT_NAME_STR":"my amazing stuff", "CRAZY_ARR":[0,7,"hungry"], "MAGICAL_NUMBER_INT": 42, "THING_BOO":true}';
Usually I have like 1 var I need, such as a project name, so I find this quick n' simple.
Also I often have something like this in my package.json
"scripts": {
"start": "NODE_ENV=development node local.js"
}
And being greedy I want "all of it", NODE_ENV and the CMD line arg stuff.
You simply access these things like so in your file (in my case local.js)
console.log(process.env.NODE_ENV, starter_obj.CRAZY_ARR, starter_obj.PROJECT_NAME_STR, starter_obj.MAGICAL_NUMBER_INT, starter_obj.THING_BOO);
You just need to have this bit above it (I'm running v10.16.0 btw)
var starter_obj = JSON.parse(JSON.parse(process.env.npm_config_argv).remain[0]);
Anyhoo, question already answered. Thought I'd share, as I use this method a lot.
I settled for something like this, look at the test-watch script:
"scripts": {
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest",
"test-watch": "cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 tsc-watch --onSuccess",
},
You invoke the test-watch script like this:
// Run all tests with odata in their name
npm run test-watch "jest odata"
npm run script_target -- < argument > Basically this is the way of passing the command line arguments but it will work only in case of when script have only one command running like I am running a command i.e. npm run start -- 4200
"script":{
"start" : "ng serve --port="
}
This will run for passing command line parameters but what if we run more then one command together like npm run build c:/workspace/file
"script":{
"build" : "copy c:/file <arg> && ng build"
}
but it will interpreter like this while running copy c:/file && ng build c:/work space/file
and we are expected something like this
copy c:/file c:/work space/file && ng build
Note :- so command line parameter only work ad expected in case of only one command in a script.
I read some answers above in which some of them are writing that you can access the command line parameter using $ symbol but this will not gonna work
Try cross-env NPM package.
Easy to use. Easy to install. Cross all platform.
Example:
set arguments for command
// package.json
"scripts": {
“test”: “node test.js”,
“test-with-env-arg”: “cross-env YourEnvVarName=strValue yarn test,
}
get arguments from process.env
// test.js
const getCommandLineArg = Boolean(process.env.YourEnvVarName === 'true') // Attention: value of process.env.* is String type, not number || boolean
i had the same issue when i need to deploy to different environments
here is the package.json pre and post the updates.
scripts:
{"deploy-sit": "sls deploy --config resources-sit.yml",
"deploy-uat": "sls deploy --config resources-uat.yml",
"deploy-dev": "sls deploy --config resources-dev.yml"}
but here is the correct method to adopt the environment variables rather than repeating ourselves
scripts:{"deploy-env": "sls deploy --config resources-$ENV_VAR.yml"}
finally you can deploy by running
ENV_VAR=dev npm run deploy-env

How to disable warnings when node is launched via a (global) shell script

I am building a CLI tool with node, and want to use the fs.promise API. However, when the app is launched, there's always an ExperimentalWarning, which is super annoying and messes up with the interaction prompts. How can I disable this warning/all warnings?
I'm testing this with the latest node v10 lts release on Windows 10.
To use the CLI tool globally, I have added this to my package.json file:
{
//...
"preferGlobal": true,
"bin": { "myapp" : "./index.js" }
//...
}
And have run npm link to link the ./index.js script. Then I am able to run the app globally simply with myapp.
After some research I noticed that there are generally 2 ways to disable the warnings:
set environmental variable NODE_NO_WARNINGS=1
call the script with node --no-warnings ./index.js
Although I was able to disable the warnings with the 2 methods above, there seems to be no way to do that while directly running myapp command.
The shebang I placed in the entrance script ./index.js is:
#!/usr/bin/env node
// my code...
I have also read other discussions on modifying the shebang, but haven't found a universal/cross-platform way to do this - to either pass argument to node itself, or set the env variable.
If I publish this npm package, it would be great if there's a way to make sure the warnings of this single package are disabled in advance, instead of having each individual user tweak their environment themselves. Is there any hidden npm package.json configs that allow this?
Any help would be greatly appreciated!
I am now using a launcher script to spawn a child_process to work around this limitation. Ugly, but it works with npm link, global installs and whatnot.
#!/usr/bin/env node
const { spawnSync } = require("child_process");
const { resolve } = require("path");
// Say our original entrance script is `app.js`
const cmd = "node --no-warnings " + resolve(__dirname, "app.js");
spawnSync(cmd, { stdio: "inherit", shell: true });
As it's kind of like a hack, I won't be using this method next time, and will instead be wrapping the original APIs in a promise manually, sticking to util.promisify, or using the blocking/sync version of the APIs.
I configured my test script like this:
"scripts": {
"test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest"
},
Notice the NODE_NO_WARNINGS=1 part. It disables the warnings I was getting from setting NODE_OPTIONS=--experimental-vm-modules
Here's what I'm using to run node with a command line flag:
#!/bin/sh
_=0// "exec" "/usr/bin/env" "node" "--experimental-repl-await" "$0" "$#"
// Your normal Javascript here
The first line tells the shell to use /bin/sh to run the script. The second line is a bit magical. To the shell it's a variable assignment _=0// followed by "exec" ....
Node sees it as a variable assignment followed by a comment - so it's almost a nop apart from the side effect of assigning 0 to _.
The result is that when the shell reaches line 2 it will exec node (via env) with any command line options you need.
New answer: You can also catch emitted warnings in your script and choose which ones to prevent from being logged
const originalEmit = process.emit;
process.emit = function (name, data, ...args) {
if (
name === `warning` &&
typeof data === `object` &&
data.name === `ExperimentalWarning`
//if you want to only stop certain messages, test for the message here:
//&& data.message.includes(`Fetch API`)
) {
return false;
}
return originalEmit.apply(process, arguments);
};
Inspired by this patch to yarn

Node ncp copy without overwriting (no clobber) in command line mode

GNU copy has the -n flag to copy without overwriting like so:
cp -n config.ini.dist config.ini
Is there a way to get the same functionality from the npm package ncp on the command line?
My aim is to copy a distributed configuration file for a npm package:
"scripts": {
"prepare": "ncp config.dist.ini config.ini -n",
...
However it does not know the -n flag and overwrites existing files.
If you scroll down the page of the documentation link you provided, you’ll find that setting the clobber option to false will do what you’re asking for.
options.clobber - boolean=true. if set to false, ncp will not overwrite destination files that already exist.
For command line use, it appears from looking at their source code that the CLI does not expose the 'clobber' option to the CLI. Fortunately, it's pretty easy to fix this yourself with your own little utility:
//./bin/ncp
#!/usr/env node
const ncp = require('ncp').ncp;
ncp.limit = 16;
// note: also add error handling. I'm also being explicit here, you can
// use their bin file for a more extensive example: https://github.com/AvianFlu/ncp/blob/master/bin/ncp
const source = process.argv[2];
const destination = process.argv[3];
// note you can get fancier and read the options in from the CLI if you want, I'm just assuming you know what you want to always use here.
ncp(source, destination, { clobber: false }, function (err) {
if (err) {
return console.error(err);
process.exit(1);
}
console.log('done!');
process.exit(1):
});
Then in your package.json you can just do
"scripts": { "prepare": "./bin/ncp config.ini.dist config.ini"}}
Hope that helps.
You can use cp in windows like this
"scripts": {
"build": "ng build && npm run build:server && npm run cp",
"build:server": "tsc --build server/tsconfig.json",
"cp": "#powershell cp server/config.json,server/notice.json dist/server",
...
'#powershell' will run cp as powershell command

Add git information to create-react-app

In development, I want to be able to see the build information (git commit hash, author, last commit message, etc) from the web. I have tried:
use child_process to execute a git command line, and read the result (Does not work because browser environment)
generate a buildInfo.txt file during npm build and read from the file (Does not work because fs is also unavailable in browser environment)
use external libraries such as "git-rev"
The only thing left to do seems to be doing npm run eject and applying https://www.npmjs.com/package/git-revision-webpack-plugin , but I really don't want to eject out of create-react-app. Anyone got any ideas?
On a slight tangent (no need to eject and works in develop),
this may be of help to other folk looking to add their current git commit SHA into their index.html as a meta-tag by adding:
REACT_APP_GIT_SHA=`git rev-parse --short HEAD`
to the build script in the package.json and then adding (note it MUST start with REACT_APP... or it will be ignored):
<meta name="ui-version" content="%REACT_APP_GIT_SHA%">
into the index.html in the public folder.
Within react components, do it like this:
<Component>{process.env.REACT_APP_GIT_SHA}</Component>
I created another option inspired by Yifei Xu's response that utilizes es6 modules with create-react-app. This option creates a javascript file and imports it as a constant inside of the build files. While having it as a text file makes it easy to update, this option ensures it is a js file packaged into the javascript bundle. The name of this file is _git_commit.js
package.json scripts:
"git-info": "echo export default \"{\\\"logMessage\\\": \\\"$(git log -1 --oneline)\\\"}\" > src/_git_commit.js",
"precommit": "lint-staged",
"start": "yarn git-info; react-scripts start",
"build": "yarn git-info; react-scripts build",
A sample component that consumes this commit message:
import React from 'react';
/**
* This is the commit message of the last commit before building or running this project
* #see ./package.json git-info for how to generate this commit
*/
import GitCommit from './_git_commit';
const VersionComponent = () => (
<div>
<h1>Git Log: {GitCommit.logMessage}</h1>
</div>
);
export default VersionComponent;
Note that this will automatically put your commit message in the javascript bundle, so do ensure no secure information is ever entered into the commit message. I also add the created _git_commit.js to .gitignore so it's not checked in (and creates a crazy git commit loop).
It was impossible to be able to do this without ejecting until Create React App 2.0 (Release Notes) which brought with it automatic configuration of Babel Plugin Macros which run at compile time. To make the job simpler for everyone, I wrote one of those macros and published an NPM package that you can import to get git information into your React pages: https://www.npmjs.com/package/react-git-info
With it, you can do it like this:
import GitInfo from 'react-git-info/macro';
const gitInfo = GitInfo();
...
render() {
return (
<p>{gitInfo.commit.hash}</p>
);
}
The project README has some more information. You can also see a live demo of the package working here.
So, turns out there is no way to achieve this without ejecting, so the workaround I used is:
1) in package.json, define a script "git-info": "git log -1 --oneline > src/static/gitInfo.txt"
2) add npm run git-info for both start and build
3) In the config js file (or whenever you need the git info), i have
const data = require('static/gitInfo.txt')
fetch(data).then(result => {
return result.text()
})
My approach is slightly different from #uidevthing's answer. I don't want to pollute package.json file with environment variable settings.
You simply have to run another script that save those environment variables into .env file at the project root. That's it.
In the example below, I'll use typescript but it should be trivial to convert to javascript anyway.
package.json
If you use javascript it's node scripts/start.js
...
"start": "ts-node scripts/start.ts && react-scripts start",
scripts/start.ts
Create a new script file scripts/start.ts
const childProcess = require("child_process");
const fs = require("fs");
function writeToEnv(key: string = "", value: string = "") {
const empty = key === "" && value === "";
if (empty) {
fs.writeFile(".env", "", () => {});
} else {
fs.appendFile(".env", `${key}='${value.trim()}'\n`, (err) => {
if (err) console.log(err);
});
}
}
// reset .env file
writeToEnv();
childProcess.exec("git rev-parse --abbrev-ref HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_BRANCH", stdout);
});
childProcess.exec("git rev-parse --short HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_SHA", stdout);
});
// trick typescript to think it's a module
// https://stackoverflow.com/a/56577324/9449426
export {};
The code above will setup environment variables and save them to .env file at the root folder. They must start with REACT_APP_. React script then automatically reads .env at build time and then defines them in process.env.
App.tsx
...
console.log('REACT_APP_GIT_BRANCH', process.env.REACT_APP_GIT_BRANCH)
console.log('REACT_APP_GIT_SHA', process.env.REACT_APP_GIT_SHA)
Result
REACT_APP_GIT_BRANCH master
REACT_APP_GIT_SHA 042bbc6
More references:
https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env
If your package.json scripts are always executed in a unix environment you can achieve the same as in #NearHuscarl answer, but with fewer lines of code by initializing your .env dotenv file from a shell script. The generated .env is then picked up by the react-scripts in the subsequent step.
"scripts": {
"start": "sh ./env.sh && react-scripts start"
"build": "sh ./env.sh && react-scripts build",
}
where .env.sh is placed in your project root and contains code similar to the one below to override you .env file content on each build or start.
{
echo BROWSER=none
echo REACT_APP_FOO=bar
echo REACT_APP_VERSION=$(git rev-parse --short HEAD)
echo REACT_APP_APP_BUILD_DATE=$(date)
# ...
} > .env
Since the .env is overridden on each build, you may consider putting it on the .gitignore list to avoid too much noise in your commit diffs.
Again the disclaimer: This solution only works for environments where a bourne shell interpreter or similar exists, i.e. unix.
You can easily inject your git information like commit hash into your index.html using CRACO and craco-interpolate-html-plugin. Such way you won't have to use yarn eject and it also works for development server environment along with production builds.
After installing CRACO the following config in craco.config.js worked for me:
const interpolateHtml = require('craco-interpolate-html-plugin');
module.exports = {
plugins: [
{
plugin: interpolateHtml,
// Enter the variable to be interpolated in the html file
options: {
BUILD_VERSION: require('child_process')
.execSync('git rev-parse HEAD', { cwd: __dirname })
.toString().trim(),
},
},
],
};
and in your index.html:
<meta name="build-version" content="%BUILD_VERSION%" />
Here are the lines of code to add in package.json to make it all work:
"scripts": {
"start": "craco start",
"build": "craco build"
}

Resources