vscode node debugger with custom webpack build - javascript

I have a JS web app that has a client and server bundle, both built using webpack's node api.
Running my project in dev mode goes through these steps:
Run two webpack builds, resulting in two output files.
Server bundle is output to dist/server/index.js
Spawn child node process using the dist/server/index.js path
Watch folder for changes. On change, kill the old child process and re-run steps 1-3
I want to add node server debugging using vscode.
So far, I've added the following flags during step 3, when I launch a new child process.
['--inspect=9222', '--no-lazy', '--inspect-brk']
My launch.json file in vscode looks like this
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to dev server",
"type": "node",
"request": "attach",
"protocol": "inspector",
"address": "localhost",
"port": 9222,
"restart": true,
"trace": true,
"stopOnEntry": true
}
]
}
When I start the server and run the debugger, things mostly work.
However, I'd love to fix the following two things:
Even with "stopOnEntry": true, the debugger will not pick up any breakpoints, unless I include "--inspect-brk" when launching my child process. This is annoying, because if I'm not running the debugger, the process will hang and will not continue execution. With this flag included, when I run the debugger, the built dist/server/index.js file will open in my editor with a breakpoint on line 1. If I hit continue, all future debugging works.
I'm generating sourcemaps using webpack's "inline-source-map" option. This puts the "original source" in the built file. However, it's the source after babel transformation, making debugging the code a little annoying. E.g. _myFunction.default instead of myFunction. Does vscode have a way to correctly map the built .js file to the pre-built source code in my project? I saw the remoteRoot and localRoot options, but could not get them to work (and am unsure if these are the correct options).
Thanks!

Update VS Code 1.47+:
With the new JavaScript debugger in VS Code 1.47 and later versions, child processes are automatically debugged in Node.js - just set breakpoints where needed.
Example launch.json (with TypeScript source to illustrate the sourcemap approach):
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/main.ts", // use .ts source
"outFiles": ["${workspaceFolder}/dist/**/*.js"], // search here for sourcemaps
}
Example main.ts:
const { spawn } = require("child_process");
const args = [path.resolve("./child.js")];
const proc = spawn(process.execPath, args, { stdio: "inherit" });
See this post for an explanation of pwa-node.
VS Code debug options
program: specifies main source file to be debugged. You can directly reference the .ts source file - VS Code will search the workspace for sourcemaps or consult outFiles.
outFiles: tell VS Code to explicitely search for sourcemaps in these glob locations.
sourceMaps: if VS code shall look for sourcemaps; defaults to true, so no need to set.
stopOnEntry: breaks immediately when program launches - same, as a breakpoint on first line. 1
nolazy: ensures that breakpoints are validated before the code is run and don't "jump". Per default, VS Code sets this flag automatically, so it can be left out.
remoteRoot / localRoot: are for remote debugging and are not directly related to generating sourcemaps (see OP question).
autoAttachChildProcesses: was used to automatically attach to child processed launched in debug mode; no need to set it with new debugger.
Node debug options
--inspect: starts the program in debug mode without waiting for the debugger to be attached.
--inspect-brk: same as --inspect, but waits for the debugger to attach before starting.
You can set one of these to enable debug mode for a program started on the command-line. Note: VS Code now can also auto-attach from integrated terminal without these flags given.
Generate sourcemaps with Webpack
For webpack, you can generate sourcemaps with inline-source-map or source-map 2.
// inside webpack.config.js
devtool: "inline-source-map",
If babel-loader is used, sourcemaps should be considered and merged automatically by webpack with above config entry. For TypeScript, see the Webpack docs.
(Old) Debug child legacy solution
If that does not work in older versions, pass a conditional DEBUG environmental variable for --inspect/--inspect-brk together with autoAttachChildProcesses:
const runner = spawn(process.execPath,
[...(process.env.DEBUG === "true" ? ["--inspect-brk"] : []), ...args],
);
// inside launch.json configuration
"env": {
"DEBUG": "true"
},
1 Despite this developer comment, stopOnEnty has not been propagated to child processes for me - even with autoAttachChildProcesses and child processed started with --inspect.
2 These options provide best compatibility from my experience.

Related

Invalid prettier configuration file detected in VS Code

