I am trying to create react component library and bundling the same with webpack to target esm but my component lib is not treeshakable

Usage of my lib in a project

import {Button, Input} from "my-lib"

if i am using analyze or source-map-explorer in the project to check the build details, build file shows complete lib is included in the final build instead of only adding the button and input component

sharing config of my-lib

webpack config

const fs = require("fs");
const { join, resolve } = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
const webpack = require("webpack");
// const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

const getPackageJson = function (...args) {
    const packageJSON = JSON.parse(
        fs.readFileSync(join(__dirname, "./package.json"))
    );
    if (!args.length) {
        return packageJSON;
    }
    return args.reduce((out, key) => {
        out[key] = packageJSON[key];
        return out;
    }, {});
};

const {
    name: pkgName,
    version,
    description,
    license,
    author,
    homepage,
} = getPackageJson(
    "name",
    "version",
    "description",
    "license",
    "author",
    "homepage"
);

const banner = ` Name: ${pkgName}
 Version: ${version}
 Description: ${description}
 Author: ${author}
 Homepage: ${homepage}

 Copyright (c) ${author.replace(/ *<[^)]*> */g, " ")} and project contributors.

 This source code is licensed under the ${license} license found in the LICENSE file in the root directory of this source tree.`;

// common
const common = {
    mode: "production",
    devtool: "source-map",
    entry: "./src/index.ts",
    externals: ["react"],
    resolve: {
        plugins: [new TsconfigPathsPlugin()],
        extensions: [".js", ".jsx", ".ts", ".tsx", ".css", ".scss"],
    },
    module: {
        rules: [
            {
                test: /.css$/,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /.scss$/i,
                use: ["style-loader", "css-loader", "postcss-loader"],
            },
            {
                // Include ts, tsx, js, and jsx files.
                test: /.(ts|js)x?$/,
                exclude: /node_modules/,
                use: [{ loader: "ts-loader" }],
            },
            {
                test: /.m?js$/,
                resolve: {
                    fullySpecified: false,
                },
            },
        ],
    },
    plugins: [
        // new CleanWebpackPlugin(),
        new webpack.BannerPlugin(banner),
        new BundleAnalyzerPlugin(),
    ],
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                // parallel: true, // Multi-threading
                extractComments: false,
            }),
        ],
    },
};


module.exports = [
    {
        output: {
            path: resolve(__dirname, "dist"),
            filename: "[name].common.js",
            library: {
                type: "commonjs",
            },
        },
        ...common,
    },
    {
        output: {
            path: resolve(__dirname, "dist"),
            filename: "[name].umd.js",
            libraryTarget: "umd",
        },
        ...common,
    },
    {
        experiments: {
            outputModule: true,
        },
        output: {
            path: resolve(__dirname, "dist"),
            filename: "[name].esm.js",
            library: { type: "module" },
            environment: { module: true },
            // sourceType: module,
        },
        ...common,
    },
    {
        output: {
            path: resolve(__dirname, "dist"),
            filename: "[name].min.js",
        },
        ...common,
    },
];

.babelrc

{
    "sourceMaps": "inline",
    "presets": [
        [
            "@babel/preset-env",
            {
                "loose": true,
                "modules": false,
                "targets": {
                    "esmodules": true
                },
                "useBuiltIns": "entry",
                "corejs": { "version": 3, "proposals": true }
            }
        ],
        "@babel/preset-react",
        [
            "@babel/preset-typescript",
            {
                "isTSX": true,
                "allExtensions": true
            }
        ]
    ],
    "plugins": [
        [
            "babel-plugin-styled-components",
            {
                "ssr": false
            }
        ]
    ]
}

tsconfig.json

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "lib": ["ES2017", "ES7", "ES6", "DOM"],
        "strict": true,
        "strictNullChecks": true,
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "baseUrl": "./",
        "outDir": "./lib",
        "typeRoots": ["node_modules/@types"],
        "moduleResolution": "node",
        "esModuleInterop": true,
        "sourceMap": true,
        "declaration": true,
        "declarationDir": "./build/",
        "noEmitOnError": true,
        "jsx": "react-jsx",
        "importHelpers": true,
        // "noEmit": false,
        // "allowJs": true,
        // "skipLibCheck": true,
        // "noImplicitThis": false,
        // "allowSyntheticDefaultImports": true,

        "paths": {
            "@components/*": ["src/components/*"],
            "@providers/*": ["src/providers/*"],
            "@utils/*": ["utils/*"],
            "@src/*": ["src/*"]
        },
        "noErrorTruncation": true
    },
    "include": ["src/**/*.ts", "src/**/*.tsx", "examples/**/*"],
    "exclude": ["node_modules", "dist", "**/*.spec.tsx", "**/*.spec.ts"]
}

