Debugging current file in VS Code - javascript

I am writing javascript and am currently doing simple exercises/programs. At times, I wish to run my file for testing purposes. I am aware I could create an HTML file and do this within the console. In Sublime, there exists a way to "build" the current file and immediately see the results (say, whatever is sent to console.log).
With VS Code, it seems that for every file I want to "build"/debug in this manner, I must manually change the launch.json file to reflect the name of the current program.
I have been researching a way around this, and I learned that there are variables like ${file} , but when I use that in the launch.json "program" attribute, for example:
"program": "${workspaceRoot}/${file}"
with or without the workspaceRoot part, I get the following error:
Attribute "program" does not exist" (file name here).
Am I missing a simple way to accomplish this, or must I keep editing launch.json every time I want to run the file?
Thanks in advance!

Change to:
"program": "${file}"

For reference this is the full launch.json
{
"launch": {
"version": "0.2.0",
"configurations": [
{
"name": "Node.js - Debug Current File",
"type": "node",
"request": "launch",
"program": "${file}"
}
]
}
}

There are many different ways you may need to access a file that are provided by Predefined variables:
Supposing that you have the following requirements:
A file located at /home/your-username/your-project/folder/file.ext opened in your editor;
The directory /home/your-username/your-project opened as your root workspace.
So you will have the following values for each variable:
${userHome} - /home/your-username
${workspaceFolder} - /home/your-username/your-project
${workspaceFolderBasename} - your-project
${file} - /home/your-username/your-project/folder/file.ext
${fileWorkspaceFolder} - /home/your-username/your-project
${relativeFile} - folder/file.ext
${relativeFileDirname} - folder
${fileBasename} - file.ext
${fileBasenameNoExtension} - file
${fileDirname} - /home/your-username/your-project/folder
${fileExtname} - .ext
${lineNumber} - line number of the cursor
${selectedText} - text selected in your code editor
${execPath} - location of Code.exe
${pathSeparator} - / on macOS or linux, \ on Windows

For a single file, you can skip the launch.json file entirely. Just click the green arrow in the debugger panel and choose Node as your environment.
From here.

Related

Parcel Bundler beautify, lint, and create .min.js