Booted up my VM running xubuntu in vmware workstation 17 pro. Started working on an exercise in the Odin project in VS Code, beforehand, updated and upgraded via sudo apt-get update and upgrade. Started working and noticed my prettier rules were not formatting on save.
The following error occurs:
["INFO" - 5:58:23 AM] Formatting completed in 6ms.
["INFO" - 5:58:30 AM] Formatting file:///home/t/repos/css-exercises/flex/03-flex-header-2/style.css
["ERROR" - 5:58:30 AM] Invalid prettier configuration file detected.
["ERROR" - 5:58:30 AM] No loader specified for extension ".prettierrc"
Error: No loader specified for extension ".prettierrc"
at Explorer.getLoaderEntryForFile (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/node_modules/prettier/third-party.js:8194:17)
at Explorer.loadFileContent (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/node_modules/prettier/third-party.js:8448:29)
at Explorer.createCosmiconfigResult (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/node_modules/prettier/third-party.js:8453:40)
at runLoad (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/node_modules/prettier/third-party.js:8464:37)
at async cacheWrapper (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/node_modules/prettier/third-party.js:8294:22)
at async Promise.all (index 0)
at async t.ModuleResolver.getResolvedConfig (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/dist/extension.js:1:5693)
at async t.default.format (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/dist/extension.js:1:13308)
at async t.PrettierEditProvider.provideEdits (/home/t/.vscode/extensions/esbenp.prettier-vscode-9.10.3/dist/extension.js:1:11417)
at async B.provideDocumentFormattingEdits (/usr/share/code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:94:45902)
["ERROR" - 5:58:30 AM] Invalid prettier configuration file detected. See log for details.
Looked in user settings and the formatter was incorrect and then I switched it to prettier code formatter. Still nothing would work. Uninstalled and reinstalled prettier with no change. Tried disabling and reenabling the extension. Tried turning on and off prettier: use editor config, prettier: resolve global modules, prettier: require config. No change.
Currently the file is located in /home/t/repos/ and I also tried copy and pasting into the project directory and adding into the workspace of vs code. Side note, in the /repos folder is also the node_modules directory. The eslintrc.prettierrc and prettier.eslintrc files are correctly named and they remain intact.
What I did to try and work around this was to add a config path directly to the file in the repos directory via settings.JSON. Here is my current settings.JSON file:
{
"workbench.colorTheme": "Default Dark+",
"editor.guides.bracketPairs": true,
"workbench.iconTheme": "vscode-icons",
"editor.linkedEditing": true,
"security.workspace.trust.untrustedFiles": "open",
"prettier.configPath": "/home/t/repos/eslintrc.prettierrc",
"[javascript]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"gitlens.hovers.currentLine.over": "line",
"liveServer.settings.donotShowInfoMsg": true,
"liveServer.settings.AdvanceCustomBrowserCmdLine": "/opt/firefox/firefox",
"editor.formatOnSave": true,
"prettier.useEditorConfig": false
}
Where did I get these configs from originally?
Directly from this guide: https://vicvijayakumar.com/blog/eslint-airbnb-style-guide-prettier#4-install-the-airbnb-style-config-for-eslint-and-all-dependencies
Side note: The prettier: prettier path to the prettier module is currently blank. Inserting a path to the file did not work as I believe this is node module related?
Does anyone have any recommendations on how to fix this situation, please? I have tried every solution I have ran across. Deeply appreciate any help I can get.
TO START:
Its helpful to know which "settings.json" your configuring. You need to make sure that both your workspace ".vscode/settings.json" file, and your user "settings.json" file (path is contingent on the O.S. your running) are configured to work harmoniously, and that one is not overriding the other with the same configuration twice.
SECONDLY
Remove all configurations you added to your "./settings.json" file for prettier. Those settings were added by the extension author. Despite the esbenp.prettier-vscode being the official prettier extension for VS Code, Prettier was never intended to be configured via VS Code's configuration files. Prettier is very nit-picky about its "./.prettierrc" configuration file. When we use the VS Code config ("settings.json") when attempt to use a prettier config that the extension generates somewhere. If you end up with settings in some project workspace vscode configurations (e.g. ".vscode/settings.json" files) the extension will try to regenerate a file each time one loads a prettier setting. It may even try to load multiple, depending on the scope of your settings.json file. Some how it has to handle that the user-scoped settings.json file should always be overriden by a workspace "settings.json" configuration file. That's not to mention that prettier configs often contain there own overridden rule sets within the ".prettierrc" configuration file.
Note: Just FYI, the most problematic configuration your using is the "prettier.configPath" setting.
_I'm going to stop going down the rabbit hole, hopefully you get the point I am making, which is: Don't use VS Code settings.json configuration files to configure "Prettier".
This will be more easy to explain with a bullet-list
The following will help you configure a clean environment, one where Prettier will work as you have configure it to work.
To start...
...delete all Prettier settings that you added to all settings.json files. This includes any Prettier settings you added to project ".vscode/settings.json" files, and it especially includes all Prettier-settings that you added to your user "settings.json" file. After you finish, reload VS Code, by closing it out completely, and reopening it.
Rather than delete all prettier configuration files from any projects you have open, I am going to instead ask that when you reopen VS Code, that you only open one instance of VS Code. If VS Code opens a project (aka project-folder) after restarting, you're going to want to close that project w/o opening another one. To do that you can...
Use the keybinding ALT + K followed by the F key.
Alternatively you can use the title-bar menu like so: FILE  >>  CLOSE FOLDER
Additionally, make sure all tabs are closed as well.
At this point your instance of VS Code should be totally empty, completely a blank canvas. From here you are going to want to create a new file. To do this...
You have one of two options
(A) You can use the keybinding CTRL + ALT + SUPER + N
(B) Another way to achieve the same thing is to use the title-bar menu like so:   FILE  >>  NEW FILE
Once you've prompted VS Code to create a new file VS Code will want you to pick a location where it's to be created at. The location doesn't matter, so long as it is in a completely empty file, with nothing else in it. To name the file, VS Code will probably use the drop-down that is often refereed to as the quick input menu. The file needs to be a JavaScript file, as a consequence, the file must end with the file extension ".js". So I can reference the file later, I will call mine "main.js", but you can call your whatever you want, so long as you know which file I am referencing when you read "main.js".
In the same folder as "main.js", create one more new file without a file extension. This file MUST HAVE THE NAME...
.prettierrc
NOTE: "The file has a period (or dot) as the first character in its name (this makes it a hidden file)."
Add the following prettier configuration to the ".prettierrc" file you just created.
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": true,
"singleQuote": true
}
**Execute the following commands"
$ npm init
The command will ask a bunch of questions, just press enter for each one to quickly configure the environment with the default npm/Node.js configuration.
The purpose of this is simply to create a valid "package.json" file.
$ sudo npm i -g prettier && npm i -D prettier
// Or you can execute it as two commands, like this:
$ sudo npm i -g prettier
$ npm i -D prettier
The command (or commands, depending on how you enter them) install prettier as a project dependency, and as a global Node.js package.
NOTE: "Make sure that you have prettier installed as a vscode extension. And make sure that you have only one prettier extension. Having multiple can create problems and confusion. The one you should have should have the Extension ID: esbenp.prettier-vscode "
Prettier Should work now. Use the main.js file we created early to write some javascript, then press F1 to open the quick input, type the word "format document", until you see the option "Format Document", which you want to click. Then choose prettier from the menu. Prettier won't format if you have erroneous code, it needs to be free from error. (if you want to fix errors use a linter like ESLint).
You can add a bunch of blank lines, or put braces on the wrong line, leave out semi colons, and prettier should format all of those mistakes.

