Symfony Webpack Encore with company common module

There maybe some documentation out there on how to deal with this situation but i don’t even know how to look for it.

Here’s the deal, we have a Symfony “module” (ex Bundle) company-made that we share across multiple projects. Atm it is not listed on packagist and we require it with local composer repository paths if that matters.

Inside the shared module we have some css and some js that needs to be included. Since one of those shared-module (or bundle, w/e you want to call it) has bootstrap (the css frontend toolkit) the module itself requires it together with his css.

Inside the shared module we have a JS file “CoreLibrary.js” and we import the required js like this:

import $ from 'jquery';
import 'bootstrap';
export class CoreLibrary {
    ... more code
}

Then, inside the main application we include the common js file from the app.js file like this:

import { CoreLibrary } from '../public/bundles/thebundlename/js/CoreLibrary';

That doesn’t seem to be ideal, and beside that, with encore we have to repeat

import $ from 'jquery';
import 'bootstrap';
import { CoreLibrary } from '../public/bundles/thebundlename/js/CoreLibrary';

In every .js file we need. That’s so much of a burden that I can’t belive there are no better ways do to that.

Sidenote: not so long ago i had to even follow this one:
Yarn and Webpack Encore configuration in Symfony 4.1 project because i was getting error during “yarn watch”.

What is the correct way of doing it with company-shared module that requires 3rd party library like bootstrap?

How to change the markers style with their status inside azure map spider cluster?

I am using Azure map Spider Cluster in this i am unable to change the style of markers group which is display on click of cluster bubble. I got the success in case of marker which is outside the cluster bubble with the help of HtmlMarkerLayer class but unable to change the style of markers inside cluster bubble. Below is my code:

