How can i make a Progress bar using Google Storage with PHP?

how can i make a Progress bar using Google Storage with PHP?

Here is my code:

try
{
    $storage = new StorageClient([
        'keyFilePath' => 'test.json',
    ]);

    $file_tmp = $_FILES['my_file']['tmp_name'];
    $ext = pathinfo($_FILES['my_file']['name'], PATHINFO_EXTENSION);
    $filename = 'uploads/test_file'. $ext;
    $bucketName = 'test-1';
    
    $file = fopen($file_tmp, 'r');
    $chunksize = $_FILES['my_file']['size'];
    $bucket = $storage->bucket($bucketName);

    $options = [
        'name' => $filename,
    ];

    $object = $bucket->upload($file, $options);
    // freezing code :(
    echo $filename . " is uploaded successfully.";
}
catch(Exception $e)
{
    echo $e->getMessage();
}

I have reviewed all the documentation, but I have not found a solution. What I want is extremely simple, I want to get information when uploading a file.

https://github.com/googleapis/google-cloud-php/tree/main/Storage/tests

How can a nested responsive navigation menu be built in SASS so that a user can add as many submenus as needed using only HTML and no extra CSS code?

Using this video tutorial, I designed a responsive navigation menu in SASS that allows me to add sub-menus, but each sub-menu requires the creation of a new selector in SASS. I want to style the menu and sub-menus once so that a beginner user does not need to add any new selectors in SASS to add submenus in HTML.

SASS:

@font-face {
    font-family: "Roboto";
    font-style: normal;
    src: url("../Fonts/Roboto.ttf") format("truetype");
}

* {
    font-family: "Roboto";
    font-size: 20px;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    direction: rtl;
}

.logo {
    z-index: 10;
    position: relative;
}

