Debugging Javascript in VS Code - unbound breakpoints - javascript

I have some issues with unbound breakpoints in VS Code. My project structure is as follows:
mittfast2 - Project root
|_webapp
|_.vscode
|_launch.json
|_src
|_java
|_resources
|_webapp - React components etc.
|_index.js
|_node_modules
|_package.json
My package.json has the following scripts:
"scripts": {
"start": "webpack serve --mode development",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js",
"build": "webpack --mode production",
"test": "jest",
"test:coverage": "jest --coverage",
"test:watch": "jest --watch --coverage"
}
I run with "npm start" and visit http://localhost:3000. Inspecting the sources gives me this:
I can successfully use the built in debugger in Chrome by adding and hitting breakpoints.
But when I add breakpoints in IntelliJ and run my debug launcher, they are all "Unbound breakpoint". This is my launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "WSL Chrome",
"type": "pwa-chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///./src/*": "${webRoot}/*",
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
I believe something is wrong with my launch.json, specifically when I map my sources.
This is my webpack.config.js in case it is of interest:
const path = require('path')
/* Utilities */
const webpackHtml = require('html-webpack-plugin')
const webpackBundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: ['./src/main/webapp/index'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader',
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader'
}
]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]?[hash:8]',
}
}
]
},
plugins: [
new webpackHtml({
hash: true,
template: './src/main/webapp/index.html',
filename: 'index.html'
}),
new webpackBundleAnalyzer({
openAnalyzer: false
}),
new MiniCssExtractPlugin({
filename: 'style.css'
})
],
devServer: {
port: 3000,
hot: true,
historyApiFallback: true,
proxy: {
'/resources/*': {
target: 'http://localhost:8080/fenix/',
secure: false,
onError: error => { console.log('::PROXY ERROR::', error) }
}
}
},
resolve: {
alias: {
'#actions': path.resolve(__dirname, 'src/main/webapp/actions'),
'#components': path.resolve(__dirname, 'src/main/webapp/components'),
'#gui': path.resolve(__dirname, 'src/main/webapp/gui'),
'#functions': path.resolve(__dirname, 'src/main/webapp/functions'),
'#middleware': path.resolve(__dirname, 'src/main/webapp/middleware'),
'#reducers': path.resolve(__dirname, 'src/main/webapp/reducers'),
'#styles': path.resolve(__dirname, 'src/main/webapp/styles'),
}
}
}
Given my project structure, can anyone see why my launch.json is incorrect and suggest improvements to successfully bind the breakpoints?
I hope this question contains all the information needed. Otherwise, please suggest improvements and I will happily edit the question.
Thanks!

Related

Why is webpack not including my function in my ts file

I have made a fresh blazor serverside app. And I have created a tsconfig.json and JS/src folder in my project folder. In Terminal, I have used npm init -y in my JS folder. Node modules can now be installed. I installed webpack and created a webpack.config.js file in my JS folder. Then I create a simple ts file with an alert function. After configuring my tsconfig.json in my project root, I added <script src="js/bundle.js"></script> to my _Layout.cshtml. And then in my index.cshtml page I added a button and some code to call the compiled bundle.js from webpack, located in wwwroot/js/.
I cannot see the function in my bundle.js file. What have I done wrong?
Folder structure:
tsconfig.json:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES2017",
"moduleResolution": "Node"
},
"exclude": [
"node_modules"
],
"include": [
"./JS/src/*.ts"
]
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude:/node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../wwwroot/js'),
},
};
index.ts:
function showAlert() {
alert("this is a test");
}
package.json:
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
"webpack-cli": "^4.9.2"
}
}
Ok so after some struggling I figured out that I need to expose the function as a library.
In webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude:/node_modules/,
},
],
},
resolve: {
extensions: ['', '.js', '.ts']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../wwwroot/js'),
libraryTarget: 'umd',
library: 'EntryPoint'
},
};
Take note of the library and library target in the output section. I am not entirely sure whether var umd const or let is better for the library target, as I am not sure what UMD is. however it seems to work with either.
Here is my updated index.ts file:
import { Calculator } from "./calculator";
export function showAlert() {
console.log("Hello world");
alert("this is a test");
}
export let foo = new Calculator();
let bar = new Calculator();
Notice how foo and showAlert have export in front. This is required. Bar is not accessible.

Webpack5 is unable to compile images while is running and raise an error

