Import module installed with npm without node.js

Starting to take up Javascript again, it seemed the right moment to move away from the <script> tags and start using module imports.
I’m not using any framework and want to run on a classic apache webserver.

I’ve been struggling to get quite a few libraries to work in plain ES6. I wonder if i’m just not understanding things, or that quite some libraries are not suited for this approach (and expect react/vue/angular to be used).

More specifically currently i’m struggling to import the mapbox gl js library.
I used npm to install mapbox-gl, which installed the package and its dependencies in new /node_modules directory, which I moved to the /src directory.

I’ve an index.html containing:

<script type="module" src="src/index.js"></script>

in index.js

import mapboxgl from './src/node_modules/mapbox-gl/dist/mapbox-gl.js';

This returns following error:

Uncaught SyntaxError: The requested module './src/node_modules/mapbox-gl/dist/mapbox-gl.js' does not provide an export named 'default' 

I’ve been searching around and found the link below. Am I doing something wrong, or is the mapBox library, like quite a few others, just not foreseen to be used in plain ES6? Do i have to rely on cdn’s like esm.sh to deliver a compatible version, or can I handle this myself with the package installed through npm?

Relevant github mapbox discussion: https://github.com/mapbox/mapbox-gl-js/issues/8676

Why not call a fetch function eagerly when it is not even awaited

I get this message in my terminal when running my svelte frontend:

Avoid calling `fetch` eagerly during server side rendering — put your `fetch` calls inside `onMount` or a `load` function instead

I understand what it says and I can definitely put it in an onMount function, however, I don’t see the meaning of it. Imagine this example application, that is close to how I use it:

<script lang="ts">
  let response: Promise<string> = $state(loadData());

  async function loadData(): Promise<string> {
     const response = await fetch("http://my_endpoint");
     return response.json();
  }
</script>