debugger on VSCode not working with Javascript

UPDATE: This is a question about how to configure VSCode to debug Javascript. I understand it uses Node.js, which I don't know about, javascript always works in the browser, but I would like to be able to step through the code rather than write hundreds of console.log() statements just to see what it is doing.
Trying to set up debugging for Javascript in VScode, but it's not picking it up, it keeps opening the launch.json file, but I've no idea what I need to put in there to make this work. I'm new to Javascript and just run things in a browser, I am assuming Node.js is kind of standalone JavaScript engine, so I did install it.
I have Node v4.2.6 installed on linux mint computer
and:
which node
resulted in:
/usr/bin/node
I'm confused, is this the correct path for node, and how do I add it to this config, I can't work out what the key/value pair is supposed to be. here is the launch.json file is spits out:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js"
},
}
Any help on this would be much appreciated.
If I understand you correctly, you want to debug JavaScript running in the browser with VSCode. Right?
If that's the case, debugging your JavaScript running in node would not be of much value, because node may be missing the APIs your code relies upon (e.g. the DOM). Instead, you'll want to let your JavaScript run in the browser and just debug it with VSCode.
There are extensions for the different browsers that allow that, they mostly utilize the DevTools Protocol: vscode-firefox-debug, vscode-chrome-debug, vscode-edge-debug2.
Merely quoting from vscode-firefox-debug project page:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch index.html",
"type": "firefox",
"request": "launch",
"reAttach": true,
"file": "${workspaceFolder}/index.html"
}
]
}
This will open ${workspaceFolder}/index.html in a new FireFox tab and you'll be able to debug that using VSCode. It'll get nasty with bundlers, source maps and all that jazz, but this is the gist you should get: run JavaScript in the browser, connect VSCode to the DevTools using an extension.

