import JUST typescript definitions in lazy files for LSP

I am bundling one main_bundle.js file for my web app. And also bundling many smaller lazy files that are separate from main_bundle. Most every view or component in my app is a lazy file that is dynamically imported only as needed. main_bundle contains utility functions (originally as separate ts files that are bundled all up at build time). These utility functions expose functions to a scoped namespace on window. These functions need to be available to every view on the app.

It’s no problem accessing the functions on each lazy view, since it is available in the scoped window namespace. But, I also need to have LSP support in my editor.

I can do this:

import { UtilityFunction, UtilityFunctionReturnType, etc, etc } from "../../utilfunction.js"

That works great for my LSP. But, when compiling and bundling with esbuild, that whole body of js is sucked in to my lazy file … which is very bad.

Is there a way, in esbuild, tsconfig, SWC or any other method, of only pulling in declarations for my LSP and disabling bundling on build?

I can hack it in my build script by removing the import lines, but if there is a more standard way of doing this Id rather go with that, as I want as least custom build tooling as I can get away with.

How do I split a comma separated string into an array and map to multiple HL7 segments using JavaScript?

I am attempting to convert a single JSON field into multiple HL7 NTE segments based on the number of comma separated values.

Example:

JSON Input

"caseComments" : "+ ABC, + CBA, + CAB",

HL7 Output

NTE|1|+ ABC|
NTE|2|+ CBA|
NTE|3|+ CAB|

Number of comma separated values changes per message

Normally the JSON has multiple separate segments with an individual value in each and I can split based on a predetermined number of values.

But, I am unsure how to take the string split it into an array with different amounts each time and map each value to a single NTE each.

Angular – fakeAsync tests fail after switching from es2016 to es2018 or higher

I am working on an upgrade of my project and i wanted to make sure i was using more up to date ECMAScript.

In my tsconfig.spec.json files I had es2016, and i updated it to be 2018, and even tried out es2022.

Most of my tests will pass after changing versions, but I have a small handful that fail now. For example, I have this method that closes and destroys a modal.

  async destroyModal(): Promise<void> {
    const { modalComponentType, modalComponentRef } = this._state$.value;
    document.querySelector('dialog')?.close();
    this.setState({ modalComponentType, modalComponentRef, modalOpen: false }, ModalStateActions.CloseModal);

    // Wait for 300ms for animation before proceeding
    await new Promise(resolve => setTimeout(resolve, 300));

    // Clear the modal container and notify observers
    this.resetModal();
  }

And I test this like so:

  it('should destroy modal on esc press', fakeAsync(() => {
    service.initModalContainer(hostComponent.componentInstance.viewContainerRef);
    service.createModal(DummyComponent).then(() => verifyModalCreated());
    tick();
    dispatchEscPressEvent();
    tick(500);
    verifyModalDestroyed();
  }));

When using es2016, the test correctly simulates the passage of time and then calls verifyModalDestroyed(). However, when using es2018 or es2022, verifyModalDestroyed() will be called and the test will fail before the Promise resolves inside the destroyModal() method. It is as if tick() has no effect anymore after the update.

Can anyone help me understand that the issue is or what has changed between the versions that these kinds of tests would start failing?

line break on text created by createElementNS

I feel like I have a very dumb question: I create a text with the following command:

text = document.createElementNS("http://www.w3.org/2000/svg", "text")
text.textContent = "some very long text"

How can I make the string printed span over many lines? The common 'n' doesn’t work. And I found some solutions for html text using the <br/> command, but I don’t know to convert the text to html. I also tried

text.innerHTML = "some text" + <br/> + "some more text"

but this didn’t work.

Dropdown not only works in Laravel Blade but on any editor it works great

As already described in the header I’m having a problem.

The dropdown doesn’t work in Laravel Blade, but it works on any editor (as you can very well verify below with the code).