{#await response}
  LOADING
{:then response}
  {response}
{/await}

What I am trying to point at is that the async function loadData is not awaited in the script tag. Only via the await directive in the template. I don’t see how this could be blocking more than any other normal function call. I wonder if that is just a case that was overlooked when programming this warning or if I create a real mistake that will bite me in the ass in a larger project.

Sub-grouping a group by month and year

Doctrine ODM allows to group a set of matched documents: https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.9/reference/aggregation-stage-reference.html#group

Consider documents having properties “type” and “date”. I’d like to get data grouped by type and sub-grouped by month and year.

So far, I was able to group like the following:

array(2) {
  ["_id"]=>
  array(1) {
    ["type"]=>
    string(6) "A"
  }
  ["byMonth"]=>
  array(5) {
    [0]=>
    array(2) {
      ["month"]=>
      int(7)
      ["year"]=>
      int(2025)
    }
    [1]=>
    array(2) {
      ["month"]=>
      int(7)
      ["year"]=>
      int(2025)
    }
    [2]=>
    array(2) {
      ["month"]=>
      int(3)
      ["year"]=>
      int(2025)
    }
    [3]=>
    array(2) {
      ["month"]=>
      int(3)
      ["year"]=>
      int(2025)
    }
    [4]=>
    array(2) {
      ["month"]=>
      int(1)
      ["year"]=>
      int(2025)
    }
  }
}

array(2) {
  ["_id"]=>
  array(1) {
    ["type"]=>
    string(6) "B"
  }
  ["byMonth"]=>
  array(1) {
    [0]=>
    array(2) {
      ["month"]=>
      int(2)
      ["year"]=>
      int(2025)
    }
  }
}

Here is the code used:

$aggBuilder = $dm->createAggregationBuilder(Example::class);

$aggBuilder->match()
    ->field('date')
    ->gte($from)
    ->lte($to)
;

$aggBuilder->group()
    ->field('id')
    ->expression(
        $aggBuilder->expr()
            ->field('type')
            ->expression('$type')
    )
    ->field('byMonth')
    ->push(
        $aggBuilder->expr()
            ->field('month')
            ->month('$date')
            ->field('year')
            ->year('$date')
    )
;

But as you can see, data is not aggregated for type A on months 3 and 7.

So, instead of just pushing the data (hence not grouped by month), how is it possible to aggregate the nested data by month?

Problem creating a query in MySQL via PHP [closed]

I´m trying to connect with MySQL and create a query, but I’m unable and I don’t know why. Hope you can help.

This is my code

$host="myhost";
$username="myusername";
$password= "mypw";
$db="mydB";
$conn = mysqli_connect($host,$username,$password,$database);
if (!$conn) {
    die("Conection failed: " . mysqli_connect_error());
}
else
{
echo "Connected successfully";
}
$sql="SELECT * FROM Books ORDER BY Downloads DESC LIMIT 50";
$result = mysqli_query($conn, $sql);
if (!$result) {
    die("Query error: " . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0)
 {
    echo "<table id='menu'><tr><td>ID</td><td>Name Book</td><td>Downloads</td></tr>";
  while ($row = mysqli_fetch_assoc($result))
   {
     $U = $row['Link'];
     $Title = $row['Title'];
     $plat= $row['Genre'];
    echo "<tr><td><font color='black'><p align='left'><ul type='square'><li><a href='$U' target='blank' title='Download $Titulo $plat Book'>".$Title."</a>(".$plat.")</li></ul></font>";
     }
     echo "</td></tr></table>";
}
else
{
die ("cannot connect");
}
mysqli_close($conn);
?>

Thank you in advance

Codeigniter 4 AbstractRenderer::SORT_FULL;

I have detected the following unusual problem, with codeigniter4.

Install.

PHP: 8.4.10 — CodeIgniter: 4.6.1 -- Environment: development

Error.

Undefined constant KintRendererAbstractRenderer::SORT_FULL

My composer file.

{
    "name": "codeigniter4/appstarter",
    "description": "CodeIgniter4 starter app",
    "license": "MIT",
    "type": "project",
    "homepage": "https://codeigniter.com",
    "support": {
        "forum": "https://forum.codeigniter.com/",
        "source": "https://github.com/codeigniter4/CodeIgniter4",
        "slack": "https://codeigniterchat.slack.com"
    },
    "require": {
        "php": "^7.4 || ^8.0",
        "codeigniter4/framework": "^4.0",
        "tatter/assets": "dev-master",
        "twbs/bootstrap": "v5.3.7"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9",
        "kint-php/kint": "^6.0",
        "mikey179/vfsstream": "^1.6",
        "phpunit/phpunit": "^9.1"
    },
    "autoload": {
        "exclude-from-classmap": [
            "**/Database/Migrations/**"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\Support\": "tests/_support"
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "scripts": {
        "test": "phpunit"
    }
}

It’s a normal zero installation dicodeigniter 4 but instead it gives me this error.
Everything is up to date and should not be there. How can I verify that kint library loads.

I tried putting .env in production and everything works.
When it loads kint in development it gives me this error.
Does anyone know what it can be?

Electron Js + Nuxt Js

Hello fellow developers,
I’ve been having issues packaging my Electron + Nuxt project.

I have been using electron packager, but after successful packaging and I try to open the app, it only shows a blank screen and nothing else.

What could be happening.

find the slow method in nodejs

I was wonder there is a way to find the nodejs slow method, for example, I have a function like this:

function a (){
    b();
    c();
    d();
}

I am using this way:

const lockStartTime = Date.now();
const lockHoldTime = Date.now() - lockStartTime;

to check the time take for each method, is there any way(like java jvm aop without change the code to tracing the time using of each method) to tracing the callstack and each stack takes how much time?

need help loading a wasm file into a node script (using web-tree-sitter)

i’m having trouble loading the wasm into my node script. This is my script …

const path = require('path');
const Parser = require('web-tree-sitter');

(async () => {
  await Parser.ready;
  const wasmPath = path.resolve(__dirname, 'wasm/tree-sitter-javascript.wasm');
  const Lang = await Parser.Language.load(wasmPath);

  const parser = new Parser.Parser();
  parser.setLanguage(Lang);

  const sourceCode = 'function greet() { return "hi"; }';
  const tree = parser.parse(sourceCode);

  console.log(tree.rootNode.toString());
})();

At the line const Lang = await Parser.Language.load(wasmPath); I get this error …

TypeError: Cannot read properties of undefined (reading 'loadWebAssemblyModule')
    at load (c:Usersmarkappsvscode-function-explorernode_modulesweb-tree-sittertree-sitter.cjs:3772:25)
    at processTicksAndRejections (<node_internals>/internal/process/task_queues:95:5)

web-tree-sitter is version 0.25.6.

What am I doing wrong? Can someone tell me the correct way to load wasm into a node script?

all the accordion with same styles opens up on click

I am trying to add some more accrodions to this sample web page design.

https://demo.themefisher.com/constra-bootstrap/index.html

But when I copy the accordion multiple times and try to open one of the accordion, all the accordion with same id opens up. Suppose, I copy the customer service accordion and paste two times. Now if I click on any of those copied accordion, all the three accordions open up. I can’t figure out how to stop it. Thank You!

<!--/ Accordion starts -->
          <div class="accordion accordion-group" id="our-values-accordion">
              <div class="card">
                <div class="card-header p-0 bg-transparent" id="headingOne">
                    <h2 class="mb-0">
                      <button class="btn btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                          Safety
                      </button>
                    </h2>
                </div>

                <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#our-values-accordion">
                    <div class="card-body">
                      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidata
                    </div>
                </div>
              </div>
              <div class="card">
                <div class="card-header p-0 bg-transparent" id="headingTwo">
                    <h2 class="mb-0">
                      <button class="btn btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                          Customer Service
                      </button>
                    </h2>
                </div>
                <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#our-values-accordion">
                    <div class="card-body">
                      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidata
                    </div>
                </div>
              </div>
              <div class="card">
                <div class="card-header p-0 bg-transparent" id="headingTwo">
                    <h2 class="mb-0">
                      <button class="btn btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                          Customer Service
                      </button>
                    </h2>
                </div>
                <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#our-values-accordion">
                    <div class="card-body">
                      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidata
                    </div>
                </div>
              </div>
              
              <div class="card">
                <div class="card-header p-0 bg-transparent" id="headingThree">
                    <h2 class="mb-0">
                      <button class="btn btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                          Integrity
                      </button>
                    </h2>
                </div>
                <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#our-values-accordion">
                    <div class="card-body">
                      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidata
                    </div>
                </div>
              </div>
          </div>
          <!--/ Accordion end -->

accordion section from the website

Deck.gl SolidPolygonLayer shader injection to offset extruded polygons

I am trying to to create a custom Deck.gl SolidPolygonLayer which adds an additional feature attribute to vertically offset extruded polygons (make them float above the map at variable heights).

Based on these docs:
https://deck.gl/docs/developer-guide/custom-layers/writing-shaders#standard-shader-hooks
https://deck.gl/docs/api-reference/core/project

I’ve come up with the following so far

shaders.inject = {
      'vs:#decl': `attribute float instanceBaseOffset;`,
      'vs:DECKGL_FILTER_GL_POSITION': `
        vec3 offsetWorldPosition = geometry.worldPosition + vec3(0.0, 0.01, 0.0);
        vec3 offsetWorldPosition64Low = vec3(0.0);
        vec3 commonPosition = project_position(offsetWorldPosition, offsetWorldPosition64Low);
        // position = project_common_position_to_clipspace(vec4(commonPosition, 1));
        position = vec4(position.x, position.y + 0.1, position.z, position.w);
      `
    }

I am able to access the geometry, offset it (by a constant for now), and then project it to clip space and set the position. The problem is that this resets the extrusion that Deck.gl had already calculated.

My understanding is that geometry.worldPosition contains the original geometry passed to the layer and that position contains the geometry after extrusions have been added and the projection has been calculated. Neither seems to allow me to do what I want.

I have also attempted to modify the worldPosition directly and inject that earlier before extrusions have been calculated, but I don’t seem to have access to the variable at vs:#main-start.

Any insight or suggestions would be helpful,
Thanks!

How to upload an entire folder into DataPower local folder?

I am not able to import an entire folder into datapower becouse it’s allows me to upload files only and I can’t use a JS liberay (e.g: ValidatorJS) in API Connect Gatewayscript becouse I can’t upload the lib folder

screenshot of datapower file system

I tried to upload a compressed file and extract in the datapower but I could not extract it and I do not know if it’s possible or not.

Uncaught ReferenceError: exports is not defined even I don’t use it

I have Electron application with overlay over the loaded website in React and I get error:

Uncaught ReferenceError: exports is not defined
    at index.js:2:23

this is on second line: Object.defineProperty(exports, "__esModule", { value: true });

even I don’t use any NodeJS modules inside React app.

This is my project structure:

/src
  |--assets/
  |--electron/
  |--overlay/
  |--shared/
  |-.eslintrc.cjs
  |-.gitignore
  |-package.json
  |-postcss.config.js
  |-tailwind.config.js
  |-tsconfig.electron.json
  |-tsconfig.overlay.json

Basically assets contains images, electron contains backend code in typescript, overlay contains React code, shared contains types shared between backend and frontend.

This is how my build looks like in package.json:

"build": "bun run build:css && bun run build:overlay && bun run build:electron && cpx "src/assets/**/*" dist/assets",
"build:css": "bunx tailwindcss -i ./src/overlay/index.css -o ./dist/overlay/index.css --minify",
"build:electron": "tsc -p tsconfig.electron.json",
"build:overlay": "bun build src/overlay/index.tsx --config tsconfig.overlay.json --outdir=dist/overlay --format=esm --target=browser --external=electron --external=fs --external=path --external=os --splitting",
"start": "bun run build && electron dist/electron/main.js",
    

/src/overlay contains bunfig.toml, global.d.ts, index.css and index.tsx

bunfig.toml:

entrypoint = "index.tsx"
outdir = "../../dist/overlay"
target = "browser"
sourcemap = true
minify = false
format = "iife"

global.d.ts:

import { Config } from "../shared/types";

export {};

declare global {
    interface Window {
        electronAPI: {
            onSidebarToggle: (callback: () => void) => void;
            openExternal: (url: string) => void;
            saveConfig: (config: Partial<Config>) => void;
            onConfigLoaded: (callback: (config: Config) => void) => void;
        };
    }
}

index.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

index.tsx:

import "./index.css";

import { createRoot } from "react-dom/client";

const mount = document.createElement("div");
mount.id = "sidebar-root";
document.body.appendChild(mount);

const App = () => {
    return <></>;
};

createRoot(mount).render(<App />);

/src/shared contains types.ts:

export const defaultConfig: Config = {
    autofocus: false,
    notify: true,
    rpcEnabled: true,
    informed: false,
    accentColor: "",
};

export interface Config {
    autofocus: boolean;
    notify: boolean;
    rpcEnabled: boolean;
    informed: boolean;
    accentColor: string;
}

If it is important this is /src/electron/preload.ts:

import { contextBridge, ipcRenderer, clipboard, shell } from "electron";
import { Config } from "../shared/types";

declare global {
    interface Window {
        toggleSidebar: () => void;
    }
}

contextBridge.exposeInMainWorld("electronAPI", {
    onSidebarToggle: (callback: () => void) => {
        ipcRenderer.on("sidebar-toggle", (_event, ...args) => {
            console.log("sidebar-toggle event received in preload");
            callback();
        });
    },
    saveConfig: (config: Partial<Config>) =>
        ipcRenderer.send("save-config", config),
    onConfigLoaded: (callback: (config: Config) => void) => {
        console.log("Setting up config loaded listener");
        ipcRenderer.on("config-loaded", (event, config) => callback(config));
    },
    copyToClipboard: (text: string) => clipboard.writeText(text),
    openExternal: (url: string) => shell.openExternal(url),
    checkForUpdates: () => ipcRenderer.invoke("check-for-updates"),
    quitAndInstall: () => ipcRenderer.send("quit-and-install"),
    updateAvailable: (
        callback: (event: Electron.IpcRendererEvent, ...args: unknown[]) => void
    ) => ipcRenderer.on("update-available", callback),
    updateDownloaded: (
        callback: (event: Electron.IpcRendererEvent, ...args: unknown[]) => void
    ) => ipcRenderer.on("update-downloaded", callback),
    downloadUpdate: () => ipcRenderer.invoke("download-update"),
});

I inject overlay into website like:

function injectOverlay(mainWindow: BrowserWindow) {
    const { pathToFileURL } = require("url");
    const overlayScriptPath = path.join(__dirname, "../overlay/index.js");
    const overlayScriptUrl = pathToFileURL(overlayScriptPath).href;

    mainWindow.webContents.executeJavaScript(`
      const s = document.createElement("script");
      s.type = "module";
      s.src = "${overlayScriptUrl}";
      document.body.appendChild(s);
    `);
}

tsconfig.electron.json contains:

{
    "compilerOptions": {
        "outDir": "dist",
        "rootDir": "src",
        "module": "Node16",
        "target": "ESNext",
        "moduleResolution": "node16",
        "esModuleInterop": true,
        "strict": true,
        "jsx": "react-jsx",
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "exclude": ["node_modules"],
    "include": [
        "src/electron/**/*",
        "src/overlay/**/*",
        "postcss.config.js",
        "tailwind.config.js"
    ],
    "assets": ["src/assets/**/*"]
}

tsconfig.overlay.json contains:

{
    "compilerOptions": {
        "outDir": "dist/overlay",
        "rootDir": "src/overlay",
        "module": "ESNext",
        "target": "ESNext",
        "jsx": "react-jsx",
        "moduleResolution": "bundler",
        "esModuleInterop": true,
        "strict": true
    },
    "include": ["src/overlay/**/*"]
}

Fun fact is that if I run:

bun build src/overlay/index.tsx                                                                                                                                         
  --config tsconfig.overlay.json 
  --outdir=dist/overlay 
  --format=esm 
  --target=browser 
  --external=electron --external=fs --external=path --external=os 
  --splitting 

and then: electron dist/electron/main.js

I get no error, but when I run npm start, I get error, even build command is exactly same as in package.json.