package.json

"type": "module",
    "main": "dist/index.js",
    "module": "dist/main.esm.js",
    "unpkg": "dist/main.min.js",
    "types": "dist/index.d.ts",
    "sideEffects": false,
    "files": [
        "dist",
        "src",
        "tsconfig.json"
    ],
    "scripts": {
        "bundle": "webpack --config webpack.lib.config.js",
    },

If we are consuming only 2 components of my-lib in a project, then final build of my project should have only those 2 components instead of complete my-lib package

Radio Button Selection Sync Issue, Selection in One Question Affects Another

so i have a quiz page where it can show different value based on current state like the question, and answer option, i use radio button for answer option. So my problem is when i select the first option of the first question, when i hit next to the second question, the answer option of the second question got affected it also select the first option. im using react

const [currentSoal, setCurrentSoal] = useState(0);
const [selectedOptions, setSelectedOptions] = useState({});

const handleOptionChange = (event) => {
    const { name, value } = event.target;
    setSelectedOptions({
        ...selectedOptions,
        [name]: value,
    });
};
{item.soal[currentSoal].opsi.map((opsiItem, opsiIndex) => (
    <label key={opsiIndex}>
        <input
            id={`option-${opsiItem.id}`}
            type="radio"
            name={item.soal[currentSoal].id}
            value={opsiItem.id}
            checked={selectedOptions[item.soal[currentSoal].id === opsiItem.id]}
            onChange={handleOptionChange}
        />
        <span className="pl-5">{opsiItem.opsi}</span>
    </label>
))}

i have an example but using laravel blade view like this, but im confuse how to implement it in react

@foreach ($question->opsi as $option)
    <div class="form-check">
       <input class="form-check-input" type="radio" 
           name="soal[{{ $question->id }}]"
           id="option-{{ $option->id }}"
           value="{{ $option->id }}"
              @if (old("soal.$question->id") == $option->id) 
                  checked 
              @endif />
        <label class="form-check-label" for="option-{{ $option->id }}">
            {{ $option->opsi }}
        </label>
    </div>
 @endforeach

Jest Testing. How to use dynamic substitution for jest functions?

I have a series of test cases like this:

  it('should render button disabled', async () => {
    render(...);

    const button = screen.getByRole("button");
    expect(button ).toBeDisabled();
  });

for some cases, it will be button disabled. I am trying to use it.each() to test instead of writing individual cases.

For such situation, the test will be toBeEnabled() and toBeDisabled(). Is it possible to use variables for these jest functions ?

Thanks.

PS: I’m using enabled/disabled as an example. In other cases, it would involve more function.

Why does my function always execute but returns false as the same time using Ajax with WordPress?

I have the following Javascript:

// on button click, update database values
jQuery( document ).ready(function($) {
    $("#button-set-view").click(function(){        
        var data = {
            'action':        'my_action',
            'osm_geometry':  osm_geometry,
            'latitude':      latitude,
            'longitude':     longitude      
        };
        $.post(my_ajax_object.ajax_url, data, function(response) {
            alert('Server response: ' + response);
        });
    });
});

In my main app php file, I then run below;

add_action('wp_ajax_my_action', 'my_action');

function my_action() {
    
    $osm_geometry   = $_POST['osm_geometry'];
    $latitude       = $_POST['latitude'];       // field_64b485ae5c619
    $longitude      = $_POST['longitude'];      // field_64b4858b5c618
    
    $args = array(
        'posts_per_page'    => 1, // for safety, set the return value as 1 record
        'post_type'         => 'fs_ski_resorts',
        'meta_key'          => 'osm_geometry',
        'meta_value'        => $osm_geometry 
    );

    $id = ($query[0]->ID);

    if (update_field('field_64b38c4e3ec56', array(
            'field_64b485ae5c619'=>$latitude,
            'field_64b4858b5c618'=>$longitude,
        ), $id))
    {
        echo 'Successfully updated '.$id;
    } else {
       echo ''Failed or Nothing to Updated.';
    } 
   
    wp_reset_postdata(); 
    wp_die();
}

