Webpack: Compilation error when going through the Getting Started tutorial

Getting a compilation error when following the Webpack tutorial at https://webpack.js.org/guides/getting-started/.

I’ve gone through it three times now, one time where I typed everything in manually to avoid any hidden characters from copy-paste.

Running on Powershell on Windows 10, Npm version 8.3.0, Lodash version 4.17.21, Webpack version 5.66.0, Webpack-cli version 4.9.1.

The error message is this:

(base) PS C:pathtowebpack-demo> npx webpack
assets by status 291 bytes [cached] 1 asset
./src/index.js 458 bytes [built] [code generated] [1 error]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.
js.org/configuration/mode/

ERROR in ./src/index.js 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are confi
gured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

webpack 5.66.0 compiled with 1 error and 1 warning in 196 ms

I’ll paste in the lines of code I have here, but they should be identical to what’s in the tutorial.

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="uft-8" />
    <title>Getting Started </title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

index.js:

import _ from 'lodash';

function component {
  const element = document.createElement('div');

  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

package.json

{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.66.0",
    "webpack-cli": "^4.9.1"
  },
  "dependencies": {
    "lodash": "^4.17.21"
  }
}

Generate sonarcloud report with Jest

Is there anyway to generate a sonarcloud report with Node.js using jest? I’ve found the plugin jest-sonarcloud-reporter, but only runs it locally and generates de .xml, and I need to upload de report to sonarcloud.io. Is there anyway to upload de .xml? Or is there any other way to generate the report directly there with the token?

Slide in and out effect using GSAP

I have a header section which contains a search icon. When this icon is clicked, I want my search bar to slide in from the top. When it’s closed, I want it to slide back up.

Currently:

  1. My search bar slides down on initial click, but when clicking “click me again”, it doesn’t slide back up.
  2. Once you’ve clicked the icon twice, on the third instance, when trying to slide the menu in (which works on first click), it doesn’t slide in, just appears

Demo:

$(function() {

  function slideDown(){
    var element = $(".header__searchBar");
    var tl = new TimelineLite();

    tl.to(element, 1, {
      top: 0,
      autoAlpha: 1
    });

/*     tl.from(element, 1, {
      top: "-100%",
      autoAlpha: 1
    }); */

  }

  $(".header__searchIcon").click(function() {
    $(".header__searchBar").toggleClass("active");
    slideDown();

  });


});
.header {
  position: relative;
  padding: 20px 0;
}
.header__searchIcon {
  position: relative;
  z-index: 99;
  cursor: pointer;
}
.header__searchBar {
  position: absolute;
  left: 0;
  top: -100%;
  width: 100%;
  height: 100%;
  color: white;
}
.header__searchBar.active {
  z-index: 10;
  background-color: #5F249F;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js" integrity="sha512-H6cPm97FAsgIKmlBA4s774vqoN24V5gSQL4yBTDOY2su2DeXZVhQPxFK4P6GPdnZqM9fg1G3cMv5wD7e6cFLZQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div class="header">

  <div class="container">
    <div class="row">
      <div class="col-2">
        LOGO
      </div>
      <div class="col-8">
        MENU
      </div>
      <div class="col-2">
        <div class="header__searchIcon">
          Click me
        </div>
      </div>
    </div>
  </div>

  <div class="header__searchBar">
    SEARCH FORM HERE
  </div>

</div>

I am getting repeated input values as an Output when I am trying to get User Input from Prompt box and showing those input values in an Array

In example – 1 I am getting all the values Entered from the Prompt box.

//Example – 1

<button id="btn">Click Here</button>
    <div id="data1"></div>
    <div id="data2"></div>

  document.getElementById("btn").onclick = () => {

            let cars = new Array(5);

            for(let get = 0 ; get <= 5 ; get++){

                cars[get] = prompt("Enter Any Values");
            }

            for(let show = 0 ; show <= 5 ; show++ ){

                document.getElementById("data1").innerHTML += `You have Entered : ${cars[show]}<br>`;
            }

            document.getElementById("data2").innerHTML = `The Total Values are : ${cars}`;

        }

I am Facing a Problem in Example – 2 .please tell me Where I did wrong. Thank You..!

//Example – 2

<button id="btn">Click Here</button>
    <div id="data1"></div>
    <div id="data2"></div>

 document.getElementById("btn").onclick = () => {

            let cars = new Array(5);

            for(let get of cars){

                cars[get] = prompt("Enter Any Values");
            }

            for(let show of cars){

                document.getElementById("data1").innerHTML += `You have Entered : ${cars[show]}<br>`;
            }

            document.getElementById("data2").innerHTML = `The Total Values are : ${cars}`;

        }

How can I reach a property of an object in localStorage

I have that problem: I’m trying to reach the property of on object “user” that I save in localStorage and the browser gives me the error “Cannot read properties of undefined”.
I apply my code

 like(recipe) {
        if (this.favorites.indexOf(recipe) === -1) {
            this.favorites.push(recipe)
        }
        let user = JSON.parse(localStorage.getItem("users"));
        let currFav = user.favorites;
        currFav.push(recipe);
        localStorage.setItem("users", JSON.stringify(user))
    }

Reactjs doesen’t re render after setState to array

when I finish to get data from my database and I useState setValue and pass the array, render function doesen’t render again.

Code where I setArray

function getNotifiche(){
     onSnapshot(collection(db, "Users",auth.currentUser.uid, "Notifiche"), async (snapNotifiche) => {
            const notifichee = [];
            snapNotifiche.forEach(async notificaDoc => {

                const docRef = doc(db,"Users",notificaDoc.data().Invitato);
                const userData = await getDoc(docRef);

                
                        notifichee.push({
                            "data":notificaDoc.data(),
                            "invitante":userData.data()
                            })
               });
          
            setListaNotifiche(notifichee);

});

This is in the return function:

 {         
        (listaNotifiche.map((notifica,index)=>{
            return(<div key={index}>
                <label>Invitato da {notifica.invitante.Username} in data{new Date(notifica.data.DataInvito.seconds * 1000).toString()}</label>
                <button>Partecipa</button>
                <button>Elimina</button> 
                </div>);
        }))
    }

So I tried also using setListaNotifiche([…notifichee]) but I get the error: TypeError: Cannot read properties of undefined (reading ‘map’)

Subcategories aren’t populating as s – Javascript

I’m trying to concatenate a string of <optgroup>s and <option>s based on categories and subcategories.

Currently, I am getting a string that has all the categories first then all of the subcategories. I need it to go category > subcategories for said category etc.

The backend has two tables, main categories, and subcategories.

Subcategory Table
  id
  title
  main_category_id

Main Category Table
  id
  title

In my code below, I am trying to loop through the main categories, adding them to an <optgroup>. Before moving to the next main category, I am getting the subcategories for each and adding them as <option>s.

let select = document.querySelector("#category");
let str = "";

async function getMainCategories() {
    const categoriesURL = "INSERT_URL"
    await fetch(categoriesURL)
      .then(response => response.json())
      .then(async categories => {
      await categories.sort(function(a, b) {
        var nameA = a.title.toUpperCase(); // ignore upper and lowercase
        var nameB = b.title.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
      }).map(async cat => {
        str += `<optgroup label="${cat.title}">`;
        await getSubcategories(cat.id);
        console.log(str)
        str += '</optgroup>';
      })
    });
    select.innerHTML = "<option disabled selected>Select a category</option>" + str;
}

async function getSubcategories(id) {
    let subcategoriesURL = `INSERT_URL?cat_id=${id}`;

    await fetch(subcategoriesURL)
      .then(response => response.json())
      .then(subcategories => {
      subcategories.sort(function(a, b) {
        var nameA = a.title.toUpperCase(); // ignore upper and lowercase
        var nameB = b.title.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
      }).map(sub => {
        return str += `<option value="${sub.id}">${sub.title}</option>`;
      })
    });
}
getMainCategories();

I can’t start the debugger because it can’t find the npm-cli file

When I try to start the debugger it gives me an error because it can’t find the file npm-cli.js which makes sense because it can’t be found where it tries to look for it Uncaught Error: Cannot find module 'C:Program Filesnodejsnode_modulesnpm binnode_modulesnpmbinnpm-cli.js instead it is actually located at: C:Program Filesnodejsnode_modulesnpmbinnode_modulesbinnpm-cli.js.

The problem is that this only happens to me in the debugger and not when I run it from the command line (npm run works fine).

I already tried to reinstall node to the latest version (16), update node_modules with npm i (and ci). Uninstall and reinstall vscode.

Does anyone know how to configure the path for npm-cli or any other solution?

How to read values from response object?

I am trying to read a value from a response object, but this

fetch("https://api.nft.storage/upload", options)
          .then((response) => response.json())
          .then((response) => console.log(response))
          .then((response) => {
            console.log(response.value.cid);
            }

… doesn’t work. Although my console shows the object being sent:

enter image description here

.. I get this error:

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'value')

1056 | .then((response) => response.json())
  1057 | .then((response) => console.log(response))
  1058 | .then((response) => {
> 1059 |   console.log(response.value.cid);

What’s the best way to loop inside React JSX

I’m working with WordPress/scripts, and I need to do a for loop inside jsx. I did find this post but it is fairly old (7 years). Is the answer still correct today? or are there better solutions?

My Attempt

import { __ } from "@wordpress/i18n";
import { useSelect, useDispatch } from "@wordpress/data";
import { registerPlugin } from "@wordpress/plugins";
import { PluginDocumentSettingPanel } from "@wordpress/edit-post";
import { TextControl, PanelRow } from "@wordpress/components";

class postcodePricingBeDocSidebar {
  constructor() {
    const TextController = (props) => {
      // Get post meta
      const meta = useSelect((select) =>
        select("core/editor").getEditedPostAttribute("meta")
      );

      // Meta prefix
      const metaPrefix = "_postcode_pricing_";

      // Meta fields
      const rows = [
        "outward_code",
        "postal_town",
        "postal_county",
        "auto_1hr",
        "auto_5hr",
        "auto_10hr",
        "auto_weekend_evening",
        "manual_1hr",
        "manual_5hr",
        "manual_10hr",
        "manual_weekend_evening",
      ];

      let metaString = "original";

      for (var i = 0; i < rows; i++) {
        // create meta string
        metaString = metaPrefix + rows[i];
      }

      console.log(metaString);

      const { editPost } = useDispatch("core/editor");

      return (
        <>
          <PanelRow>
            <TextControl
              label={__(rows[i], "postcode-pricing")}
              value={meta}
              onChange={(value) =>
                editPost({
                  meta: { [metaString]: value },
                })
              }
            />
          </PanelRow>
        </>
      );
    };

    const postcodePricingBeDocSidebar = () => {
      // build the panel
      return (
        <PluginDocumentSettingPanel
          name="postcode-pricing"
          title="Area Pricing"
          className="postcode-pricing"
        >
          <TextController />
        </PluginDocumentSettingPanel>
      );
    };

    // render the panel
    registerPlugin("postcode-pricing-be-doc-sidebar", {
      render: postcodePricingBeDocSidebar,
    });
  }
}

export default postcodePricingBeDocSidebar;

Change background of a card when radio selected

My question is very simple : how to add a background color to my card element when the button radio is selected ?

<div class="col-6 col-md-3 mt-4 text-center my-auto">
            <label for="'.$abreviation.'">
                <div class="card card-block d-flex">
                    <div class="card-body align-items-center d-flex justify-content-center">
                        <input type="radio" id="'.$abreviation.'" name="tri" value="'.$abreviation.'" class="check-on" /> '.$tri.'
                    </div>
                </div>
            </label>
        </div>

Is there any way to achieve this with just css or I have to use javascript or jquery ?
I tried to do this but all of the cards are in a red backgroundColor instead of just the card where the radio is selected.


    $(document).ready(function(){

        $(".check-on").click(function(){

          $('.check-on').parent().parent().addClass('backgroundCard') 

        });

    });

Thanks a lot for your help.

Get object from s3 bucket and display as thumbnail in react js

I’m getting objects from s3 and now I want to show them as thumbnails in my react app, so how can I achieve it?

var params = {
   Bucket: BUCKET_NAME,
   Prefix: 'media',
};
s3.listObjects(params, function (err, data) {
    if (err) console.log(err, err.stack);
    else {
        console.log('objects list', data); // successful response
    }
});

I’m getting the contents in the response but the question is how can I display them in my app?

The function cannot be called in the onclick event. How can I call the function?

I can’t call “function” in html onclick, I don’t know why.
tell me how to call “myfunction” when onclick

function commentHtml(data, commentId, userId) {
  function myfunction() {
    console.log("test");
  }
  const comment_text = document.querySelector(".comment_text");
  const comment = comment_text.value;
  const check = data.author._id === userId;
  if (check) {
    return `
        <div class="comment-detail">
            <div class="comment-nickname">${data.author.name}</div>
            <div class="comment-text">${data.content}</div>
            <button class="comment_delete" data-id = ${commentId} onclick="myfunction()" >x</button>
        </div>`;
  }
  return `
        <div class="comment-detail">
            <div class="comment-nickname">${data.author.name}</div>
            <div class="comment-text">${data.content}</div>
            <button class="comment_delete" onclick="myfunction()" style="display: none;">x</button>
        </div>`;
}