VSCode Task to run various node commands - node.js

I have a monorepo where I wish to create a script for starting up a specific project locally.
The project is completely Node.js based.
For me to set up this project locally for development, I need to run the following commands in this order:
Start up the docker images
cd docker/dockerForTests
docker-compose up -d
Start up the Web Auth server
cd src/project/webAuthentication
setenvs projectAuthentication && npm start
Start up the API
cd src/project/api
setenvs projectAPI && npm start
Start up the web client
cd src/project/web
setenvs projectWeb && npm start
I usually start each section up in a new terminal window, within VSCode, for ease of use.
To automate this process, I found out about VSCode Tasks.
Although it appears they are designed for 'building' or 'watching' tasks, I thought that I could modify the behavior to run the above commands for me.
Here was my attempt:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"runner": "terminal",
"version": "2.0.0",
"tasks": [
{
"label": "Start Docker",
"dependsOrder": "sequence",
"type": "shell",
"command": "cd docker/dockerForTests && docker-compose up -d",
},
{
"label": "Start Web Auth",
"dependsOrder": "sequence",
"type": "process",
"command": "cd src/project/webAuthentication && setenvs projectAuthentiction && npm start"
},
{
"label": "Start Up Local Development Environment",
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "new",
"showReuseMessage": false,
"clear": true
},
"dependsOn": [
"Start Docker",
"Start Web Auth"
],
"problemMatcher": []
}
]
}
The first command works fine, but I wanted it to be like the integrated terminal, where it hangs for input once the command has finished running.
Secondly, the second task does not work as it's not a Node command.
I would like it to work like the regular, bash input.
How can I automate my above workflow? Is it even possible?

At least for points 2, 3 and 4 concurrently works fine, and it should work fine for point 1 as well. With following scripts in scripts section of package.json in your root directory you should be able to launch your dev env with just one command
"start-docker": "cd docker/dockerForTests && docker-compose up -d",
"start-auth": "cd src/project/webAuthentication && setenvs projectAuthentication && npm start",
"start-api": "cd src/project/api && setenvs projectAPI && npm start",
"start-client": "cd src/project/web && setenvs projectWeb && npm start",
"start-dev": "concurrently \"npm run start-docker\" \"npm run start-auth\" \"npm run start-api\" \"npm run start-client\""
This doesn't use VSCode task, but would simplify your life anyway.

You should be able to add the necessary scripts to the root package.json's scripts section. Once you do that, you should see them as VS Code tasks, thanks to VS Code's automatic task detection.
See https://code.visualstudio.com/docs/editor/tasks#_task-autodetection for details.

Related

Reduce Loopback4 build times in development (build + restart dev server)

I am using Loopback4 to develop api in Node.
I was using the instruction given to build and watch with nodemon
It worked, but it was getting slow, like about 15 seconds in my case.
I search for other other solution and came up with idea of using Turborepo and the nodemon solution.
I wanted to know if there are better solutions or any issues with it
Gist of the solution
run build in watch mode and restart the dev server if js files in dist folder change
use Turbo repo to run these build and restart server tasks
Steps
Setup build and watch with nodemon as described in the thread
you should have something like this in the script
"scripts": {
"dev:server:watch": "nodemon server.js"
}
// watch src folder
// ignore dist
// ext only ts files
// npm start to start the dev server on any changes to the files
"nodemonConfig": {
"verbose": true,
"watch": [
"src/"
],
"ignore": [
"dist/*"
],
"ext": "ts",
"exec": "npm start"
}
Install turbo build system
yarn add turbo --dev
Update nodemon config to restart server on changes in js files in dist folder after build step
"nodemonConfig": {
"verbose": true,
"watch": [
"./dist/"
],
"ext": "js",
"exec": "yarn run start"
},
Add turbo.json
{
"pipeline": {
"dev": {
"dependsOn": ["build:watch", "dev:server:watch"]
},
"build:watch": {
"outputs": [
".dist/**"
]
},
"lint": {
"outputs": []
}
}
}
Add dev script in package.json "scripts"
"dev": "turbo run dev",
Run
yarn run dev
This seems to have reduced the build times to about 3 seconds
Can anyone confirm if this is an acceptable solution, points out any issues
Thanks

