Webpack5-How to execute js file in global scope?

I have an old project that use to load js.

And js file load on global var

such as

index.html

<head>
  <script src="Foo.js"></script>
  <script src="Bar.js"></script>
</head>

Foo.js

var Foo = function(some_var){
   //DO SOMETHING
}
var foo_text = 'HELLO WORLD'

Bar.js

var result = Foo(foo_text)

It works fine

Now I use Webpack to build Foo.js and Bar.js into one js file,but modules cant execute on Global scope

So it will get function Foo is undefined error

This is my webpack.config.ts

import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { Configuration, IgnorePlugin, ProvidePlugin } from 'webpack';
import { Configuration as DevConfig } from "webpack-dev-server"

const isProduction = process.env.NODE_ENV == 'production';


const config: Configuration & DevConfig = {
    entry: './src/index.ts',
    output: {
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: {
        open: true,
        host: 'localhost',
    },
    // devtool: false,
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html',
        }),
        // ignore require function
        new IgnorePlugin({
            'checkResource': (r, c) => {
                if (c.endsWith('js')) {
                    return true
                }
                return false
            }
        }),
        // new ProvidePlugin({

        // }),
    ],
    module: {
        rules: [
            {
                test: /.(ts|tsx)$/i,
                loader: 'ts-loader',
                exclude: ['/node_modules/'],
            },
            {
                test: /.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset',
            },
            {
                // include: path.resolve(__dirname, 'src/js'),

                resourceQuery: path.resolve(__dirname, 'src/js'),
                type: 'javascript/auto'
                // type: 'asset'
                // use: []

            }

            // Add your rules for custom modules here
            // Learn more about loaders from https://webpack.js.org/loaders/
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.jsx', '.js', '...']
    },
};

export default () => {
    if (isProduction) {
        config.mode = 'production';


    } else {
        config.mode = 'development';
    }
    return config;
};

How to resolve it?

My Project is Webpack 5

i tried script-loader ,but repo not support now

Many variables are defined in Foo.js, so I can’t export them all

Foo.js and Bar.js on single file and Foo is in global var


Passing Data Between Python and JavaScript [duplicate]

I read this article at https://healeycodes.com/talking-between-languages about passing data between Python and JavaScript. I don’t understand the purpose of returning “OK”, 200.

I understand that “OK” is parsed to JavaScript and also logged in the console at the end of the index.js file ,but I don’t know what the 200 does.

# app.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)

@app.route('/hello', methods=['GET', 'POST'])
def hello():

    # POST request
    if request.method == 'POST':
        print('Incoming..')
        print(request.get_json())  # parse as JSON
        return 'OK', 200 <---------------------------------------------------------------

    # GET request
    else:
        message = {'greeting':'Hello from Flask!'}
        return jsonify(message)  # serialize and use JSON headers

@app.route('/test')
def test_page():
    # look inside `templates` and serve `index.html`
    return render_template('index.html')
//index.js
// GET is the default method, so we don't need to set it
fetch('/hello')
    .then(function (response) {
        return response.text();
    }).then(function (text) {
        console.log('GET response text:');
        console.log(text); // Print the greeting as text
    });

// Send the same request
fetch('/hello')
    .then(function (response) {
        return response.json(); // But parse it as JSON this time
    })
    .then(function (json) {
        console.log('GET response as JSON:');
        console.log(json); // Here’s our JSON object
    })
// POST
fetch('/hello', {

    // Declare what type of data we're sending
    headers: {
      'Content-Type': 'application/json'
    },

    // Specify the method
    method: 'POST',

    // A JSON payload
    body: JSON.stringify({
        "greeting": "Hello from the browser!"
    })
}).then(function (response) { // At this point, Flask has printed our JSON
    return response.text();
}).then(function (text) {

    console.log('POST response: ');

    // Should be 'OK' if everything was successful
    console.log(text);
});

Lightningchart js – range selection

I would like to be able to select a range or an area (circle, rectangle and lasso) on a scatter chart and be able to drag it.Once the dragging (of area selected is stopped) is stopped then calculations on the selection to be made.

Any help would be appreciated.