The field values are updated but I always get "Failed or Nothing to Update." as a result. If I run $result = (updated_field(...), and echo $result to screen it also doesn’t show true or false. update_field is an ACF function.

How can I capture success or failure correctly please?

TamperMonkey: Modify Post Request Data Payload OR Change Response Body

I’m still fairly new to user scripts/Javascript and have been looking for a way modify either the request data payload or change the returned response body of a post request. The site in question performs a XHR POST request (in curl)

curl 'https://somesite.com/endpoint' -X POST -H {various headers} --data-raw 'id=someid'

and usually returns a JSON response (36 character alphanumeric string, made up here) like

dg9gt8hs-ds8g-09ds-9dsf-ad8ygs70dsd0

Sometimes, the response can be a string that is checked against logic in a Javascript function. I’ve tried putting together a user script in TamperMonkey for this, but I’m not familiar enough with Javascript to get it working.

Ideally, this script would only be triggered for https://somesite.com/endpoint, and then randomly change someid before the POST request is sent OR modify the response body before being passed to the site’s functions.

Is this possible with TamperMonkey? Thanks in advance for the help!

How to make multiple post requests with one button handler in React?

I am trying to generated PDF for my application.Pdf functionality is working well.I have two PDF
functionality for post request which is seperate right now.Those two PDF post functionality
is setting up two indivisual button handler.
Ex1: const handleViewOrder = async () => {
const response = await fetch(‘/generate_pdf‘, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
});
}
Ex2: const handleProductSellsPdf = async () => {

  const response = await fetch('/**generate_item_pdf**', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });

what im trying now that,combine those Ex1 and Ex2 in one button handler and generate pdf
once i click button.

backend code is working fine.
problem is that i dont know how to do it in in react/java script.
any suggestion please

this is my code of pdf generate functionality for diffrent button handler in react :