VSCode: how to set shell/args for automatically detected npm scripts

I'm trying to start NPM scripts from VSCode with a custom shell (I want the NPM command to be directly prefixed by wsl.exe --, e.g. wsl.exe -- npm start). I've found a way to make it work but it requires me to set my task type to "shell" and set my shell config like so:
"version": "2.0.0",
"options": {
"shell": { <-- Shell config that I need
"executable": "wsl.exe",
"args": [
"--"
]
},
},
"tasks": [
{
"type": "shell", <-- Sample task I want to execute
"command": "npm start",
"label": "...",
"detail": "...",
},
But VSCode automatic tasks detection ("NPM Scripts" section of the sidebar) uses tasks with the type set as "npm" instead of "shell". This is the config VSCode uses for such automatic tasks:
{
"type": "npm", <-- NPM task that I want, but for which the shell config won't apply
"script": "start",
"problemMatcher": [],
"label": "npm: start",
"detail": "ng serve --proxy-config proxy.conf.json"
}
And this type of tasks do not use the shell config from the first example above (it uses wsl.exe -e <npm command> instead, which can't work in my environment) Is there a way to set a terminal/shell config for this specific kind of tasks?
To reformulate: can I set a shell executable and args for tasks of type "npm" (if so, how?) or I am forced to use tasks of type "shell" and give up on using VSCode automatic tasks detection (which are of the "npm" type)?

How to replace nodemon in a way that accommodates --inspect=9230

I have an npm script that starts apollo graphql and works as such:
"dev":"dotenv -e \"../.env.${SOME_ENV_VAR}\" nodemon --config nodemon.dev.json ./src/main.ts
I now want to slightly change it with the equivalent of the node --inspect=9230 parameter.
How would I rewrite this script to effectively do the same thing but allow debugging on port 9230 (not the default port of 9229)?
Additionally, even better if I can add the concept of graphql schema file auto reload like:
"debug": "concurrently \"tsc -w\" \"npm run watchgraphql\" \"nodemon --inspect build/dist/index.js\"",
"watchgraphql": "cpx 'src/graphql/schemas/**/*.graphql' build/dist/graphql/schemas/ -w -v"
I would normally just use the above graphql sample script but it lacks the dotenv -e \"../.env.${SOME_ENV_VAR}\" part from my originally stated goal.
Whatever I have done, I have not been able to infuse the concept of dotenv -e \"../.env.${SOME_ENV_VAR}\" in to the graphql script example... The command and parameter parsing gets all messed up and nothing executes properly.
nodemon.dev.json:
{
"watch": [
"src"
],
"ext": "ts,gql",
"ignore": [
"src/**/*.spec.ts",
"src/types/**/*.d.ts"
],
"register": [
"graphql-import-node/register"
],
"execMap": {
"ts": "ts-node"
}
}
Thanks
Directly from nodemon's README.
You can also pass the inspect flag to node through the command line as you would normally:
nodemon --inspect ./server.js 80
it should be enough:
"dev": "dotenv -e \"../.env.${SOME_ENV_VAR}\" nodemon --config nodemon.dev.json --inspect=9230 ./src/main.ts"

How to chain custom script in package.json to call prestart mongod?

Trying to streamline my package.json and local development with a custom script to run Nodemon. I'm currently building an app with a front and back end I need to call mongod before start and before my custom in two tabs however I'm running into an issue.
mongod will only run in the terminal if the terminal path is set to local from testing and I've read:
Correct way of starting mongodb and express?
npm starts to execute many prestart scripts
How to npm start at a different directory
How do I add a custom script to my package.json file that runs a javascript file?
I can use prestart as:
"scripts": {
"prestart": "cd && mongod",
"start": "node app",
"nodemon": "./node_modules/.bin/nodemon app"
}
but I'm not seeing how I should chain a prestart with a custom scripts. When I try to chain it with nodemon as:
"scripts": {
"prestart": "cd && mongod",
"start": "node app",
"nodemon": "cd && mongod && ./node_modules/.bin/nodemon app"
},
Nodemon is fired first than mongodb crashes in my package.json when I call Nodemon as:
npm run nodemon
How can I start mongod before starting nodemon in my development process through one command in the package.json?

Run two tasks/scripts that both "hog the terminal" [duplicate]

In my package.json I have these two scripts:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
}
I have to run these 2 scripts in parallel everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:
"dev": "npm run start-watch && npm run wp-server"
... but that will wait for start-watch to finish before running wp-server.
How can I run these in parallel? Please keep in mind that I need to see the output of these commands. Also, if your solution involves a build tool, I'd rather use gulp instead of grunt because I already use it in another project.
Use a package called concurrently.
npm i concurrently --save-dev
Then setup your npm run dev task as so:
"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""
If you're using an UNIX-like environment, just use & as the separator:
"dev": "npm run start-watch & npm run wp-server"
Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:
"dev": "npm-run-all --parallel start-watch wp-server"
From windows cmd you can use start:
"dev": "start npm run start-watch && start npm run wp-server"
Every command launched this way starts in its own window.
You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you'll need to manually stop it after all tests are finished.
This is an example for protractor testing through npm:
scripts: {
"webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
"protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
"http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
"test": "npm-run-all -p -r webdriver-start http-server protractor"
}
-p = Run commands in parallel.
-r = Kill all commands when one of them finishes with an exit code of zero.
Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.
I've checked almost all solutions from above and only with npm-run-all I was able to solve all problems. Main advantage over all other solution is an ability to run script with arguments.
{
"test:static-server": "cross-env NODE_ENV=test node server/testsServer.js",
"test:jest": "cross-env NODE_ENV=test jest",
"test": "run-p test:static-server \"test:jest -- {*}\" --",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watchAll",
}
Note run-p is shortcut for npm-run-all --parallel
This allows me to run command with arguments like npm run test:watch -- Something.
EDIT:
There is one more useful option for npm-run-all:
-r, --race - - - - - - - Set the flag to kill all tasks when a task
finished with zero. This option is valid only
with 'parallel' option.
Add -r to your npm-run-all script to kill all processes when one finished with code 0. This is especially useful when you run a HTTP server and another script that use the server.
"test": "run-p -r test:static-server \"test:jest -- {*}\" --",
I have a crossplatform solution without any additional modules. I was looking for something like a try catch block I could use both in the cmd.exe and in the bash.
The solution is command1 || command2 which seems to work in both enviroments same. So the solution for the OP is:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
// first command is for the cmd.exe, second one is for the bash
"dev": "(start npm run start-watch && start npm run wp-server) || (npm run start-watch & npm run wp-server)",
"start": "npm run dev"
}
Then simple npm start (and npm run dev) will work on all platforms!
If you replace the double ampersand with a single ampersand, the scripts will run concurrently.
How about forking
Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.
Minimal example
This would just run the scripts as-is and assume they're located in the parent script's directory.
// fork-minimal.js - run with: node fork-minimal.js
const childProcess = require('child_process');
let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));
Verbose example
This would run the scripts with arguments and configured by the many available options.
// fork-verbose.js - run with: node fork-verbose.js
const childProcess = require('child_process');
let scripts = [
{
path: 'some-script.js',
args: ['-some_arg', '/some_other_arg'],
options: {cwd: './', env: {NODE_ENV: 'development'}}
},
{
path: 'some-other-script.js',
args: ['-another_arg', '/yet_other_arg'],
options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
}
];
let runningScripts= [];
scripts.forEach(script => {
let runningScript = childProcess.fork(script.path, script.args, script.options);
// Optionally attach event listeners to the script
runningScript.on('close', () => console.log('Time to die...'))
runningScripts.push(runningScript); // Keep a reference to the script for later use
});
Communicating with forked scripts
Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.
runningScripts.forEach(runningScript => runningScript.kill());
For more available events and methods see the ChildProcess documentation
npm-run-all --parallel task1 task2
edit:
You need to have npm-run-all installed beforehand. Also check this page for other usage scenarios.
Quick Solution
In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &
An example of doing this in a partial package.json file:
{
"name": "npm-scripts-forking-example",
"scripts": {
"bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
"serve": "http-server -c 1 -a localhost",
"serve-bundle": "npm run bundle & npm run serve &"
}
You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:
"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",
Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:
Further Context RE: Unix Tools & Node.js
If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:
Much of Node.js lovingly imitates Unix principles
You're on *nix (incl. OS X) and NPM is using a shell anyway
Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.
step by step guide to run multiple parallel scripts with npm.
install npm-run-all package globally
npm i -g npm-run-all
Now install and save this package within project where your package.json exists
npm i npm-run-all --save-dev
Now modify scripts in package.json file this way
"scripts": {
"server": "live-server index.html",
"watch": "node-sass scss/style.scss --watch",
"all": "npm-run-all --parallel server watch"
},
now run this command
npm run all
more detail about this package in given link
npm-run-all
with installing npm install concurrently
"scripts": {
"start:build": "tsc -w",
"start:run": "nodemon build/index.js",
"start": "concurrently npm:start:*"
},
Use concurrently to run the commands in parallel with a shared output stream. To make it easy to tell which output is from which process, use the shortened command form, such as npm:wp-server. This causes concurrently to prefix each output line with its command name.
In package.json, your scripts section will look like this:
"scripts": {
"start": "concurrently \"npm:start-watch\" \"npm:wp-server\"",
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server"
}
npm install npm-run-all --save-dev
package.json:
"scripts": {
"start-watch": "...",
"wp-server": "...",
"dev": "npm-run-all --parallel start-watch wp-server"
}
More info: https://github.com/mysticatea/npm-run-all/blob/master/docs/npm-run-all.md
In a package.json in the parent folder:
"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"
this work in windows
Just add this npm script to the package.json file in the root folder.
{
...
"scripts": {
...
"start": "react-scripts start", // or whatever else depends on your project
"dev": "(cd server && npm run start) & (cd ../client && npm run start)"
}
}
... but that will wait for start-watch to finish before running wp-server.
For that to work, you will have to use start on your command. Others have already illustrated but this is how it will work, your code below:
"dev": "npm run start-watch && npm run wp-server"
Should be :
"dev": " start npm run start-watch && start npm run wp-server"
What this will do is, it will open a separate instance for each command and process them concurrently, which shouldn't be an issue as far as your initial issue is concerned. Why do I say so? It's because these instances both open automatically while you run only 1 statement, which is your initial goal.
I ran into problems with & and |, which exit statuses and error throwing, respectively.
Other solutions want to run any task with a given name, like npm-run-all, which wasn't my use case.
So I created npm-run-parallel that runs npm scripts asynchronously and reports back when they're done.
So, for your scripts, it'd be:
npm-run-parallel wp-server start-watch
My solution is similar to Piittis', though I had some problems using Windows. So I had to validate for win32.
const { spawn } = require("child_process");
function logData(data) {
console.info(`stdout: ${data}`);
}
function runProcess(target) {
let command = "npm";
if (process.platform === "win32") {
command = "npm.cmd"; // I shit you not
}
const myProcess = spawn(command, ["run", target]); // npm run server
myProcess.stdout.on("data", logData);
myProcess.stderr.on("data", logData);
}
(() => {
runProcess("server"); // package json script
runProcess("client");
})();
This worked for me
{
"start-express": "tsc && nodemon dist/server/server.js",
"start-react": "react-scripts start",
"start-both": "npm -p -r run start-react && -p -r npm run start-express"
}
Both client and server are written in typescript.
The React app is created with create-react-app with the typescript template and is in the default src directory.
Express is in the server directory and the entry file is server.js
typescript code and transpiled into js and is put in the dist directory .
checkout my project for more info: https://github.com/nickjohngray/staticbackeditor
UPDATE:
calling npm run dev, to start things off
{"server": "tsc-watch --onSuccess \"node ./dist/server/index.js\"",
"start-server-dev": "npm run build-server-dev && node src/server/index.js",
"client": "webpack-dev-server --mode development --devtool inline-source-map --hot",
"dev": "concurrently \"npm run build-server-dev\" \"npm run server\" \"npm run client\""}
You can also use pre and post as prefixes on your specific script.
"scripts": {
"predev": "nodemon run-babel index.js &",
"dev": "webpack-dev-server"
}
And then run:
npm run dev
In my case I have two projects, one was UI and the other was API, and both have their own script in their respective package.json files.
So, here is what I did.
npm run --prefix react start& npm run --prefix express start&
Simple node script to get you going without too much hassle. Using readline to combine outputs so the lines don't get mangled.
const { spawn } = require('child_process');
const readline = require('readline');
[
spawn('npm', ['run', 'start-watch']),
spawn('npm', ['run', 'wp-server'])
].forEach(child => {
readline.createInterface({
input: child.stdout
}).on('line', console.log);
readline.createInterface({
input: child.stderr,
}).on('line', console.log);
});
I have been using npm-run-all for some time, but I never got along with it, because the output of the command in watch mode doesn't work well together. For example, if I start create-react-app and jest in watch mode, I will only be able to see the output from the last command I ran. So most of the time, I was running all my commands manually...
This is why, I implement my own lib, run-screen. It still very young project (from yesterday :p ) but it might be worth to look at it, in your case it would be:
run-screen "npm run start-watch" "npm run wp-server"
Then you press the numeric key 1 to see the output of wp-server and press 0 to see the output of start-watch.
A simple and native way for Windows CMD
"start /b npm run bg-task1 && start /b npm run bg-task2 && npm run main-task"
(start /b means start in the background)
I think the best way is to use npm-run-all as below:
1- npm install -g npm-run-all <--- will be installed globally
2- npm-run-all --parallel server client
How about a good old fashioned Makefile?
This allows you a lot of control including how you manage subshells, dependencies between scripts etc.
# run both scripts
start: server client
# start server and use & to background it
server:
npm run serve &
# start the client
client:
npm start
call this Makefile and then you can just type
make start to start everything up. Because the server command is actually running in a child process of the start command when you ctrl-C the server command will also stop - unlike if you just backgrounded it yourself at the shell.
Make also gives you command line completion, at least on the shell i'm using. Bonus - the first command will always run so you can actually just type make on it's own here.
I always throw a makefile into my projects, just so I can quickly scan later all the common commands and parameters for each project as I flip between them.
Using just shell scripting, on Linux.
"scripts": {
"cmd": "{ trap 'trap \" \" TERM; kill 0; wait' INT TERM; } && blocking1 & blocking2 & wait"
}
npm run cmd
and then
^C will kill children and wait for clean exit.
As you may need to add more and more to this scripts it will become messy and harder to use. What if you need some conditions to check, variables to use? So I suggest you to look at google/zx that allows to use js to create scripts.
Simple usage:
install zx: npm i -g zx
add package.json commands (optional, you can move everything to scripts):
"scripts": {
"dev": "zx ./scripts/dev.mjs", // run script
"build:dev": "tsc -w", // compile in watch mode
"build": "tsc", // compile
"start": "node dist/index.js", // run
"start:dev": "nodemon dist/index.js", // run in watch mode
},
create dev.mjs script file:
#!/usr/bin/env zx
await $`yarn build`; // prebuild if dist is empty
await Promise.all([$`yarn start:dev`, $`yarn build:dev`]); // run in parallel
Now every time you want to start a dev server you just run yarn dev or npm run dev.
It will first compile ts->js and then run typescrpt compiler and server in watch mode in parallel. When you change your ts file->it's will be recompiled by tsc->nodemon will restart the server.
Advanced programmatic usage
Load env variables, compile ts in watch mode and rerun server from dist on changes (dev.mjs):
#!/usr/bin/env zx
import nodemon from "nodemon";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
// load env variables
loadEnvVariables("../env/.env");
await Promise.all([
// compile in watch mode (will recompile on changes in .ts files)
$`tsc -w`,
// wait for tsc to compile for first time and rerun server on any changes (tsc emited .js files)
sleep(4000).then(() =>
nodemon({
script: "dist/index.js",
})
),
]);
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function getDirname() {
return path.dirname(fileURLToPath(import.meta.url));
}
function loadEnvVariables(relativePath) {
const { error, parsed } = dotenv.config({
path: path.join(getDirname(), relativePath),
});
if (error) {
throw error;
}
return parsed;
}

Resources