I have seen this question (rectangle and also seen the cytometry example with the polgon. I like to select by drawing on the plot and be able to drag.

On the h5 page of the mobile terminal, the video screen of ios 17+ is not fully displayed

On the h5 page of mobile terminal, there is a problem with the display of the video screen in ios 17+. Has anyone ever encountered this situation? The width and height of the video label is 100%, but only part of the screen inside will [fail], which will be displayed normally in ios16, and the object-fit: contain is set; This style also does not use the h5 page of the mobile terminal. There is a problem with the display of the video screen in ios 17+, has anyone encountered this situation? The width and height of the video label is 100%, but only a part of the screen inside will be displayed normally in ios16, and the object-fit: contain is set; This style doesn’t work either

enter image description here

<template>
  <div style="width:100%;height:100%">
    <button style="position:fixed;top:10px;left:10px;z-index:3" @click="isChange = !isChange">
      change
    </button>
    <div :style="[isChange ? style1 : style2, { backgroundColor: 'red' }]">
      <video autoplay muted src="xxx" style="width:100%;height:100%"></video>
    </div>
    <div :style="[isChange ? style2 : style1, { backgroundColor: 'blue' }]">
      <video autoplay muted src="xxx" style="width:100%;height:100%"></video>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      style1: { position: 'fixed', top: '0', left: '0', bottom: '0', right: '0', zIndex: 1 },
      style2: {
        position: 'fixed',
        right: '50px',
        top: '50px',
        width: '120px',
        height: '170px',
        zIndex: 2
      },
      isChange: false
    };
  }
};
</script>

How to rename a date library with the same name in a single file?

I’m encountering an issue when importing two date libraries in the same file. Both libraries share the same name, “Datepicker,” and I’d like to use both of them in my project.

Currently, I’m importing the libraries as follows:

import DatePicker from "react-datepicker";
import Datepicker from "react-tailwindcss-datepicker";

However, due to the identical names, the second import overwrites the first, and I can’t use both libraries simultaneously.

I’m aware that a potential solution would be to rename the second import. However, I’m unsure of the best way to proceed.

Could someone guide me on how to correctly rename the second import to avoid naming conflicts? Is there a recommended convention for handling this kind of situation?

I trie to do this code:

import Datepicker as TDatepicker from "react-tailwindcss-datepicker";

and it is not working

Child retain percentage position in parent on scale

I have a pin (red dot) over image that has percentage position set.

How can I retain pin position the same relative to image when risizing parent wrap container ? (resize wrap container to see the issue)

#wrap{
  position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}
.pin{
  width:50px;
  height:50px;
  background:red;
  position:absolute;
  left:40%;
  top:40%;
}
img{
  display:block;
  width:100%;
}
<div id="wrap">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/1200px-Altja_j%C3%B5gi_Lahemaal.jpg"/>
<div class="pin"></div>
  
  
</div>

is writing code like this bad for efficency? [closed]

You are given two arrays and an index.

Copy each element of the first array into the second array, in order.

Begin inserting elements at index n of the second array.

Return the resulting array. The input arrays should remain the same after the function runs

this was a solution i got from one of answers that they provided

function frankenSplice(arr1, arr2, n) {
    return [...arr2.slice(0, n), ...arr1, ...arr2.slice(n)]};

This was my answer.

function frankenSplice(arr1, arr2, n) {
    let extract=arr2.slice(n)
    let arr3=[]
    let arr4=[]
    if(n===0){
    arr3=[...arr1,...arr2]
    }else if(!n==0){
    for(let i=0;i<n;i++){
        arr4[i]=arr2[i]
    }return arr3=[...arr4,...arr1,...extract]
    }
    return arr3;
}

Java App hosted using Azure App Service – Unexpected token ‘<'

I have a Java application (JSP and Servlets) that is hosted using Azure App Service in three different environments – dev, test and production.

The production instance is now not working and I see a weird blue background on the UI. On the console, I can the see the following errors :

Uncaught SyntaxError: Unexpected token '<' (at dataTables.fixedHeader.min.js:18:195)
Uncaught SyntaxError: Unexpected token '<' (at editor.selectize.js:119:1)
Uncaught SyntaxError: Unexpected token '<' (at editor.autoComplete.js:91:1)

These are Datatables library and on looking at the above JavaScript files – I see the HTML code being inserted which when extracted separately gives the Azure 200 Web App Error Page.

I have tried restarting the Azure app service, scaling up and down the web app but the error still persists. I have checked the configuration across the three environments and those are same and couldn’t find something that might have caused this issue. I have reviewed the Application insights logs but couldn’t find anything. The issue is only showing up for the production instance and not the dev and test instances.

I have also redeployed the code to the App Service but that also didn’t work.

Can some one please guide on what should be the next steps and how do I resolve this issue?

ReferenceError: document is not defined – testing with vitest

I am woking on a Vite project using react framework.
I write some test cases for my app using vitest when I run the test I see the following error

 FAIL  tests/Reservations.test.jsx > Reservations Component > displays error for invalid number of guests exceeding maximum
