Visual Code Run Build Task npm - node.js

I'm using Visual Studio Code 1.13.0 on Windows 10.
I have the following build script in my package.json:
{
//omitted other props
"scripts": {
"build": "webpack"
}
}
I've installed webpack with npm install --global webpack, so it's installed globally.
The webpack.config.js is irrelevant for my question.
When I run npm run build in the terminal, everything works fine. But when I run the Visual Code Tasks: Run Build Task (ctrl+shift+b or ctrl+shift+p > Run Build Task), then I'm getting the following message in the output window:
'"npm run build"' is not recognized as an internal or external
command, operable program or batch file.
Why? (using npm version: 3.10.10)

You should create tasks.json file and specify build task with npm task runner as described here ctrl+shift+p > Configure Task Runner. In your case task.json file should looks something like that
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [
{
"isBuildCommand": true,
"taskName": "build",
"args": ["run", "build"]
}
]
}

tasks.json can be used for running multiple different tasks. This is #oleg-m's answer updated for version 2 of tasks.json:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type":"npm",
"script": "build",
"group": "build"
}
]
}

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

What could be affecting my Node.JS environment that does not allow me to debug my JS with babel-node?

I have a Node JS server written with ES6 features and use Babel to transpile the code for production. The code itself complies and works fine. I am also able to run my "dev" server and test it locally with this command:
npm run dev
which runs this command inside my package.json:
"dev": "nodemon --exec babel-node ./src/server.js"
Pretty standard so far.
I am having issues with debugging my code so I can use breakpoints. Here's the launch script in my VS Code launch.json file:
{
"name": "Debug",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/server.js",
"stopOnEntry": false,
"sourceMaps": true,
"args": [],
"preLaunchTask": null,
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
"runtimeArgs": ["--no-lazy"],
"env": {
"NODE_ENV": "development"
},
"skipFiles": [
"${workspaceFolder}/node_modules/**/*.js",
"<node_internals>/**/*.js"
]
}
And my .babelrc file:
{
"presets": [
[
"#babel/env",
{
"targets": {
"node": "current"
}
}
]
],
"env": {
"development": {
"sourceMaps": "inline",
"retainLines": true
}
},
"comments": true,
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
]
}
When I try to enter debug mode I get this execption thrown right away:
Exception has occurred: Error: Cannot find module 'kexec'
Require stack:
- F:\Dev\Web Development\****\dev\server\node_modules\#babel\node\lib\babel-node.js
- F:\Dev\Web Development\****\dev\server\node_modules\#babel\node\bin\babel-node.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
at Function.Module._load (node:internal/modules/cjs/loader:804:27)
at Module.require (node:internal/modules/cjs/loader:1028:19)
at require (node:internal/modules/cjs/helpers:102:18)
at F:\Dev\Web Development\****\dev\server\node_modules\#babel\node\lib\babel-node.js:65:68
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is where is gets really odd. I pulled the same sourcecode to my laptop and debugging worked just fine. I also spun up a sandbox virtual machine on my Windows 10, did a clean install of Node + VS Code on it, and it worked perfectly there too.
There's something in my current environment that is causing this issue and I cannot figure it out. I've been trying to solve this issue for a few days now with no success.
Here are the steps I have already taken:
Upgrade and downgrade versions of Node + NPM and retry using
different versions
Delete node_modules and reinstall with "npm install" (and using npm ci)
Completely uninstall Node and do a fresh install
Removed user and system environemnt variables before the fresh install
Manually delete all NPM caches from %AppData% folder
I also want to point out that when I used a different launch script that is attached to a process ID, I was able to debug the code, but I am trying to streamline this process instead of having to choose the process each time.
This method does work:
npm run dev to start the dev server, which runs this code:
"dev": "nodemon --exec babel-node ./src/server.js"
I then run the debugger and attach it to the running process. Here's the launch script for that:
{
"name": "Attach by Process ID",
"processId": "${command:PickProcess}",
"request": "attach",
"skipFiles": ["<node_internals>/**"],
"type": "node"
}
If kexec is used by Babel, isn't it already supposed to be installed as a dependecy? I couldn't find it anywhere in my modules folder though.
I also tried installing kexec separately but was receiving a lot of node-gyp errors which I tried fixing by reinstalling all of Node build tools using multiple different methods. None of these actions also fixed the issue.
Any ideas or support would tremendously help at this point.

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)?

Loopback 4 Debugger nodemon Solution

