How to setup pathMapping in VSCode to debug a Snowpack application - javascript

I'm evaluating Snowpack for building my JavaScript project. However, VSCode and the Debugger for Chrome extension cannot match the scripts on the dev server to the local source files. Because of this, breakpoints don't work. I'm not using any source maps because I'm not bundling/transforming anything, just using vanilla ES modules.
I'm using the following template: https://github.com/snowpackjs/snowpack/tree/main/create-snowpack-app/app-template-lit-element
A simplified directory layout of the project is:
public/
index.html
src/
index.js
Now when I start the Snowpack dev server it serves the files using the following layout, which is quite different:
index.html
dist/
index.js
I tried the following launch configuration in VSCode, but it does not work, i.e., it cannot match the javascript files:
{
"name": "Launch localhost",
"type": "chrome",
"request": "launch",
"url": "http://localhost:8080/",
"webRoot": "${workspaceFolder}/public",
"pathMapping": {
"/dist": "${workspaceFolder}/src"
}
}
The pathMapping property has very scant documentation, and I'm wondering whether it's working at all.
Any ideas?
Update:
The lit-element example seems to use babel for transpiling, but even with transpiling disabled the problem persists. This is more a VSCode problem, not a Snowpack problem.

To create an output you would like to have please configure mount option for snowpack config, experiment with this config to get the result you need.
mount: {
public: '/',
src: '/src',
},

Related

Cannot Get when running Webpack Config in React.js 2020

I run 'watch' to execute webpack dev sever "watch": "webpack-dev-server --progress"
it compiles with no issues detected in terminal. However, when i go to http://localhost:8080 , I receive an error message 'Cannot Get'
I've created a sandbox.
What I've tried so far adding writeToDisk: true in webpack.config.js and including loaders for svg "file-loader" and css "css-loader" which corrected another error i was having regarding not using a loader for css. I've also tried changing the port to 3000. Not sure how relevant this is to solving this issue but i am using webstorm ide.
UPDATE:
I fixed this issue by moving index.html and manifest.json in to the src folder.
My question now is is there away to make this work without moving index.html and manifest into the same folder as webpack.config.js? If possible i'd rather leave index.html and manifest in the public folder.
I'd suggest reading through webpack's documentation on Output Management.
To your question:
My question now is is there away to make this work without moving index.html and manifest into the same folder as webpack.config.js?
You can make this work using the official HtmlWebpackPlugin to generate your index.html file. You'll be able to point it at your own file, wherever you want it, and it will also let you scale your code eventually to generate the html file from a template.
new HtmlWebpackPlugin({
template: 'path/to/index.html'
})

ESLint doesn't run for HTML files in PyCharm

I am working on a Django+JavaScript project using ESLint as an integrated linter in PyCharm. It works well for *.js files but doesn't analyze any JavaScript in *.html files at all. How do I enable ESLint for HTML files, too?
Here is what I have tried
I added the eslint-plugin-html and followed its setup instructions here: https://www.npmjs.com/package/eslint-plugin-html
This includes adding "plugins": [ "html" ] into .eslintrc.js and adding --ext .html,.js into the "Extra ESLint options" input box in "Languages & Frameworks > JavaScript > Code Quality Tools > ESLint" at PyCharm Preferences.
Here is what my .eslintrc.js file looks like (rules are skipped). I commented out the ESLint vue plugin so far as it is said to have incompatibilities with eslint-plugin-html, which didn't help either.
module.exports = {
"env": {
"browser": true,
"es6": true
},
"extends": [
"eslint:recommended",
//"plugin:vue/essential",
"google"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"plugins": [
"html",
//"vue"
],
"rules": {
...
}
};
Here is the screenshot of my ESLint settings in PyCharm preferences:
ESLint settings in PyCharm preferences
An important matter is that HTML files in my case were used as Django templates (which is the standard approach for the scenario I'm describing i.e. for Django projects). As explained by lena in the comment above, linting Django templates is not currently supported. I've got the same confirmation from an official request to JetBrains (the company that owns PyCharm).
So the answer is - currently there is no way to enable ESLint for Django templates in PyCharm. The workaround is to move the JS code to the other supported types of files to have the code linted (for example, .js or .vue files).
JetBrains has opened a new issue in their tracking system for adding the lacking support, so please vote there if this feature matters to you: ESLint: support linting JavaScript code in Django templates. Also, use this link to get most recent updates on whether this feature gets supported.

vscode node debugger with custom webpack build

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.

webpack javascript in one line

I am running an Angular 4 project with Webpack 2.4.
For some reason, some of the third party Javascript plugins files are being modified after compilation, and they are shown in the browser's debugger as a very long, one line string:
This is very inconvenient because I can't use Chrome / FF debugger, as I am unable to set up any breakpoint in there.
Following some of the already posted questions in this site and many others, I extracted the webpack.config.js file by executing ng eject
The section where the js files are imported look as follows:
{
...
"scripts": [
...
"script-loader!./node_modules/handsontable-pro/dist/handsontable.full.js",
...
],
"styles": [
...
]
},
"output": {
"path": path.join(process.cwd(), "dist"),
"filename": "[name].bundle.js",
"chunkFilename": "[id].chunk.js"
}
The file handsontable.full.js does not look like that in my project's folder. It seems to be pretty structured. It seems to suffer some kind of modification when the application is built and served.
More puzzling, many other files in the node_modules folder do not have the same problem.
Now, I tried to tweak the webpack.config.js, as suggested in many forums, specifically SourceMapDevToolPlugin, but with very little luck.
So, several questions arise here:
What is happening here? The transformed file doesn't seem to be a minified file, or a hashed file... What is it?
How can I prevent this from happening, so I can set up breakpoints in that file and use the browser's debugger for tracing, var inspect, etc.
Check the devtool: property in the Webpack config object. If it's set to eval, cheap-eval-source-map (or something like it, don't remember all the eval options), try changing it to source-map or cheap-source-map.
Full list of options here: https://webpack.js.org/configuration/devtool/

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.

Categories