const handleViewOrder = async () => {
    try {
      const response = await fetch('/generate_pdf', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const responseData = await response.json();
      const pdfURL = responseData.pdf_url; 
      localStorage.setItem("pdf_url",pdfURL)
      window.open(pdfURL, '_blank');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }

  };
const handleProductSellsPdf = async () => {
    try {
      const response = await fetch('/generate_item_pdf', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const responseData = await response.json();
      const pdfURL = responseData.pdf_url; 
      localStorage.setItem("pdf_url",pdfURL)
      window.open(pdfURL, '_blank');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

Correct display of items and scrolling text slider

I have a simple text slider, but I’m now solving the following problems there.

  1. I only want to display what fits in 300px when it loads. So in this case it displays “Some longer text, Text, Some text, Some..” but to me it displays part of another element. Is it possible to limit it to show only the complete items?
  2. Moving. If only the visible items are displayed, is it possible to make it move two fully visible items each time? It doesn’t matter which side. And it always ends with the last item at the end of the slider or the first one at the beginning. Is it possible to do this?

Here is my code.

var currentPosition = 0;

  function moveMenu(direction) {
    var menu = document.getElementById('menu');
    var menuWrapperWidth = document.querySelector('.menu-wrapper').offsetWidth;
    var totalMenuWidth = [...menu.children].reduce((acc, el) => acc + el.offsetWidth + 20, 0);
    var maxScroll = totalMenuWidth - menuWrapperWidth;
    var scrollStep = menuWrapperWidth / 2;

    if (direction === 'next' && currentPosition > -maxScroll) {
      currentPosition -= scrollStep;
      currentPosition = Math.max(currentPosition, -maxScroll);
    } else if (direction === 'prev' && currentPosition < 0) {
      currentPosition += scrollStep;
      currentPosition = Math.min(currentPosition, 0);
    }
    menu.style.transform = `translateX(${currentPosition}px)`;
  }

  document.getElementById('prevButton').addEventListener('click', function() {
    moveMenu('prev');
  });
  document.getElementById('nextButton').addEventListener('click', function() {
    moveMenu('next');
  });
.menu-wrapper {
  width: 300px;
  overflow: hidden;
}
.menu {
  display: flex;
  white-space: nowrap;
  transition: transform 0.5s ease;
}
.menu-item {
  margin-right: 20px;
  flex-shrink: 0;
}
<div class="menu-wrapper">
  <button id="prevButton">Prev</button>
  <div id="menu" class="menu">
    <span class="menu-item">Some longer text</span>
    <span class="menu-item">Text</span>
    <span class="menu-item">Some text</span>
    <span class="menu-item">Some text</span>
    <span class="menu-item">Longer text</span>
    <span class="menu-item">Some longer text</span>
    <span class="menu-item">Text</span>
    <span class="menu-item">Some text</span>
  </div>
  <button id="nextButton">Next</button>
</div>

How do you search a column that uses a select element to search on its value instead of its key with datatables.net in js

So I have a table column that uses a list of key value pairs in a razor page for a select element and when searching the table using the main datatables search bar this column gets searched on the id and not the value when using said datatables search bar. How can I allow he regular search on the other columns and do a custom search on this 1 column based on its value instead of the id while still using only the main search bar?

How to replace with hide/show div1 with div2 and div2 with div3 using onclick() and a function in JavaScript

i want to replace divs using onclick() in a way that they seem to rotate from the default div1 to div2 to div3 and back to div1 and over and over again.

i have with me something i have made that is working just fine but i am stuck trying to make it return to the default condition (conditions) and rotate the function show() from start to end and end to start.

this is the code i have that is working just fine but not executing the function show() from start to end and end to start

<!DOCTYPE html>
  <html>
  <body>
 <div style="margin-left:30%;margin-bottom:20%;">
    <div id="div1" style="display:block">
    <h2>one</h2>
</div>
<div id="div2" style="display:none">
    <h2>two</h2>
</div>
    <div id="div3" style="display:none">
    <h2>three</h2>
</div>



    <div id="div4" style="display:block">
    <h2>one under</h2>
</div>
<div id="div5" style="display:none">
    <h2>two under</h2>
</div>
    <div id="div6" style="display:none">
    <h2>three under</h2>
</div>

<button onclick=show()>click here</button>
</div>
</body>
<script>
function show() {
    let div1 = document.querySelector('#div1');
    let div2 = document.querySelector('#div2');
let div3 = document.querySelector('#div3');
    let div4 = document.querySelector('#div4');
    let div5 = document.querySelector('#div5');
let div6 = document.querySelector('#div6');


    if (div1.style.display == "block" && div4.style.display == "block") {
        div1.style.display = "none";
        div2.style.display = "block";
       div4.style.display = "none";
        div5.style.display = "block";
    } else {
        div1.style.display = "block";
        div2.style.display = "none";
     div4.style.display = "block";
        div5.style.display = "none";
    }
   if (div2.style.display == "block" && div5.style.display == "block") {
        div2.style.display = "block";
        div3.style.display = "none";
   div5.style.display = "block";
        div6.style.display = "none";
    } else {
        div2.style.display = "none";
        div3.style.display = "block";
 div5.style.display = "none";
        div6.style.display = "block";
    }
   if (div3.style.display == "block" && div6.style.display == "block") {
        div2.style.display = "none";
       div1.style.display = "none";
        div3.style.display = "block";
       div5.style.display = "none";
       div4.style.display = "none";
        div6.style.display = "block";
  } 
 
  }
 
</script>
</html>

storefront files Webpack:// to apache htdocs folder how?

I have a example storefront webpack files and there are src, cloudinary, js, node modules, web, and webpack folders in storefront doc.And a lot of scss and js files in folders.

in mainpage.js there are webpack:// paths to this .js files but this paths have webpack://path/./path/path/.js and webpack://path/../../path/.js so ı cant have . or .. name docs for this paths in windows.
How can ı run this schema in apache folder or install webpack:// host to apache root folder or windows?
And if all files be in right folders .js files run correctly without any install app like nmp install?

Dont run index.html files without paths

How to make my website work with node.js? [closed]

I’m a teacher and I created a game that my students can play during class. For this game, they have to log in to play and their score is stored in MySQL database. I can always check their progress since I can access the database and give them feedback. Everything is working perfectly, but I decided to change the game to be multiplayer and to do that, I’m using socket.io and express. The multiplayer part is working well too, but now I need to put it together with login, register, score, etc.

So, the part that I need help with is that I don’t know how I can make the game run on the server, with register, login, score, database, and everything that is already working on my website.

The part that I handle login, register, password recovering and scores are .php files, and I use three.js for the game logic.

I haven’t tried anything yet, because I don’t know where to start.

I’m having trouble using window.scrollY on the mobile version of the website

I have a website that prints the current Y position to the console whenever the window is scrolled up or down. It works perfectly on the computer, even when I resize the window. However, when I access it on a mobile device or even in the mobile version of Chrome’s developer mode, it does not print the value of window.scrollY. It remains at 0, even when scrolling down. However, it starts to appear when I reach approximately the middle of the page.:

function chama() {
        let posVert = window.scrollY || document.documentElement.scrollTop || 0;
        console.log(posVert);
    }
    
    window.addEventListener("touchmove", chama);
    window.addEventListener("scroll", chama);
```[enter image description here](https://i.stack.imgur.com/DYnGB.png)



I tried to create the same code with an empty HTML file, and it worked both on desktop and mobile. I believe there might be something in my HTML causing the issue, but I'm not sure what it is.

IP rotation is not happening

I’m using IPRoyal to scrap the same website with IP rotation for every request.
I get the same IP address every iteration until I restart the app. Only then the ip gets changed.

    const axiosInstance =
  process.env.PROXY_PROTOCOL &&
  process.env.PROXY_HOST &&
  process.env.PROXY_PORT &&
  process.env.PROXY_USERNAME &&
  process.env.PROXY_PASSWORD ?
  axios.create({
    ...(process.env.PROXY_ENABLED === 'true' ?
      {
        proxy: {
          protocol: process.env.PROXY_PROTOCOL,
          host: process.env.PROXY_HOST,
          port: Number(process.env.PROXY_PORT),
          auth: {
            username: process.env.PROXY_USERNAME,
            password: process.env.PROXY_PASSWORD
          }
        }
      } :
      {}),
    headers: {
      accept: '*/*',
      'accept-language': 'en-US,en;q=0.9',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': '"Windows"',
      'sec-fetch-dest': 'empty',
      'sec-fetch-mode': 'cors',
      'sec-fetch-site': 'same-origin',
      'Referrer-Policy': 'strict-origin-when-cross-origin',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      cookie: USD_EN_US_COOKIE
    }
  }) :
  null;

// Get ip address
for (let i = 0; i < 5; i++) {
  const ipResponse: AxiosResponse = await axiosInstance.get('https://api.ipify.org');
  if (!ipResponse || ipResponse.status !== 200 || !ipResponse.data) {
    throw new Error('No response from ipify');
  }

  const ip = ipResponse.data;
  if (!ip || !ip.length) {
    throw new Error('No ip address');
  }

  console.log('ip address', ip);
}

I get:

ip address x.x.x.x
ip address x.x.x.x
ip address x.x.x.x
ip address x.x.x.x

instead of a random IP address every iteration.

Comparing dynamic client-side time with server-side time in Flask and JavaScript

I am working on a Flask web application where I have a list of medications with scheduled times (obj.time). I want to dynamically compare these scheduled times with the client-side time to determine whether it’s time to take the medication.

<!-- index.html -->
<html lang="en">
<head>
    <!-- ... (other head elements) ... -->
    <script>
        // ... (existing JavaScript code) ...
        function updatePage() {
            $.ajax({
                url: '/update_page',
                type: 'GET',
                data: { current_time: new Date().toISOString() },
                dataType: 'json',
                success: function(data) {
                    $('#current_time').text(data.current_time);
                },
                complete: function() {
                    setTimeout(updatePage, 1000);
                }
            });
        }
        $(document).ready(function() {
            updatePage();
        });
    </script>
</head>
<body>
    <!-- ... (existing HTML code) ... -->
    <p>Current hour:<span id="current_time"></span></p>
    {% for obj in objects %}
        {% if obj.time == current_time %}
            <p>Ia medicamentul: {{ obj.name }}</p>
            <td><a href="{{ url_for('confirm_approved', object_id=obj.id, object_instructions=obj.instructions,object_dosage=obj.dosage) }}">Confirma ca ai luat pastila</a></td>
        {% endif %}
    {% endfor %}
    <!-- ... (existing HTML code) ... -->
</body>
</html>

How can I effectively compare the client-side time (current_time updated by JavaScript) with the server-side time (obj.time retrieved from the Flask server),because i can only see the real time with this span id=”current_time” ?