developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.04k stars 362 forks source link

Get imports from window #924

Closed MikeDombo closed 2 years ago

MikeDombo commented 2 years ago

Hello there, I'm trying to use microbundle to build a plugin for an existing react-based website. On my main react site, I'm exporting common libraries into the window so that my plugin can use it without bundling its own copies of the UI framework and things like that.

I've tried everything I can think of with alias, define, global, external, without much luck.

When I use --globals @awsui/components-react=window.awsui --format iife, this does do nearly what I'd expect by replacing the import with a lookup in window.awsui. However, the iife format won't work for me; modern format would be preferred.

Command is microbundle --compress --format modern --jsxFragment h.Fragment --jsx h.createElement TSX looks like

import awsui from "@awsui/components-react"

export default function (props: any) {
    return (
        <awsui.Header>
            {props.name}
        </awsui.Header>)
}

I would expect that there should be a way for me to tell microbundle that import awsui from "@awsui/components-react"=const awsui = window.awsui. I have tried writing a define option to do that, but babel keeps complaining about how import is used.

Any help would be much appreciated.

developit commented 2 years ago

Hi @MikeDombo - I think this should be possible by aliasing the modules to your own versions that export the desired window property:

build script:

microbundle -f modern --alias @awsui/components-react=./src/libs/awsui-components-react.js

file: src/libs/awsui-components-react.js

export default window.awsui;

example: src/index.js

import awsui from "@awsui/components-react"
// use awsui as if it were the library
MikeDombo commented 2 years ago

Aha, excellent!

That absolutely works great, thank you very much for your help.

developit commented 2 years ago

Great! Feel free to re-open this issue if you run into anything.