Simplest way to test JavaScript code (for web-frontend) on each Git push

I'm looking for the simplest most minimalist way to create automated tests on each Git push for a relatively simple JavaScript code (on GitHub) for an HTML/CSS/JS web application, in a way that it can also test the HTML elements (via JS manipulation).
I assume it would need some sort of a "headless browser" testing - in which case I would only need it to be executed in Google Chrome. (This application is not planned be used in any other browser.)
I already created a JS function that does the testing. This function should be executed after the entire application (web page) is loaded (HTML, CSS, JS), since it involves the manipulation of HTML elements. For the sake of a simple example, let's say I always expect an even number that is larger than 5. The number is, say, the count of paragraph elements in one of the div elements on the application's HTML page. In that case the function would be:
function my_test() {
var is_valid = true;
var num = $("#my_div").find("p").length; // (JQuery is included in the app)
if (num % 2 != 0) {
console.log("it's not an even number");
is_valid = false;
} else if (num <= 5) {
console.log("it's smaller than 5");
is_valid = false;
}
return is_valid ;
}
So the question is, what would be the simplest way to make this test automatically be run in the terminal whenever git push is executed (by anyone who wants to contribute to the repository)?
I know that there are Node.js testing frameworks such as Tape, but it seems complicated for what I imagine (or hope) could be done simpler; plus if I install these it adds MBs to the otherwise tiny application (around 0.3 MB) which I don't really like.
Such testing could then be automatically run with e.g. Travis, so for example I could just add a ".travis.yml" file, with
language: node_js
node_js:
- "node"
And then in the package.json file I could add e.g. the line "test": "jshint my_code.js" to test the my_code.js with the jshint package.
But is there a way to execute my own simple JS function as a test? E.g., to say "first load my page (HTML, CSS) with all my related JS code, then execute my custom my_test() function (above), display (in the terminal) whatever would be output in the console (via console.log('output')), and, if in the end it does not return true, disrupt the git push".
I appreciate any suggestions, but the best would be a clear description of what steps should be taken to set all this up. E.g., "create the .travis.yml with such and such content, add the package.json file with such and such content, etc.". And/or if it's perhaps also possible to use e.g. Tape without installing it on top of the application, but just automatically calling it whenever the testing is executed, then how would that be done.
(I don't insist on Travis or Tape at all, these were just examples.)
(UPDATE: I now accepted my own solution - for lack of a better one - but if someone can offer a simpler/better one, I will change the accepted answer.)
Git has hooks that allow running different tasks when something occurs.
In this case, you need to add logic in the pre-push hook
Sample pre-push script: https://github.com/git/git/blob/master/templates/hooks--pre-push.sample
Edit your hooks in .git/hooks/pre-push
The script used for git hooks can be made in any scripting language, so in this case, you will use your js code.
Do not forget to add the shebang for node
#!/usr/bin/env node
Make sure to return a non-zero respond if you want to stop the push.
Here is my solution, though not too simple. I used Travis, Karma, and a very basic Jasmine code.
First, you need to have a package.json file in the root of the application with this content:
{
"name": "CITapp",
"description": "Concealed Information Test app",
"version": "1.0.2",
"scripts": {
"test": "karma start test/karma.conf.js --single-run"
},
"devDependencies": {
"jasmine-core": "*",
"karma": "*",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "*",
"karma-fixture": "^0.2.6",
"karma-html2js-preprocessor": "*",
"karma-jasmine": "*",
"karma-phantomjs-launcher": "*",
"phantomjs-prebuilt": "*"
}
}
If you now run npm install in the terminal at the path of the app, every required module will be added to the app (under node_modules folder). (For this, Node.js has to be first installed on the PC.) This is only needed for local testing (on your own PC), but Travis does this installation automatically on their server on each git push (see below). (These modules occupy quite some space, so they are better not included in the app, e.g. in the repository in particular.)
For Travis, you just need a .travis.yml file with:
language: node_js
node_js:
- "stable"
Now, in the package.json file there was this line "test": "karma start test/karma.conf.js --single-run". This directs the "test" command to the karma.conf.js under the test directory in the app. This file should contain something like this:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../js/jquery-2.1.3.min.js', // JQuery from the root's js folder
'../js/my_scripts.js', // personal scripts from the root's js folder
'add_html.js', // from same folder as the karma.conf.js
'test.js' // from the same folder as the karma.conf.js
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: [
'--no-sandbox',
'--disable-gpu',
'--enable-logging',
'--no-default-browser-check',
'--no-first-run',
'--disable-default-apps',
'--disable-popup-blocking',
'--disable-translate',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--disable-device-discovery-notifications',
'--remote-debugging-port=9222',
'--disable-web-security'
]
}
},
singleRun: true,
concurrency: Infinity
})
}
Most importantly, I used the framework jasmine, initiated ChromeHeadless (with some special flags because otherwise it gives errors), and loaded my files in the list of files : [...].
The add_html.js file adds HTML to the page via JS code, e.g. as (following the example in the question):
var fixture = "<div id='my_div'><p>paragraph1</p><p>paragraph2</p></div>";
document.body.insertAdjacentHTML('afterbegin', fixture);
(For some reason, when I try to load HTML directly via the Karma files list, it doesn't work - but inserting it like this is fine for me as well.)
Finally, the test with Jasmine in the test.js is as simple as this:
describe("suite", function() {
it("check if my_test() returns true", function() {
expect( my_test() ).toBe(true);
});
});
Note that the function my_test() comes from the (hypothetical) my_scripts.js file - possibly identical to the one in the question's example - so it's defined as a simple pure (well, only JQuery added) JS script. Whenever the script returns true, the Jasmine test will pass. If it does not return true (including any unrelated errors that stop the execution of the test code), the test will fail.
This can all be tested locally using the npm test command from the terminal at the path of the app (again, for this, first all required Node.js packages have to be installed).
Now the last thing to do is to connect Travis CI to the repository, which is just a few very simple steps; see their GitHub tutorial. This will create a dedicated Travis site connected to the given GitHub repository.
Then it's all done. On each push, Travis will build up the page in a headless ("invisible") Chrome browser and run the my_test() function, sending optional notifications if it fails. Each message via console.log() in this function (or in any other function of the app that is executed during testing) is shown on the Travis site. A further nice thing is that if you want the testing to stop at a certain point (e.g. if some conditions are not met), you can simply write throw "this and this condition was not met", which also stops the Travis test at that point, showing this error message.
For my actual implementation, see: https://github.com/gasparl/citapp_pc
(There are some additions of course, but the logic is the same.)

How to make Visual Studio Code check entire project for errors?

I'm using VS Code for TypeScript/JavaScript development. When I open a file it will check that file for errors. The problem is if I'm refactoring (like I move some shared code to a new location or change a name) it won't show me the errors this caused until I open the file with the problem. ...so if I want to do extensive refactoring I have to open every file just to make it scan the file for errors.
How can I make VS Code scan the whole project for errors without having to open each file one by one manually?
VS Code (v1.44) has an experimental feature, that allows project wide error reporting in TS. Try it out:
// put this line in settings.json
"typescript.tsserver.experimental.enableProjectDiagnostics": true
Figured it out. Note this answer is specific to TypeScript, which is what I am using. Here it is:
Make sure typescript is installed globally (I just had mine installed locally apparently):
npm install -g typescript
Then in VS Code press Shift+Ctrl+B. If you don't have a task runner set up it will ask what you want. I selected typescript and the tasks.json file will look like this:
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p", "."],
"showOutput": "silent",
"problemMatcher": "$tsc"
}
Then pressing Shift+Ctrl+B (or Shift+Command+B in macOS) will check the entire project for problems and they will be reported in your "problems" panel.
If you don't want to install TypeScript globally, you can do the following:
Install TypeScript locally on the project, that is yarn add --dev typescript or npm install --save-dev typescript.
Add a check-types run script to ./package.json. --noEmit means that the compiler will won't generate any JavaScript files.
{
"scripts": {
"check-types": "tsc --noEmit"
}
}
Let VSCode know about the run script in /.vscode/tasks.json.
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "check-types",
"problemMatcher": [
"$tsc"
]
}
]
}
To run the tasks hit the F1 key and select 'Run Task', and then 'npm: check-types'.
If you add the following lines to the task, pressing Ctrl+B will run it.
"group": {
"kind": "build",
"isDefault": true
}
For the most recent version of tasks.json this is the correct json, following deprecations in version 1.14. Create this as /.vscode/tasks.json
{
"version": "2.0.0",
"command": "tsc",
"type": "shell",
"args": [
"-p",
"."
],
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$tsc"
}
Once you have open your project in vs code, open the vs code terminal and run:
node_modules/.bin/tsc --noEmit
Go to View menu > Extensions and make sure the Microsoft VS Code ESLint extension is installed.
In Settings, search for "ESLint > Lint Task: Enable", and enable that setting (docs).
In the Terminal menu, choose Run Task… > eslint: lint whole folder.
UPDATE.
My answer below does not answer the original question, but if you're like me and have found this thread searching for how to turn on // #ts-check project-wide in VSCode so that you don't need to add // #ts-check to every file then my answer below is what you need. I have searched and searched and kept getting this thread as my top result so hopefully this helps others as well
I'm on vscode version 1.52.1 and the answer is so simple and right on the vscode website:
https://code.visualstudio.com/docs/nodejs/working-with-javascript#_type-checking-javascript
scroll down to the "Using jsconfig or tsconfig" section
Add a jsconfig.json in your project root and add "checkJs": true
{
"compilerOptions": {
"checkJs": true
},
"exclude": ["node_modules", "**/node_modules/*"]
}
You might need to restart vscode once you add it in
None of the other solutions worked fully for me. Here's a tasks.json that does, working with vscode 1.67+. On Linux etc. set command to tsc, on Windows be sure to run tsc.cmd as tsc alone will attempt to run the bash script and produce the following error:
The terminal process failed to launch: A native exception occurred during launch (Cannot create process, error code: 193)
"revealProblems": "always" in the presentation section shows the Problems panel on completion.
{
"version": "2.0.0",
"tasks": [
{
"label": "tsc: error check project",
"command": "tsc.cmd",
"args": [
"-p",
".",
"--noEmit"
],
"isBackground": false,
"problemMatcher": "$tsc",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"revealProblems": "always",
}
}
]
}
Edit: Since updating to 1.52.0 this no longer works. It will instead replace the current project files with what you selected...
===
I've tried every solution I can find and I think it's safe to say the answer is: You can't*
The best I've found is still technically opening each file manually, but at least it's not one-by-one:
You can't drag/drop a directory but you can select multiple files (including directories) and drag/drop. The directories will be ignored and any files you had selected will be opened in tabs.
Next, you need to give each tab focus so it triggers eslint to run. (Holding down the next tab keyboard shortcut works.)
This is terrible and I beg someone to prove me wrong.
*I haven't found a way that works as well as opening files manually. Each method -- experimental vscode feature and tsc task -- has its own set of drawbacks. The vscode feature is clearly the solution but without a way to ignore node_modules, etc. it's too painful to use.