<html lang="en">
<head>
    <!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
    <link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" rel="stylesheet" />
    <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
    <script src="https://dev2.lsquared.com/api/v1/storage/azure-maps/marker-leyer.min.js"></script>
    <script src="https://dev2.lsquared.com/api/v1/storage/azure-maps/spi-clust.min.js"></script>
    <style>
        .customInfobox { max-width: 240px; padding: 10px; font-size: 12px; margin-right: 20px; white-space: normal }
        .customInfobox .name { font-size: 14px; font-weight: bold; margin-bottom: 5px }
        .popup-content-container .popup-close { top: 12px !important; right: 6px !important; color: #ffffff !important; font-size: 16px !important; line-height: 18px !important; height: 15px !important; background: #000000 !important; width: 15px !important; border-radius: 50px !important; display: flex !important; justify-content: center !important; align-items: center !important; }
        .atlas-map-canvas { width: 100% !important }
    </style>
</head>
<body onload="GetMap()">
    <div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
    <script>
        var map, datasource, popup, spiderManager;
        function GetMap() {
            //Initialize a map instance.
            map = new atlas.Map('myMap', {
                center: [-110, 50],
                zoom: 2,
                view: 'Auto',
                //Add authentication details for connecting to Azure Maps.
                authOptions: {
                    //Use Azure Active Directory authentication.
                    authType: 'subscriptionKey',
                    subscriptionKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                }
            });

            var cordinates = [{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [-84.28295, 30.46454] }, "properties": { "Name": "aa", "Status": "online" } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-84.28295, 30.46454] }, "properties": { "Name": "bb", "Status": "offline" } },
            { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-54.28295, 60.46454] }, "properties": { "Name": "cc", "Status": "offline" } },
            { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-58.28295, 66.46454] }, "properties": { "Name": "dd", "Status": "online" } }];

            var positions = { "type": "FeatureCollection", "features": cordinates };
            map.setCamera({
                //center map
                bounds: atlas.data.BoundingBox.fromData(positions),
                padding: 50
            });

            map.events.add('ready', function () {
                //Create a popup.
                popup = new atlas.Popup();

                //Hide popup when user clicks or moves the map.
                map.events.add('click', hidePopup);
                map.events.add('movestart', hidePopup);

                //Create a data source to add your data to.
                datasource = new atlas.source.DataSource(null, {
                    //Tell the data source to cluster point data.
                    cluster: true,

                    //The radius in pixels to cluster points together.
                    // clusterRadius: 45,
                    clusterProperties: { //Calculate counts for each entity type in a cluster
                        'online': ['+', ['case', ['==', ['get', 'Status'], 'online'], 1, 0]],
                        'offline': ['+', ['case', ['==', ['get', 'Status'], 'offline'], 1, 0]]
                    },

                    //The maximium zoom level in which clustering occurs.
                    //If you zoom in more than this, all points are rendered as symbols.
                    clusterMaxZoom: 24,
                    maxZoom: 24
                });

                //set data to datasource
                datasource.setShapes(positions)
                map.sources.add(datasource);

                //Create a layer for rendering clustered data in the data source.
                var clusterBubbleLayer = new atlas.layer.BubbleLayer(datasource, null, {
                    //Scale the size of the clustered bubble based on the number of points inthe cluster.
                    radius: [
                        'step',
                        ['get', 'point_count'],
                        20,         //Default of 20 pixel radius.
                        100, 30,    //If point_count >= 100, radius is 30 pixels.
                        750, 40     //If point_count >= 750, radius is 40 pixels.
                    ],

                    //Change the color of the cluster based on the value on the point_cluster property of the cluster.
                    color: [
                        'case', //Use a conditional case expression.
                        // all offline
                        ['>', ['get', 'offline'], 0] && ['==', ['get', 'online'], 0],
                        '#a5a5a5',

                        // all online
                        ['>', ['get', 'online'], 0] && ['==', ['get', 'offline'], 0],
                        '#6aa84f',

                        // online and offline both
                        '#ff9900'
                    ],
                    strokeWidth: 0,
                    filter: ['has', 'point_count'] //Only rendered data points which have a point_count property, which clusters do.
                });

                //Create a layer to render the individual locations.
                var shapeLayer = new atlas.layer.SymbolLayer(datasource, null, {
                    filter: ['!', ['has', 'point_count']] //Filter out clustered points from this layer.
                });

                //Add the clusterBubbleLayer and two additional layers to the map.
                map.layers.add([
                    clusterBubbleLayer,

                    //Create a symbol layer to render the count of locations in a cluster.
                    new atlas.layer.SymbolLayer(datasource, null, {
                        iconOptions: {
                            image: 'none', //Hide the icon image.
                        },
                        textOptions: {
                            textField: '{point_count_abbreviated}',
                            offset: [0, 0.4]
                        },
                        filter: ['!', ['has', 'point_count']]
                    }),

                    shapeLayer
                ]);

                markerLayer = new atlas.layer.HtmlMarkerLayer(datasource, null, {
                    markerCallback: function (id, position, properties) {
                        //Check to see if marker represents a cluster.
                        if (properties.cluster) {
                            return new atlas.PieChartMarker({
                                position: position,
                                colors: '#ffffff',
                                fillColor: 'white',
                                strokeColor: 'white',
                                text: properties.point_count_abbreviated
                            });
                        } else {
                            //for single marker
                            return new atlas.HtmlMarker({
                                position: position,
                                color: properties.Status == 'online' ? '#4cae4c' : '#808080',
                            });
                        }
                    }
                });

                // map.events.add('click', markerLayer, markerClicked);

                map.layers.add(markerLayer);

                //Create an instance of the spider manager.
                spiderManager = new atlas.SpiderClusterManager(map, clusterBubbleLayer, shapeLayer);

                //Add event handler for when a feature is selected.
                map.events.add('featureSelected', spiderManager, function (e) {
                    if (e.cluster) {
                        showPopup(e.cluster.geometry.coordinates, e.shape.getProperties(), [0, 0]);
                    } else {
                        showPopup(e.shape.getCoordinates(), e.shape.getProperties(), [0, -20]);
                    }
                });

                //Add event handler for when a feature is unselected.
                map.events.add('featureUnselected', spiderManager, function () {
                    hidePopup();
                });

            });
        }

        var popupTemplate = '<div class="customInfobox"><div class="name">{name} ({status})</div></div>';
        showPopup = function (position, properties, pixelOffset) {
            var content = popupTemplate.replace(/{name}/g, properties.Name).replace(/{status}/g, properties.Status);
            popup.setOptions({
                //Update the content of the popup.
                content: content,
                //Update the position of the popup with the symbols coordinate.
                position: position,
                //Offset the popups position for better alignment with the layer.
                pixelOffset: pixelOffset
            });

            //Open the popup.
            popup.open(map);
        }

        hidePopup = function () {
            popup.close();
        }
    </script>