ReferenceError: document is not defined
 ❯ Proxy.render node_modules/@testing-library/react/dist/pure.js:215:5
 ❯ tests/Reservations.test.jsx:28:9
     26| 
     27|     it("displays error for invalid number of guests exceeding maximum", () => {
     28|         render(<Reservations />)
       |         ^
     29|         fireEvent.change(screen.getByLabelText(/Number of Guests/i), { target: { value: "15" } })
     30|         fireEvent.click(screen.getByText(/Make your reservation/i))

Heres my test code

import { Reservations } from "../src/components"
import { render, screen, fireEvent } from "@testing-library/react"
import { expect, describe, it } from "vitest"

describe("Reservations Component", () => {
    it("renders the 'Book Your Table Now' page title", () => {
        render(<Reservations />)
        const pageTitle = screen.getByText(/Book Your Table Now/i)
        expect(pageTitle).toBeInTheDocument()
    })

    it("displays error for missing date when submitting", () => {
        render(<Reservations />)
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a date/i)
        expect(errorMessage).toBeInTheDocument()
    })

    it("displays error for invalid time outside allowed range", () => {
        render(<Reservations />)
        fireEvent.change(screen.getByLabelText(/Choose Time/i), { target: { value: "14:00" } })
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a time between 5:00 PM and 10:00 PM/i)
        expect(errorMessage).toBeInTheDocument()
    })

    it("displays error for invalid number of guests exceeding maximum", () => {
        render(<Reservations />)
        fireEvent.change(screen.getByLabelText(/Number of Guests/i), { target: { value: "15" } })
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a guests between 1 and 10/i)
        expect(errorMessage).toBeInTheDocument()
    })
})

here is the vite.config.js file

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    include: ["src/**/*.test.js", "tests/**/*.test.js"],
    parallel: true,
  },
});

I tried the following options.

  • delete the node modules folder and install it again.
  • double check the testing environment.
  • double check the code.
  • see the documentation

Typescript generic type array

I’ve got the following method:

getFiveObjectsFromArray(array: string[] | number[] | myInterface[]) {
    return array.slice(0, 5);
  }

I’m using this method a few times, is there any why using Typscript to pass a generic argument instand of using multiple types?

By the way, when i’m trying use parameter ‘T’ i’ve got this error:

“TS7006: Parameter ‘T’ implicitly has an ‘any’ type.”

Why is value duplicated when selecting the default element?

I have a regular Select on my website, where the user can select one option from the list (to make it default). Implemented Select using the Radix library https://www.radix-ui.com/primitives/docs/components/select

There is only problem is that when the user clicks on the desired item to select it as default, in the window where the default value is displayed, it is duplicated twice. The explanation may be confusing, here is a .gif example

enter image description here

const DefaultTitle = () => {
  const { settings, refresh } = useSlicesSettings();
  const { mutate } = useUpdateSlicesSettings({
    onSuccess: () => {
      refresh();
    },
  });
  const [title, setTitle] = useState<string>();

  const [triggers, setTriggers] = useState(settings?.triggers);

  const defaultTrigger = triggers?.find(
    (trigger) => trigger.id === settings?.quickTriggerId
  );

  function getTriggerByTitle(title_: string): SlicesTrigger | undefined {
    return triggers?.filter((trigger_) =>
      trigger_.title === title_ ? trigger_ : undefined
    )[0];
  }

  const onChangeTrigger = async (title_: string) => {
    const selectedTrigger = getTriggerByTitle(title_) ?? defaultTrigger;
    mutate({
      quick_trigger_id: selectedTrigger?.id,
    });
  };

  useEffect(() => {
    const defaultTriggerNow = settings?.triggers?.find(
      (trigger) => trigger.id === settings?.quickTriggerId
    );

    if (settings) {
      setTriggers(getSortedTriggers(settings!.indexes, settings!.triggers));
      setTitle(defaultTriggerNow?.title);
    }
  }, [settings]);

  return (
    <Select.Root value={title} onValueChange={onChangeTrigger}>
      <Select.Trigger>
        <Select.Value />
      </Select.Trigger>
      <Select.Content>
        <Select.Viewport>
          <SlicesDefaultTriggerContent
            trigger={
              getTriggerById(settings!.triggers, settings!.quickTriggerId)!
            }
          />

          {triggers?.map((trigger) => (
            <SlicesDefaultTriggerContent key={trigger.id} trigger={trigger} />
          ))}
        </Select.Viewport>
      </Select.Content>
    </Select.Root>
  );
};

Is it possible to handle the pointerover event on an am5.Container?

When adding an HTML label to the map and attaching a pointerover event, it doesn’t trigger. The goal is to change the HTML content on hover. I tried using a tooltip, but the hover event doesn’t work, and the tooltip displays a border, which is not acceptable in my case