Node debugging with WebPack and Feathers

I joined a group building a product with Node, Webpack, TypeScript and Express/Feathers. Other developers know what they are doing, but I have only used JavaScript on a client until now and have literally only a few hours of Node under my belt. Trying to figure out how to go about debugging. Specifically, my first task is to fix some failing API tests.
Tests are executed with:
$npm run testserver
My package has:
"scripts": {
....
"testserver": "webpack --config webpack.servertest.config.js && NODE_ENV=test mocha dist/serverTests.js",
....
},
The routine is to compile typescript into ES6 then babel to ES5 compatible with Node.
I tried doing:
$node-debug dist/serverTests.js
When this node-debug invocation runs, the results are not the same as with npm. Please share your experience.
Thank you
Based on your setup, I can recommend you to try Visual Studio Code, OS text editor/ide based on Electron as well as Atom editor.
To solve your issue you can use two vscode features:
Debugging - link on docs how to debug in vscode
Tasks - task management, for instance to look into webpack config which is started with some args and etc
Firstly, let's try simple solution that may be appropriate in your case (tasks file doesn't need):
Add to the end of testserver --debug-brk it's used for debug in node.js, brk - it simply stops execution on the first line.
"testserver": "webpack --config webpack.servertest.config.js && NODE_ENV=test mocha dist/serverTests.js --debug-brk",
Now when you npm run testserver, mocha starts in debug mode and in console you will see something like Debugger listen on port 5858
Second step, in vscode you need to add some props (port 5858) to launch.json - read section Debugging in docs that I mention above:
{
"version": "0.1.0",
"configurations": [
{
"name": "Attach", // or e.g. "Mocha Debug"
"type": "node",
"request": "attach",
"port": 5858
}
]
}
And that's it. Go in debug mode in vscode, put breakpoint in a test file, choose in dropdown 'Attach' or 'Mocha Debug' and start debugging(F5)
p.s. Also VS code has first-class TypeScript support that may be helpful for you.

Categories