</body>
</html>

For more explanation, please check below image:
enter image description here

Please help me to fix this.
Thanks in advance.

Best solution for making a clickable map on web page

I want to create a page in WordPress that redirects to other pages. The links should be placed on a map of Sweden. They should contain the featured image and title of the WordPress page that they redirect to.

My idea is that I will make the map with the help of a CSS background-image. On this background image I will manually put small images and titles. The problem that I see arising is that the map might be constrained by mobile proportions and that the links are skewed from where I want the to be seen on the map. What other problems can arise?

Is there a better solution than what I can think of?

Thank you
Lars

Is there a way for a Chrome Extension popup to access the page’s html information?

I want to get a variable from a page’s html to load an url with this variable on a new tab. As I am a begginner, I followed Google’s “Getting Started” tutorial in which they build an extension that works as popup and I am building around it.

The code that gets the variable works perfectly when I test it on the console, but when I click the button it says “Uncaught TypeError: Cannot read properties of null (reading ‘getAttribute’)”. I imagine it happens because the popup has a separate html, so the javascript is not injected into the page I want.

Is there a quick fix to make the popup access the page’s html? If not, how could this feature work in another way?

// Get variable

const client = document.querySelector('[data-client-id]').getAttribute("data-client-id");

// When button is clicked, open new tab and paste URL 

var button = document.getElementById("btn1");
button.addEventListener("click", function () {
    chrome.tabs.create({ url: "https://www.huggy.app/panel/contacts/" + client });
});

How can I make a Circle using TRIANGLE_FAN in webgl using Parametric Equation for the General Circle (x + g)2 + (y + f)2 = r2

Hi, I am new to WEBGL and facing problem while rendering circle using TRIANGLE_FAN

I have written the complete code but don’t know what’s going wrong while rendering semi circle

It is making one unnecessary triangle every time at any position

Here is the code given, How can this be solved this problem?


const canvas_1 = document.getElementById("my_canvas_1");
    var gl = canvas_1.getContext('webgl');
    
    // shader Program
    function ourShader(){
            var vertCode ='attribute vec2 coordinates;' + 'void main(void) {' + ' gl_Position = vec4(coordinates,0.0, 1.0);' + 'gl_PointSize = 1.0;'+'}';
        var vertShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertShader, vertCode);
        gl.compileShader(vertShader);
    
        var fragCode = 'void main(void) {' + 'gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);' + '}';
        var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragShader, fragCode);
        gl.compileShader(fragShader);
    
    
    
        var shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertShader);
        gl.attachShader(shaderProgram, fragShader);
        gl.linkProgram(shaderProgram);
        gl.useProgram(shaderProgram);
        return shaderProgram;
    
    }
    
    // Clear background
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);
    gl.clear(gl.COLOR_BUFFER_BIT);
    var vertices = new Array();
    console.log("vertices: "+vertices);
    
    
    
    let r = 0.2;
    let prec = 0.0001;
    pos = [0.0,-0.5];
    let i=0;
    vertices.push(pos[0],pos[1]);
    
    let x = r+pos[0];
    let x_ = -r+pos[0];
    
    function drawSmallDrop(shadersProg)
    {
        if(x >= x_)
        {
            y = Math.sqrt( (r*r) - ((x-pos[0])*(x-pos[0])) ) + pos[1];  
    
            vertices.push(x,y);
            console.log(x,y,i);
            i++;
            x = x-prec;
        }
        
        if(vertices.length>=3){
    
            var vertex_buffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);        
            gl.bindBuffer(gl.ARRAY_BUFFER, null);
            
            
            gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
            
            var coord = gl.getAttribLocation(shadersProg, "coordinates");
            gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(coord);
            
            gl.drawArrays(gl.TRIANGLE_FAN, 0, vertices.length);
            
        }
        console.log(gl.getError());// for error check
    }    
    shadProg = ourShader();
    setInterval(drawSmallDrop, 1, shadProg) ;
    gl.viewport(0,0,canvas_1.height,canvas_1.height);

 