I'm new the world of automating/testing/bunding with JS and I've got parcel setup for the most part but I noticed that when it builds files, it does not actually save them with the .min.js part in the file name. I'm wondering if theres a way to do this without having to rename the build file manually.
I'm also trying to find a way to have parcel go through the original source files(the ones that you work on) and lint and beautify them for me
Here's what my package.json looks like
{
"name": "lpac",
"version": "1.3.1",
"description": "",
"dependencies": {},
"devDependencies": {
"parcel": "^2.0.0-rc.0"
},
"scripts": {
"watch": "parcel watch --no-hmr",
"build": "parcel build"
},
"targets": {
"lite-maps": {
"source": ["./path/file1.js", "./path/file2.js", "./path/file3.js"],
"distDir": "./path/build/"
}
},
"browserslist": "> 0.5%, last 2 versions, not dead",
"outputFormat" : "global",
}
I checked out the docs but I couldn't find anything on linting or beautifying with parcel. How can i go about doing that? If you have tutorial links to doing so please also share because resources/tutorials seem scarce for anything other than the basic watching and building files
Unfortunately, there is no out-of-the-box setting that can cause parcel javascript output look like [fileName].[hash].min.js instead of [fileName].[hash].js. The .min.js extension is just a convention to keep output files distinct from source files, though - it has no effect at runtime - and the fact that parcel does automatic content hashing makes it easy enough to tell this. And even though they don't have a .min.js extension, these output files are definitely still minified and optimized by default.
However, if you really, really want this anyways, it's relatively simple to write a Namer plugin for parcel that adds .min.js to all javascript output:
Here's the code:
import { Namer } from "#parcel/plugin";
import path from "path";
export default new Namer({
name({ bundle }) {
if (bundle.type === "js") {
const filePath = bundle.getMainEntry()?.filePath;
if (filePath) {
let baseNameWithoutExtension = path.basename(filePath, path.extname(filePath));
// See: https://parceljs.org/plugin-system/namer/#content-hashing
if (!bundle.needsStableName) {
baseNameWithoutExtension += "." + bundle.hashReference;
}
return `${baseNameWithoutExtension}.min.js`;
}
}
// Returning null means parcel will keep the name of non-js bundles the same.
return null;
},
});
Then, supposing the above code was published in a package called parcel-namer-js-min, you would add it to your parcel pipeline with this .parcelrc:
{
"extends": "#parcel/config-default",
"namers": ["parcel-namer-js-min", "..."]
}
Here is an example repo where this is working.
The answer to your second question (is there "a way to have parcel go through the original source files(the ones that you work on) and lint and beautify them for me") is unfortunately, no.
However, parcel can work well side-by-side with other command line tools that do this do this. For example, I have most of my projects set up with a format command in the package.json, that looks like this:
{
...
"scripts": {
...
"format": "prettier --write src/**/* -u --no-error-on-unmatched-pattern"
}
...
{
You can easily make that command automatically run for git commits and pushes with husky.

VSCode user snippet doesn't works inside jsx

I have a some snippet:
"JSON stringify": {
"prefix": "jst",
"body": [
"<pre>{JSON.stringify($1, null, 2)}</pre>"
]
},
and it works inside js scope, but when I'm trying to do same trick inside jsx render - it dont want to be working.
How to tell my VSCode, that I want to do same things inside jsx?
Maybe adding "scope" to your snippet:
"scope": "javascript,typescript,javascriptreact",
javascriptreact ---> jsx files
It should be like this...
"JSON stringify": {
"scope": "javascript,typescript,javascriptreact",
"prefix": "jst",
"body": [
"<pre>{JSON.stringify($1, null, 2)}</pre>"
]
},
Putting that snippet into your global snippets file should work.
Gear Icon/User Snippets/ myGlobalSnippets.code-snippets
It looks like inside jsx, the type of proposed snippets is not "javascript" but "jsx":
When you go to File / Preferences / User snippets you can look for the jsx format (file name jsx.json)
If you put your snippet in that file, it should be available inside your jsx
I had to put "scope": "javascript,jsx,jsx-attr". Perhaps there's a neater way but that did it for me.
In vscode Press the gear button then choose User Snippets then type javascriptreact if you are using "javascript" or typescriptreact for"typescript" then past the snippet code that you want :D

JavaScript color highlighting error in VScode

I have fresh install of VScode editor (v.1.14.2). Doesn't have any installed extensions. I have problem with javaScript highlighting in very simple file.
The same code in Sublime Text 3:
Default VScode theme (Dark+), doesn't have this bug, and all function names and methods have the same colors. But many another themes (monokai and Abyss for example) have this bug/feature.
I want to have for function names and methods the same color (line 10, 11, 13, 16). Ideally, all lines like in ST3 - blue (line 13 - green). But, it's ok if it would be a green.
I read scope naming link, try to compare different themes. Install all monokai-based themes, but all of theme, has this bug. I tried to create new one, but I didn't do what I need.
So, does it possible to fix this?
You can use vscode command Developer: Inspect TM Scopes for scope inspection. This color changes because vscode thinks click(), addEventListener()... is special DOM-related properties and should be highlighted.
Workaround would be modifying monokai-color-theme.json in
Microsoft VS Code\resources\app\extensions\theme-monokai\themes.
In this array "tokenColors": [] add:
{
"name": "DOM & invocation color fix",
"scope": "meta.function-call.js entity.name.function, meta.function-call.js support.function.dom.js",
"settings": {
"foreground": "#66D9EF"
}
}
This will make function calls & DOM-methods sublime-like.
P.S. If theme updates it will most likely overwrite this file.
Edit:
From some version it is possible to modify theme from settings.json Ctrl+,
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": ["meta.function-call.js entity.name.function",
"meta.function-call.js support.function.dom.js"],
"settings": {
"foreground": "#66D9EF"
}
}
]
}
Your function should not have an end-line ";" added. Your variable test however should have one, this is simple syntax error and doesn't always get caught. This post is years late but it came up in search and the above suggestion is too much work.