How to debug loopback 4 / node application with nodemon in visual studio code?
Looking for a solution that rebuilds the app when the loopback typescript code is changed. With option for debugging.
Regards,
Kelvijn
I finally found a solution to debug Loopback 4/node.js. If anyone has suggestions please do, this is the first solution that really does what I want.
Start Debugger by running:
npm run debug
With nodemon run the below command
nodemon --exec run debug
Add breakpoints by clicking on the left side of the line numbers in visual studio code.
Then in Visual Studio Code start application on debug mode by
Visual Studio Code (top-bar) -> Debug -> Start Debugging
package.json
"debug": "npm run build && node --nolazy --inspect-brk=9229 .",
"build": "lb-tsc es2017 --outDir dist"
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"timeout": 1000000,
"name": "Attach",
"port": 9229,
"restart": true
}
]
}
tsconfig.json
Note: This file is by default extended by loopback, so you don't have to modify this.
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES5",
"lib": ["es2015"],
"allowJs": true,
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", "platforms"]
}
Application structure
This is an alternative solution for nodemon.
tsc-watch is a similar tool that can be used with loopback 4. Basically, it works similar to the nodemon. To add tsc-watch as dev package,
run npm install tsc-watch --save-dev in your project location
add following lines to the package.json > scripts
"start": "node -r source-map-support/register .",
"dev": "tsc-watch -b --onSuccess \"npm start\""
now run npm run dev
For more details visit tsc-watch on npm or github
Create your own nodemon.json in root project source and put this in file
{
"ignore": [
"**/*.test.ts",
"**/*.spec.ts",
".git",
"node_modules"
],
"watch": [
"src"
],
"exec": "npm start",
"ext": "ts"
}
and run nodemon that's. Just make sure you installed nodemon in global scope.
Thanks for all the answers here I have manage to have something that works for my setup. I use yarn with loopback 4. Thanks to #dat-ho for the starting point.
First install nodemon in global scope
then add the nodemon config to package.json. I added this at the bottom of the file after devDependencies.
"nodemonConfig": {
"verbose": true,
"watch": [
"src/"
],
"ignore": [
"dist/*"
],
"ext": "ts",
"exec": "yarn run clean && yarn start"
}
The changes from previous answer was that nodemon detects the npm start script and it re runs npm start fine, but it does not rebuild and the changes were not shown in the running code. so I added the line "exec": "yarn run clean && yarn start" to clean and rerun the npm start command.
You can then add the following start:dev command to the package.json scripts section:
"start": "node -r source-map-support/register .",
"start:dev": "nodemon '--inspect'",
From there just run yarn start:dev and will rebuild when any typescript file changes. Hope this works for you guys. It took me a substantial amount of research to having this working. Hopefully the loopback guys can have something similar in future.

Configure local typescript compiler inside package.json

EDIT #1: seems like I have a working configuration, all suggestions to improve this are welcome though. See answer: https://stackoverflow.com/a/42269408/1155847
ORIGINAL QUESTION:
I'm currently trying to setup my environment so that my package.json's devDependencies typescript version will be used. What are some of the best practices for this, so that it is "editor unaware" and preferably can be used as an npm script, e.g.: npm run tscompile?
To be clear - I can get everything working when using npm install typescript -g - but then I'm relying on a global installed version, whic is not what I want - as we'll want to work in a team and set on a specific typescript version for each member before upgrading, so we're all on the same page.
I'm currently trying to set it up like this - yet npm then complains it doesn't recognize "node_modules" as an internal or external command... I presume I do have to pass the tsconfig.json to tsc as well, or at least give it the "working directory" - but I can't even get past launching tsc from my locally downloaded npm cache.
package.json
{
"name": "tswithnodejsgettingstarted",
"version": "1.0.0",
"description": "",
"main": "app/index.js",
"scripts": {
"start": "node app/index.js",
"tscompile": "node_modules/typescript/tsc"
},
"author": "",
"license": "ISC",
"devDependencies": {
"typescript": "2.1.6"
}
}
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"sourceMap": true,
"outDir": "app"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Ok... It seems like it was as simple as this (see below). Answering it here, for anyone else looking for the answer. Or please let me know if there are better solutions.
Configure the script like "tsc": "tsc" inside package.json. Then just run npm run tsc and it will use your tsc version you have installed locally, and discover your tsconfig.json of course. It doesn't use your global version - as I uninstalled that one - just entering tsc in the command line errors out.
E.g.:
Check the repo* where I was playing with this.
package.json
{
"name": "tscnodejsgettingstarted",
"version": "1.0.0",
"description": "",
"main": "app/index.js",
"scripts": {
"start": "npm run tsc && node app/index.js",
"tsc": "tsc"
},
"author": "",
"license": "ISC",
"devDependencies": {
"typescript": "2.1.6"
}
}
*repo: https://github.com/pluralsight-courses/typescript-fundamentals/tree/master/001-GettingStarted
You can also use the prestart script. By default it runs before the start command (see all the default scripts that you can set up here).
"scripts": {
"prestart": "npm run tsc",
"start": "node app/index.js",
"tsc": "tsc"
}

Resources