Changing Mongoose schema type not working

I have a mongoose schema with a property which was a string array.

docs: [String]

I changed the type to an object array as follows

docs: [{ url: String, type: String }]

But when I create a new item, the docs field is still validated with the type string and the following error is thrown.

enter image description here

I even tried dropping the collection and it still not works.

Create a new array from two different array after matching condition [duplicate]

I have two array, want to create a new array that match array1.id == array2.toyId.

Array1 = [
  {
    id: 2,
    name: 'arujn'
  },
  {
    id: 3,
    name: 'abhinav'
  }
]

Array2 = [
  {
    id: 1,
    toyId: 2,
    label: 'label456',
    type: 'text56'
  },
  {
    id: 2,
    toyId: 2,
    label: 'label22',
    type: 'text88'
  },
  {
    id: 3,
    toyId: 3,
    label: 'labe ffum',
    type: 'text35'
  },
  {
    id: 4,
    toyId: 3,
    label: 'label 8',
    type: 'text66'
  }
]

So, new array have name from array1 and label & type from array2,

That array will look like this:-

I am using javascript for this.

Array3 = [
  {
    name: 'arjun',
    newdata: [
      {
        label: 'label456',
        type: 'text56'
      },
      {
       label: 'label22',
       type: 'text88'
      }
    ]
  },
  {
    name: 'abhinav',
    newdata: [
      {
        label: 'labe ffum',
        type: 'text35'
      },
      {
       label: 'label 8',
       type: 'text66'
      }
    ]
  }
]

Please help me to solve this, Thank you in advance.

Types of property ‘licenses’ are incompatible. Type ‘License[]’ is not assignable to type ‘undefined’.ts in getServerSideProps using iron-session?

I get the following error with red-squiggly lines on the async word:

Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined; }; } | { ...; }>' is not assignable to parameter of type '(context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }> | Promise<...>'.
  Type 'Promise<{ props: { admin: Admin; licenses?: undefined; }; } | { props: { admin: Admin; licenses: License[]; }; }>' is not assignable to type 'GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }> | Promise<GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }>>'.
    Type 'Promise<{ props: { admin: Admin; licenses?: undefined; }; } | { props: { admin: Admin; licenses: License[]; }; }>' is not assignable to type 'Promise<GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }>>'.
      Type '{ props: { admin: Admin; licenses?: undefined; }; } | { props: { admin: Admin; licenses: License[]; }; }' is not assignable to type 'GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }>'.
        Type '{ props: { admin: Admin; licenses: License[]; }; }' is not assignable to type 'GetServerSidePropsResult<{ admin: Admin; licenses?: undefined; }>'.
          Type '{ props: { admin: Admin; licenses: License[]; }; }' is not assignable to type '{ props: { admin: Admin; licenses?: undefined; } | Promise<{ admin: Admin; licenses?: undefined; }>; }'.
            Types of property 'props' are incompatible.
              Type '{ admin: Admin; licenses: License[]; }' is not assignable to type '{ admin: Admin; licenses?: undefined; } | Promise<{ admin: Admin; licenses?: undefined; }>'.
                Type '{ admin: Admin; licenses: License[]; }' is not assignable to type '{ admin: Admin; licenses?: undefined; }'.
                  Types of property 'licenses' are incompatible.
                    Type 'License[]' is not assignable to type 'undefined'.ts(2345)