I am using webpack5 config to run a react repository and everything seems to be working fine except loading images, I have an error that I do not understand:
ERROR in ./src/assets/styles/main.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve 'file-loader' in '/Users/user.user/Desktop/react-boilerplate-master'
I have tried to reinstall the mini-css-extract-plugin butt didn't worked, not sure what could be the problem here.
This is the webpack config:
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const {
NODE_ENV: nodeEnv = 'development'
} = process.env;
const devMode = nodeEnv !== "production";
const pkg = require("./package.json");
module.exports = {
entry: {
app: "./src/index.js",
vendor: Object.keys(pkg.dependencies)
},
output: {
filename: devMode ? "[name].js" : "[name].[hash].js",
path: path.resolve(__dirname, "dist"),
chunkFilename: devMode ? "[name].js" : "[name].[chunkhash].js",
publicPath: "/"
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
chunks: "all"
}
}
}
},
devServer: {
historyApiFallback: {
index: "/index.html",
port: 3001
}
},
watchOptions: {
poll: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]?[contenthash]',
outputPath: 'images/',
},
},
],
},
{
test: /\.(woff(2)?|ttf|eot|otf|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: "fonts/",
},
},
],
},
{
test: /\.scss|css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: { url: false }
},
{
loader: "sass-loader",
options: {
sassOptions: {
includePaths: ["src/styles/"]
}
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: devMode ? "[name].css" : "[name].[hash].css",
chunkFilename: devMode ? "[id].css" : "[id].[hash].css"
}),
new HtmlWebpackPlugin({
filename: "index.html",
chunks: ["vendor", "app"],
template: path.join(__dirname, "public", "index.html")
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
'process.env.API_PATH': JSON.stringify(process.env.API_PATH)
})
]
};
and the package.json scripts:
``` "scripts": {
"start": "./node_modules/webpack/bin/webpack.js --mode development",
"build": "./node_modules/webpack/bin/webpack.js --mode production",
"start:watch": "./node_modules/webpack/bin/webpack.js --mode development --watch",
"dev": "webpack serve --mode development --open",
"test": "./node_modules/jest/bin/jest.js --env=jsdom",
"test:watch": "./node_modules/jest/bin/jest.js --watch --env=jsdom --verbose",
"test:watch:log": "TERM=dumb ./node_modules/jest/bin/jest.js --watch --env=jsdom --verbose",
"coverage": "npm test -- --coverage",
"eslint": "eslint ./src",
"profile": "./node_modules/webpack/bin/webpack.js --profile --json > stats.json",
"profile:analyze": "./node_modules/.bin/webpack-bundle-analyzer ./stats.json"
},```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/AZH7s.png
Looks like I can reproduce your issue with the above setup. It's very likely an issue from using file-loader in webpack 5.
Basically webpack has urged to use asset module in favor of kind of traditional loader like file-loader.
In short, it should be working if you replace the file-loader with asset module like:
{
test: /\.(png|jpg|gif|svg)$/,
type: 'asset/resource',
// use: [
// {
// loader: 'file-loader',
// options: {
// name: '[path][name].[ext]?[contenthash]',
// // outputPath: 'images/',
// },
// },
// ],
},

Why PWA can be installed only in dev mode?

I'm trying to integrate PWA in my react project, when i run using webpack-dev-server i can see the PWA app that i can install in my computer, but when i build the project with webpack and try to run it, i can't do it anymore
webpack.config.js
const path = require("path");
const webpack = require("webpack");
const { styles } = require("#ckeditor/ckeditor5-dev-utils");
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const BUILD_DIR = path.resolve(__dirname, "public");
const APP_DIR = path.resolve(__dirname, "src");
const envs = require('./config/envs').getEnv;
const plugins = require('./webpack-plugins');
module.exports = (env) => {
console.log("OUTPUT: env", env)
const config = envs(env.NODE_ENV);
const mode = env.production ? 'production' : 'development';
return {
mode,
entry: `${APP_DIR}/index.js`,
output: {
filename: "js/bundle.js",
path: BUILD_DIR,
publicPath: "/"
},
node: {
net: "empty",
tls: "empty",
dns: "empty",
fs: "empty"
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
exclude: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
"babel-loader",
{
loader: "eslint-loader",
options: {
failOnError: true,
emitError: true,
emitWarning: true
}
}
]
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: "graphql-tag/loader"
},
{
test: /\.(jpg|png|gif|svg|pdf|ico)$/,
use: [
{
loader: "file-loader",
options: {
name: "[path][name]-[hash:8].[ext]"
}
}
],
exclude: [
/\.(js|jsx|mjs)$/,
/\.html$/,
/\.json$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/
]
},
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
use: ["raw-loader"]
},
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/,
use: [
{
loader: "style-loader",
options: {
singleton: true
}
},
{
loader: "postcss-loader",
options: styles.getPostCssConfig({
themeImporter: {
themePath: require.resolve("#ckeditor/ckeditor5-theme-lark")
},
minify: true
})
}
]
}
]
},
devServer: {
historyApiFallback: true,
watchContentBase: true,
contentBase: "./public"
},
resolve: {
extensions: [".js"],
alias: {
src: path.resolve(__dirname, "src"),
shared: path.resolve(__dirname, "src", "shared"),
config: path.resolve(__dirname, "config"),
screens: path.resolve(__dirname, "src", "screens"),
package: path.resolve(__dirname, "package.json")
}
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new MomentLocalesPlugin({
localesToKeep: ['es-us', 'fr', 'es'],
}),
new webpack.DefinePlugin({
CONFIG: JSON.stringify(config),
}),
plugins.manifest,
plugins.sw
]
}
};
the Scripts on package.json
"build:local": "webpack --env.NODE_ENV=local --env.production --progress",
"start": "node server.js",
"dev": "webpack-dev-server --inline --watch --host 0.0.0.0 --env.NODE_ENV=local --env.development --progress"
Webpack packages used :
"webpack": "4.19.1",
"webpack-cli": "^2.0.15",
"webpack-dev-server": "^3.1.3",
"webpack-manifest-plugin": "^2.2.0"
PS: I tried both --env.production and --env.development in the build but neither worked
Any lead would be appreciated !
Making the app HTTPS fixed it, many thanks #Mathias