I am using Bootstrap 5.0.2

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.datatables.net/v/dt/jq-3.7.0/dt-2.1.8/datatables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/v/dt/jq-3.7.0/dt-2.1.8/datatables.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lipis/[email protected]/css/flag-icons.min.css" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <title>Project Laravel</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Features</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Pricing</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown link
          </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/micromodal/dist/micromodal.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
</body>

</html>

After many attempts I saw that to make it work I have to add both the cdn of ‘Bootstrap Bundle with Popper’, that is

<!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

and the cdn of ‘Separate Popper and Bootstrap JS’, that is

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

(all 3 together, which is not good). (SEE CODE BELOW)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.datatables.net/v/dt/jq-3.7.0/dt-2.1.8/datatables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/v/dt/jq-3.7.0/dt-2.1.8/datatables.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lipis/[email protected]/css/flag-icons.min.css" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <title>Project Laravel</title>

    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNavDropdown">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Features</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Pricing</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            Dropdown link
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                            <li><a class="dropdown-item" href="#">Action</a></li>
                            <li><a class="dropdown-item" href="#">Another action</a></li>
                            <li><a class="dropdown-item" href="#">Something else here</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

    <script src="https://unpkg.com/micromodal/dist/micromodal.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
</body>

</html>

Now it doesn’t work here anymore, while on my Laravel project it works fine.

I know that you don’t have to put both options regarding cdn, but I don’t know what to do anymore.

Can someone please help me?

How to inject HTML into document.documentElement.innerHTML without closing the tag

I have about 100 lines of boilerplate HTML that every file on my site begins with. It contains the following elements:

<!-- START OF BOILERPLATE TEXT -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta ...>
  <link href="..." rel="stylesheet">
  <script src="..."></script>
  <title>MY_TITLE</title>
</head>
<body>
  <div> Page banner ... </div>
  <hr>
<!-- END OF BOILERPLATE TEXT -->

I’d like to minimize the actual amount of boilerplate code needed for each page, and I’ve come up with the following solution:

<!-- Line 1 of actual code will load external script:

     <script src="/test/scripts/boot.js"></script> 

     For this demo I'm inlining it.   -->