My license.tsx file looks like:

pages/license.tsx

export const getServerSideProps = withSessionSsr(async function ({ req, res }) {
    const admin = req.session.admin
    const licenses = await prisma.license.findMany()

    if (admin === undefined) {
        res.setHeader('location', '/admin')
        res.statusCode = 302
        res.end()
        return {
            props: {
                admin: { isLoggedIn: false } as Admin,
            },
        }
    }

    return {
        props: { admin, licenses },
    }
})

My withSession.ts file looks like:

utils/withSession.ts

import { GetServerSidePropsContext, GetServerSidePropsResult, NextApiHandler } from 'next'
import { withIronSessionApiRoute, withIronSessionSsr } from 'iron-session/next'

import { IRON_OPTIONS } from '@/utils/index'

function withSessionRoute(handler: NextApiHandler) {
    return withIronSessionApiRoute(handler, IRON_OPTIONS)
}

// Theses types are compatible with InferGetStaticPropsType https://nextjs.org/docs/basic-features/data-fetching#typescript-use-getstaticprops
function withSessionSsr<P extends { [key: string]: unknown } = { [key: string]: unknown }>(
    handler: (
        context: GetServerSidePropsContext
    ) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>
) {
    return withIronSessionSsr(handler, IRON_OPTIONS)
}

export { withSessionRoute, withSessionSsr }

How do I solve this? My goal is to want the props to not only return { admin } but also any other objects, in this case, license without fiddling with the utils file since it’s a session wrapper to check if some page is private or not.

Javascript Searches/ Filter nested looping search and exact matches with lots of text

I am currently working on a way to filter through the text of a website. There are divs and inside the divs are p elements which contain text and also the inn tags, which are relevant for the search. My idea was to loop over the divs and then for each div loop through the p tags and then loop over the inn tags and then only display the div if there is a p tag which contains the inn tag with the match. I dont want a plug in solution and if possible in js or jquery since I only work with these two languages.

In short, I want to hide all divs with 0 matches and also hide all p tags with 0 matches and I want to compare the filter with the innerText of the inn tags.

I have been looking up the w3schools search filter option, but I feel like I got stuck and I would appreciate some help or also input on other ways on how to approach this problem. Another question that I have is, that if I search for Fig.1 I also get the matches for Fig. 10 or Fig. 12. Is there a way to only show exact matches?

HTML

<div>
   <p>
      considerations for viable autonomous vehicle systems. The first is a standardization
      of safety assurance, including requirements that every self-driving car must satisfy
      to ensure safety, and how those requirements can be verified. The second is
      scalability, as engineering solutions that lead to unleashed costs will not scale to
      millions of cars and may prevent widespread or even not so widespread adoption of
      autonomous vehicles. Thus, there is a need for an interpretable, mathematical model
      for safety assurance and a design of a system that adheres to safety assurance
      requirements while being scalable to millions of cars.
      <inn>Fig. 1</inn>
      considerations for viable autonomous vehicle systems. The first is a standardization
      of safety assurance, including requirements that every self-driving car must satisfy
      to ensure safety, and how those requirements can be verified. The second is
      scalability, as engineering solutions that lead to unleashed costs will not scale to
      millions of cars and may prevent widespread or even not so widespread adoption of
      autonomous vehicles. Thus, there is a need for an interpretable, mathematical model
      for safety assurance and a design of a system that adheres to safety assurance
      requirements while being scalable to millions of cars.
      <inn>Fig. 12</inn>
   </p>
   <p>  The present disclosure relates generally to autonomous vehicle navigation. Additionally, this disclosure relates to systems and methods for navigating according to potential accident liability constraints.</p>
   <p>  considerations for viable autonomous vehicle systems. The first is a standardization
      of safety assurance, including requirements that every self-driving car must satisfy
      to ensure safety, and how those requirements can be verified. The second is
      scalability, as engineering solutions that lead to unleashed costs will not scale to
      millions of cars and may prevent widespread or even not so widespread adoption of
      autonomous vehicles. Thus, there is a need for an interpretable, mathematical model
      for safety assurance and a design of a system that adheres to safety assurance
      requirements while being scalable to millions of cars.
   </p>