webpack reload styles without page refresh

I use webpack and livereload plugin but when I change something in styles, page refresh but I don't want it.
When I use gulp, I change anything in styles and save it and then css reload without page refresh.
Why does not work like gulp on webpack?
Codes are below
webpack.config.js
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const WebpackNotifierPlugin = require("webpack-notifier");
const webpack = require("webpack");
const LiveReloadPlugin = require("webpack-livereload-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: [
"./resources/js/app.jsx",
"./resources/scss/app.scss",
],
devtool: "source-map",
output: {
path: path.resolve(__dirname, "public/assets"),
filename: "js/app.js",
publicPath: "/public/assets/"
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react", 'stage-2']
}
}
}, {
test: /\.(scss)$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader', "postcss-loader"])
}]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
watch: true,
plugins: [
new CopyWebpackPlugin([{
from: "node_modules/bootstrap/dist",
to: "plugins/bootstrap"
}, , {
from: 'node_modules/font-awesome/css',
to: 'plugins/font-awesome/css',
}, {
from: 'node_modules/font-awesome/fonts',
to: 'plugins/font-awesome/fonts',
}]),
new WebpackNotifierPlugin({
alwaysNotify: true
}),
new webpack.LoaderOptionsPlugin({
debug: true
}),
new LiveReloadPlugin(),
new ExtractTextPlugin({
filename: 'css/app.css'
}),
new Dotenv({
path: './.env',
safe: true
}),
new webpack.EnvironmentPlugin(['NODE_ENV'])
],
node: {
fs: "empty"
}
};
package.json
"scripts": {
"start": "webpack-dev-server --history-api-fallback --progress --colors",
"dev": "cross-env NODE_ENV=development webpack --progress --color",
"prod": "cross-env NODE_ENV=production webpack -p --progress --color"
},
I use "npm run dev" command.
Where is the problem ?
ExtractTextPlugin sadly doesn't support hot module replacement.
From the page plugin description:
No Hot Module Replacement
what you need to do is use the plugin just in production.
rules: [
...
{
test: /\.scss$/,
use: process.env.NODE_ENV === 'production' ?
ExtractTextPlugin.extract([
"css-loader", "sass-loader", "postcss-loader"
]) : [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" },
{ loader: "postcss-loader" }
]
}
]
Try like this it will work.
{
test: /\.(s*)css$/,
loader: ExtractTextPlugin.extract(['style-loader', 'css-loader', "sass-loader"])
}
If you share the package.json than it will be helpful for others to solve the issue.

Not able to transpile jsx to js using babel

I am learning react and here is my simple project sturcture:
my_project
--node_modules
--index.js
--index.html
--package.json
--.babelrc
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
package.json
{
"name": "my_project",
"version": "1.0.0",
"description": "frontend using react js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel src -d dist"
},
"scripts": {
"build": "babel --presets es2015 -d dist"
},
"author": "kishan",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-core": "^6.23.1",
"babel-loader": "^6.4.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"webpack": "^2.2.1"
},
"babel": {
"plugins": ["transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
I am getting following error in console in browser for index.js line 1:
Uncaught SyntaxError: Unexpected token import
Please help me what is wrong with this code?
You forgot to define the babel-loader in webpack file, put this part:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
Use this webpack file:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
}
module.exports = config;
Update:
From Webpack Doc:
When using watch mode, webpack installs file watchers to all files,
which were used in the compilation process. If any change is detected,
it’ll run the compilation again. When caching is enabled, webpack
keeps each module in memory and will reuse it if it isn’t changed.
Add babel-loader in webpack to transpile jsx or js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
Starting the webpack in watch mode and will not require you to build again to do that add the followign in your package.json
"scripts": {
"build": "webpack --progress --color --config webpack.config.js --watch",
}
You may also use webpack-dev-server in hot-loading mode

Categories