const root = am5.Root.new('#map');

    root.setThemes([
      am5themes_Animated.new(root), // Adding animation
    ]);

    const chart = root.container.children.push(
      am5map.MapChart.new(root, {
        projection: am5map.geoNaturalEarth1(), // Making the map more elongated
      }),
    );
    const polygonSeries = chart.series.push(
      am5map.MapPolygonSeries.new(root, {
        geoJSON: am5geodata_worldLow,
        exclude: ['AQ'],
      }),
    );

    /**
     * Common styles for all countries.
     */
    polygonSeries.mapPolygons.template.setAll({
      fill: am5.color(0x9563c7),
      stroke: am5.color(0x292131),
      strokeWidth: 1,
      fillOpacity: 1,
      templateField: 'polygonSettings'
    });

    /**
     * Coloring individual countries
     */
    polygonSeries.data.setAll(
      this.mapService.countries.map(country => ({
        id: country.id,
        polygonSettings: {
          fill: am5.color(country.fill),
        },
      })),
    );

    /**
     * Creating custom labels for partner countries
     */
    const pointSeries = chart.series.push(
      am5map.ClusteredPointSeries.new(root, {
        minDistance: 30,
        scatterRadius: 10,
        stopClusterZoom: 0.9,
      }),
    );

    pointSeries.data.setAll(
      this.mapService.countries.map(country => ({
        countryCode: country.id,
        img: country.img,
        geometry: country.geometry,
      })),
    );

    pointSeries.bullets.push(
      (_: Root, _2: Series, dataItem: DataItem<IMapPointSeriesDataItem>): Bullet => {
        const { countryCode, img } = dataItem.dataContext as IMapData;

        const container = am5.Container.new(root, {
          cursorOverStyle: 'pointer',
          interactive: true,
          html: `
                <div class="country-label">
                    <img src="${img}" alt="img">
                    ${countryCode}
                </div>
                `,
          x: am5.percent(50),
          centerX: am5.percent(50),
        });

        container.events.on('pointerover', () => { // It doesn't work
          container.set('html', '<div>text</div>');
        });

        container.events.on('pointerout', () => { // It doesn't work
          container.set('html', '<div>text</div>');
        });

        container.events.on('click', function (ev) { // It works.
          console.log(12345);
          container.set('html', '<div>text</div>');
        });

        return am5.Bullet.new(root, {
          sprite: container,
        });
      },
    );

    /**
     * Combining labels.
     */
    pointSeries.set('clusteredBullet', function (root) {
      const container = am5.Container.new(root, {
        cursorOverStyle: 'pointer',
      });

      /**
       * This is a rounded-corner background rectangle for the cluster digit
       */
      container.children.push(
        am5.RoundedRectangle.new(root, {
          width: 60,
          height: 28,
          dx: -30,
          dy: -13,
          cornerRadiusBL: 38,
          cornerRadiusBR: 38,
          cornerRadiusTL: 38,
          cornerRadiusTR: 38,
          fill: am5.color(0x111111),
          fillOpacity: 0.3,
          brightness: 0,
          crisp: true,
          stroke: am5.color(0x171b2c),
        }),
      );

      /**
       * This is a background rectangle to create a blur effect
       */
      container.children.push(
        am5.RoundedRectangle.new(root, {
          width: 64,
          height: 34,
          dx: -31,
          dy: -14,
          cornerRadiusBL: 38,
          cornerRadiusBR: 38,
          cornerRadiusTL: 38,
          cornerRadiusTR: 38,
          fill: am5.color(0x111111),
          blur: 3,
          fillOpacity: 0.55,
        }),
      );

      /**
       * The digit, according to the documentation, is implemented using a Label
       */
      container.children.push(
        am5.Label.new(root, {
          centerX: am5.p50,
          centerY: am5.p50,
          fill: am5.color(0xffffff),
          populateText: true,
          fontSize: 16,
          text: '+{value}',
        }),
      );

      /**
       * Clicking on the cluster zooms into the region.
       */
      container.events.on('click', function (e: am5.ISpritePointerEvent) {
        pointSeries.zoomToCluster(e.target.dataItem);
      });

      return am5.Bullet.new(root, {
        sprite: container,
      });
    });

I attached events using container.events.on. However, pointerover doesn’t work, while click works perfectly.

When i used the useState in react Js for password show and hide on icon click there are not working?

import React,{useState} from "react";


function Password(){

    const [pass,setPass] = useState("password")


    const handleclick =()=>{
        setPass(("password")? "text" : "password")
    
    }
    return(
        <div>
            Password:<span style={{position:"relative"}}><input type={pass} name="" id="" />
            <i onClick={handleclick} style={{position:"absolute", top:"6px" , right:"5px"}} class="fa-solid fa-eye"></i></span>
        </div>
    )
}

export default Password;

When i used the useState in react Js for password show and hide on icon click there are not working. I only show the password show once time but i need to show and hide it whenever click the icon