</div>
<div>
   <p>
      considerations for viable autonomous vehicle systems. The first is a standardization
      of safety assurance, including requirements that every self-driving car must satisfy
      to ensure safety, and how those requirements can be verified. The second is
      scalability, as engineering 
      <inn>Fig. 10</inn>
      solutions that lead to unleashed costs will not scale to
      millions of cars and may prevent widespread or even not so widespread adoption of
      autonomous vehicles. Thus, there is a need for an interpretable, mathematical model
      for safety assurance and a design of a system that adheres to safety assurance
      requirements while being scalable to millions of cars.
   </p>
   <p>  considerations for viable autonomous vehicle systems. The first is a standardization
      of safety assurance, including requirements that every self-driving car must satisfy
      to ensure safety, and how those requirements can be verified. The second is
      scalability, as engineering solutions that lead to unleashed costs will not scale to
      millions of cars and may prevent widespread or even not so widespread adoption of
      autonomous vehicles. Thus, there is a need for an interpretable, mathematical model
      for safety assurance and a design of a system that adheres to safety assurance
      requirements while being scalable to millions of cars.
   </p>
</div>

JS CODE


  //declare all variables needed
  var input, filter, figref, test;
  input = document.getElementById('myInputDesc');
  filter = input.value.toUpperCase().trim();
  figref = document.getElementsByTagName('figref');
  test = document.getElementsByTagName('div')

  for (j = 0; j < test.length; j++) {
    p = test[j].getElementsByTagName("p");
    for (let i = 0; i < p.length; i++) {
      fig = p[i].getElementsByTagName("inn");
      if (fig.length == 0) {
        p[i].style.display = "none";
      } else {
        for (let f = 0; f < fig.length; f++) {
          ptxt = fig[f].innerText;
          console.log(ptxt)
          if (ptxt.toUpperCase() == filter) {
            console.log(p[i])
            p[i].style.display = "none";
          } else {
            console.log(test[j])

            p[i].style.display = "block";
          }
        }
      }
    }

  } ```

How to integrate Flutter Web into a existing website without using a iframme

I currently have a working Flutter web application developed, and I want to add it between the header and the footer of my web page but the only way I can manage to do it is adding the Flutter web compilation as a external web and then referring to it as a Iframme.

Because it’s an iframme it does what iframmes do and screw up things like scrolling, real time height adjustments… etc.

I really found myself into a pickle in this one there’s supposedly a way but nobody not shown how.

Thank you in advance.

Converting UTC timestamp in column to user’s time in Postgres VS on client side

I have a message table schema like this (msg_id, msg_from_id, msg_to_id, msg_text, msg_time).
…and I’m thinking about the conversion of the message timestamp.

  1. Store the user’s timezone in the users table, do an AT TIME ZONE = ‘SELECT tz FROM users where …’ while retrieving the messages.
  2. Retrieve the data just as is and convert on the client side

What’s the better approach between the two?

Read user defined metadata headers from uploaded file with nodejs

This is how I fetch the filename from uploaded aws s3 object

exports.handler = async (event) => {
   ...
   const { fileName } = getFileName(event);
};

const getFileName = event => {
    const filename = decodeURIComponent(event.Records[0].s3.object.key).replace(/+/g, " ");        
    return { fileName };
};

My file has user defined metadata such as

x-amz-meta-will-it-rain-today

How can I read this user defined metadata headers using event?

Why cant i require SQLite3 in preload.js?

This is my preload.js file in electron application

window.onload = () => {
  const $ = require('jquery');
  //const sqlite3 = require('sqlite3').verbose();
  //const db = new sqlite3.Database(':memory:');
}

Whenever i try to require sqlite3 in my preload.js file the app crushes.
is there any proper way to add sqlite3 in preload.js file ?