<script>
  async function boot(title) {

    // Will insert header boilerplate in document.documentElement.
    // Actual code will fetch boilerplate code from server.

    const my_demo = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- ****************** page-specific <head> stuff ***************** -->
    <title>${title}</title>
  <!-- ****************** end page-specific stuff    ***************** -->
</head>
<body>
    <h1>Injected by boot.js</h1>
    <hr> <!-- end of page header -->
    <!-- ****************** begin page content ***************** -->
`;

    try {
      document.documentElement.innerHTML = my_demo;
    } catch (my_error) {
      document.write('Error: ', my_error);
    }
  }
</script>

<!-- Line 2 of actual code will invoke boot() -->

<script>boot("Test Title")</script>

<!-- Now we begin adding our body html -->

<p>
  This is the actual content of the page. It should appear under the injected H1 and HR.
</p>

When I browse it, the boot() script appears to correctly insert my <head> and banner html, but my “actual content” doesn’t appear underneath. According to the Safari debugger, there was a </body> tag inserted after the last line inserted by boot(). How can I prevent that?

Fetch API cannot load . Request mode is “no-cors” but the redirect mode is not “follow”

I have this issue only in Brave browser when I disable the Shield. I have OWA analytics file on my blog:

https://stats.jcubic.pl/modules/base/js/owa.tracker-combined-min.js

And I use my Service Worker library called Wayne on my blog. The library intercept all requests and allow creating pure in browser HTTP responses. Similar to Express.js do in Node but in Service Worker. It also has similar API. I’m using the library add syntax highlighting to the JavaScript and CSS files when you open them in the browser.

But I got this error:

Fetch API cannot load https://stats.jcubic.pl/modules/base/js/owa.tracker-combined-min.js. Request mode is “no-cors” but the redirect mode is not “follow”.

The file don’t have any redirect. Domain stats.jcubic.pl have CORS enabled.

The error originate from this code (stripped from irrelevant parts):

self.addEventListener('fetch', (event) => {
    if (filter(event.request) === false) {
        return;
    }
    const promise = new Promise(async (resolve, reject) => {
        const req = event.request;
        try {
            // Wayne logic with early return
            if (event.request.cache === 'only-if-cached' &&
                event.request.mode !== 'same-origin') {
                return;
            }
            
            fetch(event.request).then(resolve).catch(reject);
        } catch(error) {
            this._handle_error(resolve, req, error);
        }
    });
    event.respondWith(promise.catch(() => {}));
});

I don’t know what this line if (event.request.cache ... is doing, found it in some example.

Why this error happen, and how can I get rid of it when I intercept all requests? I’m trying to understand what is the reason for this error, but also want to know how to fix this if there is a way.

I would prefer to fix this in the Wayne library itself so it’s fixed also for other users, not only for my blog.

Just to be complete, this is a code snippet to add OWA to my blog:

  <script type="text/javascript">
   //<![CDATA[
   var owa_baseUrl = 'https://stats.jcubic.pl/';
   var owa_cmds = owa_cmds || [];
   owa_cmds.push(['setSiteId', 'b9a1a51b38e3837c9a5b309ec4122ff3']);
   owa_cmds.push(['trackPageView']);
   owa_cmds.push(['trackClicks']);
   (function() {
       var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
       owa_baseUrl = ('https:' == document.location.protocol ? window.owa_baseSecUrl || owa_baseUrl.replace(/http:/, 'https:') : owa_baseUrl );
       _owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
       var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
   }());
   //]]>
  </script>

It’s obviously the same URL that doesn’t have any direct.

I’ve tried to add _owa.crossorigin = ''; to the above snippet but no difference.

I was thinking of add a flag called skip to the fetch event, but the problem is that the Promise callback is async (there is no other way to write this code, there is try..catch so all problems with async are handled).

quilljs formatting doesn’t work after loaded on page

I’m having an issue where after quilljs html code has been loaded from database works as regular paragraph.

This is how example in database looks:
enter image description here

This is how it looks on page where I’m creating that database item:

enter image description here

and this is how it looks on the result page (where users are supposed to look at it essentially)
enter image description here

Basically it does display text, but it doesn’t show it as h1 (even tho if I check source it does say )
enter image description here

This is my product.ejs code where it’s taking description from database and displaying it:

<%- include("partials/header") %>

<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

<div class="container mx-auto p-6">

  <div class="flex flex-col md:flex-row md:space-x-6 p-2 pb-4">
    <div>
      <h1 class="text-3xl font-semibold text-white"><%= product.name %></h1>
      <p class="text-gray-100 mt-2"><%= product.summary %></p>
    </div>
    <div>
    
    </div>
  </div>


  <div class="flex flex-col md:flex-row md:space-x-6">
    <!-- Product Image -->
    <div class="relative md:w-4/5 bg-gray-900 p-2 rounded-lg">
      <img id="main-image" class="w-full h-[60vh] object-cover rounded-lg shadow-md" src="/uploads/<%= product.mainImage %>" alt="<%= product.name %>">
      <button id="prev-arrow" class="invisible md:visible absolute left-4 w-10 h-10 bg-[#24242462] top-1/2 transform -translate-y-1/2  text-white p-2 rounded-full"><</button>
      <button id="next-arrow" class="invisible md:visible absolute right-4 w-10 h-10 top-1/2 transform -translate-y-1/2 bg-[#24242462] text-white p-2 rounded-full">></button>
      <div class="flex mt-4 space-x-2">
        <img class="image w-[10vh] h-[10vh] object-cover rounded-lg shadow-md cursor-pointer" src="/uploads/<%= product.mainImage %>" alt="<%= product.name %>">
    
        <% product.images.forEach(function(image) { %>
          <img class="image w-[10vh] h-[10vh] object-cover rounded-lg shadow-md cursor-pointer" src="/uploads/<%= image %>" alt="<%= product.name %>">
        <% }); %>
      </div>
    </div>
    <!-- Product Sidebar -->
    <div class="md:w-1/5 mt-6 md:mt-0 flex flex-col justify-between bg-gray-900 rounded-lg p-4">
      <div class="h-full">

        <h1 class="text-1xl font-semibold text-white">Purchase a license</h1>
        <p class="text-xl text-indigo-600 font-bold mt-2">$<%= product.price %></p>
        <hr class="w-full border-b-1 border-gray-700 mt-4">
        <p class="text-gray-100 mt-4">Features:</p>
          <% product.features.forEach(function(feature) { %>
            <p><span class="text-green-500">✓</span><span class="ml-4"><%= feature %></span></p>
          <% }); %>

      </div>
      <div>
        <hr class="w-full border-b-1 border-gray-700 mt-4">

        <button class="w-full mt-6 px-4 py-2 bg-indigo-600 text-white font-semibold rounded-lg shadow-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">Purchase</button>
      </div>
    </div>
  </div>
  <div class="grid bg-gray-900 p-4 mt-4 rounded-lg" id="description">
    <h1 class="text-2xl font-semibold text-white mt-2">Description</h1>
    <div class="description-content">
      <%- product.description %>

    </div>
  </div>

</div>

<script>
  const images = document.querySelectorAll('.image');
  const mainImage = document.getElementById('main-image');
  const prevArrow = document.getElementById('prev-arrow');
  const nextArrow = document.getElementById('next-arrow');

  let currentIndex = 0;

  const updateMainImage = (index) => {
    mainImage.src = images[index].src;
  };

  images.forEach((image, index) => {
    image.addEventListener('click', () => {
      currentIndex = index;
      updateMainImage(currentIndex);
    });
  });

  prevArrow.addEventListener('click', () => {
    currentIndex = (currentIndex > 0) ? currentIndex - 1 : images.length - 1;
    updateMainImage(currentIndex);
  });

  nextArrow.addEventListener('click', () => {
    currentIndex = (currentIndex < images.length - 1) ? currentIndex + 1 : 0;
    updateMainImage(currentIndex);
  });
</script>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>



<%- include("partials/footer") %>

dndkit (React): Cancel drag and drop

In dndkit (https://dndkit.com/), I need to be able to cancel a drag when a certain event happens (ex. change of props). I can’t seem to find any way to do that in the documentations. I am missing something, or is it really impossible?

The only way I have found to trigger a cancel is with a keyboard event (Keyboard sensor). It is not what I want.

How do I store data from month to month in Google App Script?

I have an app script that is setup to a trigger to automatically send out the statistics on the 1st of each month. I have tried to use PropertiesService() class to store the data. I currently have them stored in key name pairs. The variables I need to store are as follows

  • Month
  • Total Referrals
  • Intakes Complete
  • Intakes Returned

How can I save the data from the last month (Example: September) when the email is sent out on the first of the month and pull that data to send out the new statistics for October. The goal is to compare the two months together. The data it’s pulling from is constantly changing and the data on October 1st will be different on October 2nd.

Webpack Dev Server not recognizing newly created HTML files during development

I’m using Webpack Dev Server to serve my project files, but I’m encountering an issue where any new HTML files (or other pages) I create after starting the server (npm start) are not accessible through the browser.

Problem:

  • When I start the development server with npm start, I can
    access existing HTML files (like index.html). Also If I made any changes to the existing files
    then it’s updating nicely.

  • But, if I create a new HTML file or other files in the src, src/pages, src/js etc directory
    after starting the server, I cannot access it through the browser
    (e.g., Cannot GET /about.html).

My Project Structure

my-project/
├── dist/
├── src/
│   ├── css/
│   ├── images/
│   ├── js/
│   └── pages/
│       ├── index.html
│       └── about.html  // New page added
└── webpack.config.js

My Webpack.config.js

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const glob = require("glob");
const { processHtmlLoader } = require("./html-partial-processor");

module.exports = (env, argv) => {
  const isProduction = argv.mode === "production";

  return {
    entry: "./src/js/app.js",
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "js/app.bundle.js",
      clean: true,
    },
    devServer: {
      static: {
        directory: path.join(__dirname, "dist"),
      },
      compress: true,
      port: 3000,
      open: true,
      hot: true,
    },
    module: {
      rules: [
        {
          test: /.(s[ac]ss|css)$/i,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : "style-loader",
            "css-loader",
            "postcss-loader",
            "sass-loader",
          ],
        },
        {
          test: /.html$/i,
          use: [
            {
              loader: "html-loader",
              options: {
                preprocessor: processHtmlLoader,
              },
            },
          ],
        },
        {
          test: /.(png|jpe?g|gif|svg|ico|eot|ttf|woff)$/i,
          type: "asset/resource",
          generator: {
            filename: "images/[name][ext]",
          },
        },
        {
          test: /.m?js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
        },
      ],
    },
    resolve: {
      extensions: [".js"],
    },
    plugins: [
      ...glob.sync("./src/pages/*.html").map((file) => {
        return new HtmlWebpackPlugin({
          template: file,
          filename: path.basename(file),
        });
      }),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
      }),

      ...(isProduction
        ? [
            new MiniCssExtractPlugin({
              filename: "css/app.min.css",
            }),
            new ImageMinimizerPlugin({
              minimizer: {
                implementation: ImageMinimizerPlugin.imageminMinify,
                options: {
                  plugins: [
                    ["mozjpeg", { quality: 70 }],
                    ["pngquant", { quality: [0.6, 0.8], speed: 3 }],
                    ["svgo", { removeViewBox: false }],
                    ["gifsicle", { interlaced: true, optimizationLevel: 3 }],
                    ["imagemin-webp", { quality: 75 }],
                  ],
                },
              },
            }),
          ]
        : []),
    ],
    mode: isProduction ? "production" : "development",
  };
};

My package.json

{
  "name": "marketpro",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "animate.css": "^4.1.1",
    "aos": "^2.3.4",
    "jquery": "^3.7.1",
    "jquery-ui": "^1.14.0",
    "jquery.marquee": "^1.6.0",
    "marketpro": "file:",
    "select2": "^4.1.0-rc.0",
    "slick-carousel": "^1.8.1",
    "vanilla-tilt": "^1.8.1",
    "wowjs": "^1.1.3"
  },
  "devDependencies": {
    "@babel/core": "^7.25.8",
    "@babel/preset-env": "^7.25.8",
    "@fullhuman/postcss-purgecss": "^6.0.0",
    "autoprefixer": "^10.4.20",
    "babel-loader": "^9.2.1",
    "css-loader": "^7.1.2",
    "cssnano": "^7.0.6",
    "glob": "^11.0.0",
    "html-loader": "^5.1.0",
    "html-webpack-plugin": "^5.6.0",
    "image-minimizer-webpack-plugin": "^4.1.0",
    "imagemin": "^9.0.0",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-mozjpeg": "^10.0.0",
    "imagemin-pngquant": "^10.0.0",
    "imagemin-svgo": "^11.0.1",
    "imagemin-webp": "^8.0.0",
    "mini-css-extract-plugin": "^2.9.1",
    "nodemon": "^3.1.7",
    "postcss": "^8.4.47",
    "postcss-loader": "^8.1.1",
    "postcss-preset-env": "^10.0.7",
    "sass": "^1.79.5",
    "sass-loader": "^16.0.2",
    "style-loader": "^4.0.0",
    "tailwindcss": "^3.4.13",
    "webpack": "^5.95.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.1.0"
  }
}

I’ll be very very thankful If anyone help me to solve this. I tried many solutions, but everytime I failed. Thanks in advance.

How can I use React without any bundling or transpilation

I want to use React as a library natively on the browser without any additional tooling such as webpack or Babel. In development, I am tired of having to transpile my React code into regular JavaScript code. This would also let me create a React application that benefits from ES6 modules, as they are also supported natively and do not require any additional tooling such as webpack or Babel.

I have looked into React.createElement but it is not very user friendly. Here is an example of React.createElement

React.createElement('div', null, 'Hello');
// <div>Hello</div>

I would like to use all of the features of React including hooks useState, useEffect, etc. Is there a viable solution to use React without needing to transpile or bundle?

How to dynamically bundle specific views and SDKs for different clients in a Vue.js application?

I am working on a Vue.js application that contains multiple views and consumes several SDKs, which are service providers imported via the package.json. Here is the project structure:

- /src
  - /views
    - abc
    - xyz
  - other folders 
- /package.json
- /routes.js

I’m using vue-cli-service to build the application. Right now, the application is built with all views and SDKs (service providers). However, I need to share the code selectively with different stakeholders:

  1. View Owners: I want to share only specific views without exposing the entire application structure.
  2. Service Provider SDK Owners: Similarly, I need to share specific SDK-related code without revealing which other service providers we are using.

Current Approach:

I plan to write a script that:

  • Takes the service provider and view as parameters.
  • Deletes all other views and service provider dependencies from the package.json.
  • Then sharing with respective owners.

While this approach works, I’m concerned about its scalability and whether there’s a more efficient solution to handle this kind of selective sharing the code base for multiple clients and views.

Only on mobile break point, how to move a child element from one parent to another parent, and insert it at a particular location?

Let’s say I have this HTML(below) and it can not be changed. Using jQuery, I’m having some issues moving the child element bottomExcerpt from parent wrapper , to wrapperTwo.

On mobile, I want to move bottomExcerpt element and place it underneath smallhyperlinks and before picture. So basically, bottomExcerpt will be the middle element between smallhyperlinks and picture.

But for some reason on mobile, bottomExcerpt is getting moved underneath the picture but it should move underneath smallhyperlinks. The picture should be the last element, not bottomExcerpt.

On Mobile, what it is currently displaying as : smallhyperlinks -> picture -> bottomExcerpt

But it should display as: smallhyperlinks -> bottomExcerpt -> picture

I have shared my JS code below. Am I missing something in the code?

JS

$(window).resize(function () {
    if ($(window).width() < 580) {
        $('.wrapperTwo .picture').insertAfter('.wrapperTwo .smallhyperlinks');
        $('.smallhyperlinks h2').removeClass('hidden');
        if ($('.wrapper .bottomExcerpt').length > 0) {
            $('.wrapper .bottomExcerpt').insertAfter('.wrapperTwo .smallhyperlinks');
        }
    } 
    else 
    {
        $('.wrapperTwo .smallhyperlinks').insertAfter('.wrapperTwo .picture');
        $('.smallhyperlinks h2').addClass('hidden'); 
    }
});
HTML

<div class="wrapper">
    <div id="wrapperItems" class="container">
        <div class="row belowContent">
            <div class="favoriteContainer"></div>
            <div class="bottomExcerpt">
                <p>HTML links are hyperlinks. You can click on a link and jump to another document.</p>
             </div>
        </div>
    </div>
</div>

  
<div class="wrapperTwo">
    <div id="wrapperItemsTwo" class="container">
        <div class="row belowContent">
            <div class="picture">
                <div class="symbol"></div>
             </div>
             <div class="smallhyperlinks">
                <h2 class="hidden">H2 Text</h2>
             </div>
        </div>
    </div>
</div>