Visual Studio Chutzpah Running test on different projects with AMD modules

I have two projects under a solution, one is my main web project, say MyProject and the other serves for testing purposes, say MyProject.Tests.
Solution
MyProject
MyProject.Tests
I want to have my JavaScript headless tests running to the second one.
On the first project, all the javascript files are under the Scripts directory, like so:
Scripts/
Common.js
Libs/
jquery/
jquery.js
requirejs/
require.js
At the test project, I have my chutzpah.json file on root.
MyProject.Tests
chutzpah.json
Tests/
Specs/
spec.js
The file has this configuration:
{
"Framework": "jasmine",
"TestHarnessReferenceMode": "AMD",
"TestHarnessLocationMode": "SettingsFileAdjacent",
"Tests": [ { "Path": "Tests/Specs" } ],
"AMDBasePath": "../MyProject/Scripts",
"CodeCoverageExcludes": ["*Common.js"],
"References": [
{ "Path": "../MyProject/Scripts/Libs/requirejs/require.js" },
{ "Path": "../MyProject/Scripts/Common.js" }
]
}
But when I try to run the spec file I get an error.
Spec file:
define(["jquery"], function ($) {
//code here. Doesn't matter, the error is because of the jquery module
});
The error, is this:
Error: Error opening C:/Users/g.dyrrahitis/Documents/Visual Studio 2013/Projects/MySolution/MyProject.Tests/Scripts/Libs/jquery/jquery.js: The system cannot find the path specified.
The thing is that chutzpah tries to find my jquery module at the test project rather the main project, where it resides.
Why I'm getting this kind of behavior and how can I solve this please? I've been trying for hours to tackle this with no luck so far.
Note
*The names MySolution, MyProject, MyProject.Tests are used for clarity, rather than using the real names.
I've found it, the chutzpah file hadn't the right configuration options (as expected) for the test harness directory.
I needed the TestHarnessDirectory and TestHarnessLocationMode options to explicitly instruct it to look at my main project directory.
This now is the correct one:
{
"TestHarnessDirectory": "../MyProject",
"TestHarnessLocationMode": "Custom",
"TestHarnessReferenceMode": "AMD",
"Framework": "jasmine",
"Tests": [ { "Path": "JavaScript/Specs" } ],
"AMDBasePath": "../MyProject/Scripts",
"CodeCoverageExcludes": [ "*Common.js" ],
"References": [
{ "Path": "../MyProject/Scripts/Libs/requirejs/require.js" },
{ "Path": "../MyProject/Scripts/Common.js" }
]
}
Just needed to tell chutzpah that the harness location mode is custom, in order to provide a directory for it, which is the root of my main project.
Beware for the right configuration paths then, you may end up struggling for hours like me to find a solution. And read the documentation thoroughly (which I hadn't done).

execute some code and then go into interactive node

Is there a way to execute some code (in a file or from a string, doesn't really matter) before dropping into interactive mode in node.js?
For example, if I create a script __preamble__.js which contains:
console.log("preamble executed! poor guy!");
and a user types node __preamble__.js they get this output:
preamble executed! poor guy!
> [interactive mode]
Really old question but...
I was looking for something similar, I believe, and found out this.
You can open the REPL (typing node on your terminal) and then load a file.
Like this: .load ./script.js.
Press enter and the file content will be executed. Now everything created (object, variable, function) in your script will be available.
For example:
// script.js
var y = {
name: 'obj',
status: true
};
var x = setInterval(function () {
console.log('As time goes by...');
}, 5000);
On the REPL:
//REPL
.load ./script.js
Now you type on the REPL and interact with the "living code".
You can console.log(y) or clearInterval(x);
It will be a bit odd, cause "As time goes by..." keep showing up every five seconds (or so).
But it will work!
You can start a new repl in your Node software pretty easily:
var repl = require("repl");
var r = repl.start("node> ");
r.context.pause = pauseHTTP;
r.context.resume = resumeHTTP;
From within the REPL you can then call pause() or resume() and execute the functions pauseHTTP() and resumeHTTP() directly. Just assign whatever you want to expose to the REPL's context member.
This can be achieved with the current version of NodeJS (5.9.1):
$ node -i -e "console.log('A message')"
The -e flag evaluates the string and the -i flag begins the interactive mode.
You can read more in the referenced pull request
node -r allows you to require a module when REPL starts up. NODE_PATH sets the module search path. So you can run something like this on your command line:
NODE_PATH=. node -r myscript.js
This should put you in a REPL with your script loaded.
I've recently started a project to create an advanced interactive shell for Node and associated languages like CoffeeScript. One of the features is loading a file or string in the context of the interpreter at startup which takes into account the loaded language.
http://danielgtaylor.github.com/nesh/
Examples:
# Load a string (Javascript)
nesh -e 'var hello = function (name) { return "Hello, " + name; };'
# Load a string (CoffeeScript)
nesh -c -e 'hello = (name) -> "Hello, #{name}"'
# Load a file (Javascript)
nesh -e hello.js
# Load a file (CoffeeScript)
nesh -c -e hello.coffee
Then in the interpreter you can access the hello function.
Edit: Ignore this. #jaywalking101's answer is much better. Do that instead.
If you're running from inside a Bash shell (Linux, OS X, Cygwin), then
cat __preamble__.js - | node -i
will work. This also spews lots of noise from evaluating each line of preamble.js, but afterwords you land in an interactive shell in the context you want.
(The '-' to 'cat' just specifies "use standard input".)
Similar answer to #slacktracer, but if you are fine using global in your script, you can simply require it instead of (learning and) using .load.
Example lib.js:
global.x = 123;
Example node session:
$ node
> require('./lib')
{}
> x
123
As a nice side-effect, you don't even have to do the var x = require('x'); 0 dance, as module.exports remains an empty object and thus the require result will not fill up your screen with the module's content.
Vorpal.js was built to do just this. It provides an API for building an interactive CLI in the context of your application.
It includes plugins, and one of these is Vorpal-REPL. This lets you type repl and this will drop you into a REPL within the context of your application.
Example to implement:
var vorpal = require('vorpal')();
var repl = require('vorpal-repl');
vorpal.use(repl).show();
// Now you do your custom code...
// If you want to automatically jump
// into REPl mode, just do this:
vorpal.exec('repl');
That's all!
Disclaimer: I wrote Vorpal.
There isn't a way do this natively. You can either enter the node interactive shell node or run a script you have node myScrpt.js. #sarnold is right, in that if you want that for your app, you will need to make it yourself, and using the repl toolkit is helpful for that kind of thing
nit-tool lets you load a node module into the repl interactive and have access to inner module environment (join context) for development purposes
npm install nit-tool -g
First I tried
$ node --interactive foo.js
but it just runs foo.js, with no REPL.
If you're using export and import in your js, run npm init -y, then tell node that you're using modules with the "type": "module", line -
{
"name": "neomem",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "home.js",
"keywords": [],
"author": "",
"license": "ISC"
}
Then you can run node and import a file with dynamic import -
$ node
Welcome to Node.js v18.1.0.
Type ".help" for more information.
> home = await import('./home.js')
[Module: null prototype] {
get: [AsyncFunction: get],
start: [AsyncFunction: start]
}
> home.get('hello')
Kind of a roundabout way of doing it - having a command line switch would be nice...

Categories

Resources