.header {
    float: center;
    background: linear-gradient(to top, #9472ff 2%, #3d00ff 98%) center/100%;
    border-radius: 10px;
    box-shadow: 1px 2px 4px #000000;
    color: white;
    width: 100%;
    height: 100px;
    padding-left: 0px;
    padding-right: 10px;
    padding-top: 40px;
    text-align: right;
    text-shadow: 0px 2px 2px #000000;
}

.nav {
    list-style: none;
    display: flex;
    gap: 24px;
}

.nav li a {
    text-decoration: none;
    font-size: 28px;
    color: #f3b238;
    display: inline-block;
    width: 100%;
    position: relative;
}

.nav li a:hover {
    color: #fff;
}

.nav li a::after {
    content: "";
    width: 0%;
    height: 4px;
    background-color: #fff;
    position: absolute;
    left: 0px;
    bottom: -5px;
    border-radius: 5px;
    transition: all 0.7s ease;
}

.nav li a:hover::after {
    width: 100%;
}

@media (max-width: 769px) {
    .nav {
        position: fixed;
        inset: 0;
        background: linear-gradient(to top, #9472ff 2%, #3d00ff 98%) center/100%;
        flex-direction: column;
        align-items: center;
        padding-top: 150px;
        transform: translateX(100%);
        transition: all 0.7s ease;
    }

    .nav[data-visible=true] {
        transform: translateX(0%);
    }

    .nav-menu-button {
        position: absolute;
        display: flex;
        z-index: 10;
        justify-content: center;
        align-items: center;
        height: 80px;
        width: 80px;
        right: -10px;
        top: -10px;
        cursor: pointer;
        transition: all 0.7s ease-in-out;
    }

    .nav-menu-line {
        width: 50px;
        height: 6px;
        background-color: #d0fd66;
        border-radius: 5px;
        transition: all 0.7s ease-in-out;
    }

    .nav-menu-line::before,
    .nav-menu-line::after {
        content: "";
        position: absolute;
        width: 50px;
        height: 6px;
        background-color: #d0fd66;
        border-radius: 5px;
        transition: all 0.7s ease-in-out;
    }

    .nav-menu-line::before {
        transform: translateY(-16px);
    }

    .nav-menu-line::after {
        transform: translateY(16px);
    }

    .nav-menu-button.open .nav-menu-line {
        transform: translateX(-50px);
        background: transparent;
    }

    .nav-menu-button.open .nav-menu-line::before {
        transform: rotate(45deg) translate(35px, -35px);
    }

    .nav-menu-button.open .nav-menu-line::after {
        transform: rotate(-45deg) translate(35px, 35px);
    }
}

JavaScript:

const MenuButton = document.querySelector(".nav-menu-button");
const Navigation = document.querySelector(".nav");
let MenuOpen = false;
MenuButton.addEventListener("click", () => {
    switch (!MenuOpen) {
        case true:
            MenuButton.classList.add("open");
            Navigation.setAttribute("data-visible", "true")
            MenuOpen = true;
            break;
        default:
            MenuButton.classList.remove("open");
            Navigation.setAttribute("data-visible", "false")
            MenuOpen = false;
            break;
    }
});

HTML:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pasha-Piano</title>
    <link rel="stylesheet" href="SCSS/AppStyle.css">
    <link rel="stylesheet" href="SCSS/AppStyle.scss" media="(max-width:769px)">
    <link rel="stylesheet" href="Script.js">
</head>

<body>
    <div class="logo" role="img">
        <img src="Images/Logo.png" height="100" style="width:auto; float:left;" />
    </div>
    <header class="header">
        <div class="nav-menu-button">
            <div class="nav-menu-line"></div>
        </div>
        <nav class="nav" data-visible="false" role="navigation">
            <li><a href="#">Home</a></li>
            <li><a href="#">Goods</a></li>
        </nav>
    </header>
    <script src="Script.js"></script>
</body>

</html>

If your answer solves my problem (by using this multi-level dropdown style), I will accept and score it.

Thanks.

How to create Custom Document(_document.tsx) in Nextjs 13+

I’m trying to create a React Portal in Nextjs 13+ app, but there are no more local app/pages folder in which you would usually create Custom Document(_document.tsx) file. Instead its already created in server side, outside of src directory.

Or is there a better way of dealing with that problem?

My current _document.tsx is located in src/app directory and it has code:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
    return (
        

        <Html>
            <Head />
            <body>
                <Main />
                <NextScript />
                <div id='portal' />
            </body>
        </Html>
    )
}

And then I have a Modal.tsx file,

import React, { ReactElement, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'

type PropsType = {
    active: boolean
    setActive: (arg: boolean) => void
    children: ReactElement
}

function Modal({ active, setActive, children }: PropsType) {
    const [domReady, setDomReady] = useState(false)
    const ref = useRef<Element | null>(null)

    useEffect(() => {
        ref.current = document.querySelector<HTMLElement>('portal')
        setDomReady(true)
    }, [])

    return domReady && typeof window === 'object'
        ? createPortal(
                <div
                    className={active ? 'modal active' : 'modal'}
                    onClick={() => setActive(false)}
                >
                    <div
                        className={active ? 'modal__content active' : 'modal__content'}
                        onClick={e => e.stopPropagation()}
                    >
                        {children}
                    </div>
                </div>,
                document.getElementById('portal')!
          )
        : null
}

export default Modal

How to get the id of the desired album and add it to the if modx condition

I have a snippet call and I need to set a condition that if the album id is above 1000, then random sorting is applied, if below 1000 then by id. How do I get the album id when calling the Galery snippet?

<div id="gal_wrap" class="grid-gallery">    
 [[!If?         &subject=[[+id]]         &operator=>=         &operand=1000         &then=[[!Gallery?&thumbWidth=200&thumbHeight=150&thumbZoomCrop=1&imageWidth=1024&imageHeight=768&thumbTpl=GalThumb&sort=random]]         &else=[[!Gallery?&thumbWidth=200&thumbHeight=150&thumbZoomCrop=1&imageWidth=1024&imageHeight=768&thumbTpl=GalThumb&sort=rank]]]] 
</div>

my chunk Unfortunately it doesn’t work. I really need to solve this. Thanks to those who didn’t pass by.

My problem with get duration between 2 dates via moment

there are two dates with a difference of 20 minutes:

const a = moment.tz('Europe/Kiev');
const b = moment(item.sheduledAt);
console.log('my current time: ', a.format('DD MMMM, HH:mm')); // 08 June, 09:42
console.log('sheduled time: ', moment(item.sheduledAt).format('DD MMMM, HH:mm')) // 08 June, 10:00
console.log('diff: ', b.diff(a)) // 11832381
console.log('dur: ', moment.duration(b.diff(a)).asHours()) // 3.2867725

If you do not specify the time zone, then my time is shown incorrectly (according to the real server, it is 3 hours less). But after all, I’m just comparing 2 dates, which, when using format () above, show a difference of 20 minutes, where does 3 hours come from and how to remove them?

Parsing response returned by mediawiki api

PS – Scroll down to the bold italic thing for my question; everything else is context

The program is pretty simple (which makes how long I’ve struggled with every aspect of it even more embarrassing) ; html form takes an input from the user; queries the media wiki api using that input as the search query, gets the response.

I’ve gotten this much to work, & I can render the whole Json object media wiki returns.

enter image description here

From here I can access the value for the “pages” key.

enter image description here

enter image description here

But this is not easily readable, so I need to figure out how to index each of the keys separately, store those values in some JS object, & then I can display things in a normal way.

However this is proving more difficult than I’d have thought. Below are a bunch of things I tried. Any ideas on both how to parse this Json object & why the below things failed?

Things that did not work

this.answer = data.pages.excerpt
this.answer = data.pages
this.ans_spec = this.answer.excerpt

Both of the above resulted in “benign failures” where this.answer / this.ans_spec were undefined

this.answer = JSON.parse(data.pages)
this.answer = data.pages
this.ans_spec = JSON.parse(this.answer)

These properly caused the JS block to fail & go to the catch block

Create an array of objects separating what is text and what is markup

From an HTML code, I’ve to make an array of objects separating what is text and what is markup, like this way:

[
    {"text": "A "},
    {"markup": "<b>"},
    {"text": "test"},
    {"markup": "</b>"}
]

The HTML code that I’m using is this one:

<h2 id="mcetoc_1h1m1ll27l">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at tincidunt lectus.<a href="https://www.sadasdas.es" aria-invalid="true">tr</a><a title="titulo" href="https://www.sadasdas.es" aria-invalid="true">adsf afjdasi k</a><a title="titlee" href="https://www.sadasdas.es" aria-invalid="true">asdsssssssssssss</a><a href="https://www.sadasdas.es" aria-invalid="true">s</a></p>
<p><a href="https://www.sadasdas.es" aria-invalid="true">Lorem Ipsum</a></p>

To avoid the using of RegEx, first I create an array with all the nodes and then I loop over the nodes, looking what is an Element and what is a text node.

Currently I’m stuck with closing tags when an element node has child text nodes followed element nodes (and I’m not sure if I’m overcomplicating things):

<p>Lorem ipsum dolor sit...<a href="..." aria-invalid="true">tr</a><a title="..." href="..." aria-invalid="true">...</a><a title="..." href="..." aria-invalid="true">...</a><a href="..." aria-invalid="true">...</a></p>

So from this paragraph, my object looks so:

{markup: '<p>'}
{text: 'Lorem ipsum dolor sit...'}
{markup: '</p>'}
{markup: '<a>'}
//...

As you can see the close tag appears after the text node. I’ve managed it for element nodes followed by other element nodes, but this case still escapes me.

This is what I’ve done so far (codepen):

const obj = {
    annotation: []
};

const nodelist = (() => {
    const res = [];
    const tw = document.createTreeWalker(document.body);

    while (tw.nextNode()) {
        res.push(tw.currentNode)
    }

    return res;
})();

console.log(nodelist);

const nodeHasParents = (node) => node.parentNode.nodeName !== 'BODY';
const isTextNode = (node) => node.nodeType === Node.TEXT_NODE;
const isElementNode = (node) => node.nodeType === Node.ELEMENT_NODE;

const GetNextNodeElements = (i) => {
    let n = i + 1;
    let res = [];

    while (nodelist[n] && isElementNode(nodelist[n])) {
        res.push(nodelist[n]);
        n++;
    }

    return res;
}

const GetNextTextNode = (i) => {
    let n = i + 1;

    for (let n = i; n < nodelist.length; n++) {
        if (isTextNode(nodelist[n])) return nodelist[n];
    }
}


for (let i = 0; i < nodelist.length; i++) {
    let node = nodelist[i];
    let opentags = '';
    let closetags = '';

    if (isTextNode(node) && !nodeHasParents(node)) {
        obj.annotation.push({"text": node.textContent});
    }
    else if (isElementNode(node)) {
        opentags += `<${node.nodeName.toLowerCase()}>`;

        const currentNode = node;
        const nextNodeElements = GetNextNodeElements(i);

        if (nextNodeElements) {
            nextNodeElements.forEach(node => opentags += node.outerHTML.replace(node.textContent, '').replace(`</${node.nodeName.toLowerCase()}>`, ''));
            nextNodeElements.reverse();
            nextNodeElements.forEach(node => closetags += `</${node.nodeName.toLowerCase()}>`);

            i = i + nextNodeElements.length;
            node = nodelist[i];
        }

        if (!!closetags.length) {
            closetags = `</${currentNode.nodeName.toLowerCase()}>` + closetags;
        }
        else closetags += `</${currentNode.nodeName.toLowerCase()}>`

        obj.annotation.push({"markup": opentags});
        obj.annotation.push({"text": GetNextTextNode(i)?.textContent});
        obj.annotation.push({"markup": closetags});
    }
}

console.log(obj.annotation);

Effective way to display different contents in the same style of accordion in React?

what is an effective way to display different contents in the multiple accordions?
enter image description here
This is what I am doing in my project, and obviously shipping information and delivery options would contain different textboxs, labels, and input boxes.

As of now, I am hardcoding every label, input box, textbox for the different accordions, but I don’t think this is very smart and effective. Hardcoing makes my code very long for this one page. Below is a snippet of how I am hardcoding everything.
Or should I simply divide the different accordions into different react classes to make the code shorter.

<div className="dropdown-header" onClick={toggle}>
                                <h4 className="dropdown-text">Shipping Information</h4>
                                <span className="dropdown-selection">{selected ? '-' : '+'}</span>
                            </div>
                            {selected && (<div className="wrapper">
                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="info-group mb-3">
                                            <label>First name</label>
                                            <input type="text" className="info-input" name="firstname" />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="info-group mb-3">
                                            <label>Last name</label>
                                            <input type="text" className="info-input" name="firstname" />
                                        </div>

RequireActual for a manual mock

Searched everywhere, but couldn’t find.

I’m mocking axios in a manual mock __mocks__/axios.js:

let mockAxios = jest.genMockFromModule('axios')
// mockAxios = jest.requireActual('axios')

export default mockAxios

But sometimes I want to use the actual axios implementation (like what the commented out line does).

In my test axios is not used directly. So I tried to undo manual mock for that test suite:

test('200 response', async () => {
    jest.mock("axios", () => jest.requireActual("axios"))
    const response = await getContent('SomeID')
    expect(response.id).toEqual('SomeID');
  })

This doesn’t seem to change anything and the test fails because axios.get doesn’t return anything useful.

Is there a way to have a test, or a test file where manual mock is not used at all?

How to Minimize variable names but keep line breaks on Webpack

I am looking a way to minimize the variables and stuff but keep line breaks so the codes are more debugable in my production envirenmnet.

Setting minimize: false will keep original file names. I am working with some Lamda function. So reducing size was expected to increase the invocation time of my fucntions.
Adding source maps is expensive on the bundle size. If I could preserve line breaks and introduce a cheap source map, I hope it will reduce overall build size.

**
I am using extend to use a base cofig. The attched one is the base config I currently use.**

const path = require('path');

module.exports = {

  target: 'node',
  mode: 'production',
  resolve: {
    extensions: ['.ts', '.js'],
  },

  entry: handlers.reduce(function (obj, el) {
    obj[(path.parse(el).dir+"/"+path.parse(el).name).replace( /^(./)?[^/]+//,"")] = el;
    return obj;
  }, {}),

  output: {
    path: output_dir,
    filename: "[name].js",
    clean: true,

  },
  module: {
    rules: [
      {
        test: /.ts$/,

        use: [
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
            },
          },
        ],
        exclude: /node_modules/,
      },
    ],
  },
  optimization: {
    minimize: false,
    splitChunks: {
      chunks: 'all', // Split and share code among entries
    },
  },

};

I tried full source-maps and minimize disable so far, Any other suggetions.

differentiating browsing sessions between child tabs in chrome extension

I am trying to write a feature in my chrome extension that behaves like the SessionBox or MultiLogin chrome extensions. My main stump at the moment is differentiating cookies between the different child tabs such that they maintain their own individual sessions. When session cookies are updated by some interaction with a website on one tab, that is propagated to other tabs accessing the same website, due to the shared cookie store.

I have tried a few things.

  1. Having a main child tab array in the extension page that houses each tab object by its id, storing cookies associated with that tab’s current url. I am having trouble though differentiating site cookie update events between tabs on the same website though, as these updates are to the whole browser’s cookie store and not tab based.

  2. Utilizing chrome profiles, as having several child windows, each with a different chrome profile assigned to it, would accomplish the goal. The issue I’m having though is programmatically creating these chrome profiles. This was possible at one point, but was removed from chrome’s api, and the only way for this method to work would be having the user manually create chrome profiles. I want this to be completely seamless, with no more user interaction than necessary.

  3. Utilizing incognito child windows. Originally, I thought that each incognito window was its own browsing session with unique cookies from other incognito windows accessing the same webpage. Unfortunately, incognito windows all share the same cookies with each other. So incognito doesn’t actually isolate the window from all others, just from windows running in non incognito mode.

  4. I also looked into sandboxing, but that just outright didn’t seem the way to go.

So far, it looks like further implementation of option 1 would be the best way to go, but I am a bit stumped on that. Secondarily, option 2 could potentially work, but is not ideal.

Fastify cookie setup not working from subdomain

I’ve scoured the internet for a while, but haven’t been able to find out what I might be doing wrong.
I’ve a fastify server which is hosted on a subdomain: https://api.example.com

The UI is served via CloudFlare pages on the domain https://example.com and it’s a react-app.

Now I am calling the /authenticate endpoint in my backend via the fetch in the UI as:

 const requestOptions: RequestInit = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      redirect: "follow",
      referrerPolicy: "no-referrer",
      body: JSON.stringify({ message })
    };

return fetch(`${SERVER_URI}/authenticate`, requestOptions)
  .then(response => response.json())
  .then(result => console.log({ result }));

On the backend I am using the following setup:

 // Setup the CORS package
 await fastify.register(require('@fastify/cors'), {
    origin: /example.com$/,
    methods: ['GET', 'PUT', 'POST', 'DELETE']
  });


// Cookies Manager
fastify.register(require('@fastify/cookie'), {
    secret: 'someSecret'
});

When the /authenticate endpoint is called, it goes to a method which should set the cookie in the browser by running the following code:

AuthController.js:
...

res
  .setCookie('__auth', token, {
    domain: '.example.com',
    path: '/',
    signed: true,
    httpOnly: true,
    secure: true,
    sameSite: 'Lax'
  })
  .send({ authenticated: true, meta: {} });
  • I tried to add credentials: 'include' in the fetch call from the UI, that didn’t help.
  • I read about the different properties and headers that are available, but I am definitely missing something which has lead me to stackoverflow.

Expectation:

  • Cookie to be set in the browser.

Image created through html2canvas and uploaded to firebase storage has size of 0KB

I am trying to create an image of a div using html2canvas and upload to firebase storage. Every bit of the code works fine apart from the fact that the uploaded image has 0 kb size. Looks like the canvas element is not converted ultimately to an image. Here is the div and next is the code to upload

<div id="refit" style="margin: 3%; border: solid; border-radius: 4px; border-width: 3px;">
    <p style="margin-right: 2%; margin-left: 2%; "><u>Complaint/Issues:</u></p>
</div>

The script to convert this to an image and upload is as follows, The variable filename has been defined:

html2canvas(document.getElementById("refit")).then(function(canvas) {
                        var screenshot = canvas.toDataURL();
                        var storageRef = firebase.storage().ref();
                        var imagesRef = storageRef.child('Images/'+filename+'.jpg');
                        imagesRef.putString(screenshot,'data_url',{contentType:'image/jpg'}).then((snapshot) => {
                            snapshot.ref.getDownloadURL().then(function(downloadURL) {
                                firebase.database().ref('Somewhere/' + filename).update({ Something1: downloadURL, Something2: "Complete" },function(error){
                                    if (error) {
                                                alert("Network Error: Try again");
                                                
                                            } else {
                                                
                                                alert(" Submitted")
                                              
                                            }
                                })
                            })
                            
                        });
                    });

javascript design pattern Music Streaming Service

Design for a Music Streaming Service

Use the Strategy pattern to handle various music formats, such as Mp3 and Wav.
Implement the Observer pattern to monitor the music playback status.
Define a Subject interface to update the Ui whenever there are any changes. Apply the Factory pattern to create objects required for music playback. For example, when playing Mp3 format music, create an Mp3 Decoder object, and for Wav format music, create a WavDecoder object.
Utilize the Composite pattern to structure music playlists. Use the Facade pattern to determine whether the user is a member or not.

I’m not sure if this design I came up with is accurate. I’m a beginner and currently studying, but I don’t know the proper usage of design patterns or the correct order to apply them. Could you show me a simple UML diagram or help me improve the part I designed? Also, please guide me on the appropriate sequence for using design patterns.

I felt like I used multiple patterns, but I had the sense of designing in order to use design patterns, and I’m not sure about the design for the music streaming service

esbuild hybrid plugin to bundle multiple files iife and single esm bundle

There is a project SlickGrid that have multiple files that are all written as iife (it was originally built with jQuery namespace). Most files are optional and the user can choose which feature they are interested (ie slick.contextmenu.js, slick.headermenu.js, …) by loading whichever file(s) and every time they do it simply extends the Slick object on the window object.

I’d like to keep the iife for the users who still want to use standalone <script> loading but also want to provide ESM in a separate build folder. I think that I can achieve this with esbuild by writing an esbuild plugin with onResolve. I manage to make it work but it’s not the most elegant, I’d like help to find a better solution

import {
  Event as SlickEvents,
  EventData as SlickEventData,
  EditorLock as SlickEditorLock,
  Utils as SlickUtils,
} from './slick.core.js';
import { Draggable as SlickDraggable, MouseWheel as SlickMouseWheel, Resizable as SlickResizable } from './slick.interactions.js';

// I would like to avoid having the write the following lines
// for iife, pull from window.Slick object but for ESM use SlickX
const SlickEvent = window.Slick ? Slick.Event : SlickEvents;
const EventData = window.Slick ? Slick.EventData : SlickEventData;
const EditorLock = window.Slick ? Slick.EditorLock : SlickEditorLock;
const Utils = window.Slick ? Slick.Utils : SlickUtils;
const Draggable = window.Slick ? Slick.Draggable : SlickDraggable;
const MouseWheel = window.Slick ? Slick.MouseWheel : SlickMouseWheel;
const Resizable = window.Slick ? Slick.Resizable : SlickResizable;

// ...

// use the code
const options = Utils.extend(true, {}, defaults, options);

So I wrote a custom plugin that will use either window.Slick for iife when found OR will use the named import for ESM. Running a build for ESM is roughly the same but without using the plugin since we want to bundle everything into 1 file. However one thing to note is that for iife, we’ll still build every single into separate files (I still use bundle for the import but they are removed by the plugin), but for ESM we bundle everything into a single file and let tree shaking do the rest for ESM users.

import { build } from 'esbuild';

const myPlugin = {
    name: 'my-plugin',
    setup(build) {
      build.onResolve({ filter: /..(js|ts)$/ }, args => {
        if (args.kind !== 'entry-point') {
          return { path: args.path + '.js', namespace: 'import-ns' }
        }
      })

      build.onLoad({ filter: /.*/, namespace: 'import-ns' }, (args) => {
        return {
          contents: `// do nothing`,
          loader: 'js',
        };
      })
    }
};

build({
    entryPoints: ['slick.grid.js'],
    color: true,
    bundle: true,
    minify: false,
    target: 'es2015',
    sourcemap: false,
    logLevel: 'error',

    format: 'iife',
    // globalName: 'Slick',
    outfile: 'dist/iife/slick.grid.js',
    plugins: [myPlugin],
});

So this approach seems to work but is not very elegant, ideally it would be great if I could get the named imports and replace them directly in the code somehow and avoid having to write all these extra lines (ie: const SlickEvent = window.Slick ? Slick.Event : SlickEvents;)