Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot read properties of null (reading 'useState') in iife lib #195

Closed
longilineo opened this issue Apr 1, 2024 · 1 comment
Closed

Comments

@longilineo
Copy link

longilineo commented Apr 1, 2024

vite.config.js

`import { defineConfig } from 'vite'
import { resolve } from 'path';
import react from '@vitejs/plugin-react-swc'

export default defineConfig({
define: {
'process.env': process.env
},
plugins: [react()],
build: {
sourcemap: true,
lib: {
entry: resolve(__dirname, 'lib/main.js'),
name: 'Mylib',
fileName: 'my-lib',
formats: ['iife']
},
},
})
`

lib/main.js

`import ReactDOM from 'react-dom/client'
import DrawerShowdown from "../src/DrawerShowdown"

export {
ReactDOM,
DrawerShowdown,
};`

Here is the component using 'useState'.

`import React, {useState} from 'react';

function DrawerShowdown() {
const [open, setOpen] = useState(false);

const toggleDrawer = (newOpen) => () => {
setOpen(newOpen);
};
...
`

Here is how I'm using this component:

            <div id="testreact"></div>
            <script src="my-lib.iife.js" />
            <script>
                MyLib.ReactDOM.createRoot(document.getElementById('testreact')).render(
                    MyLib.DrawerShowdown(),
                )
            </script>

If I remove useState from component it works as expected. The host project doesn't include react / react-dom so excluding them from bundle causes 'ReactDOM not defined' error.

@ArnaudBarre
Copy link
Member

Hey I forgot to add the need reproduction back then. Please provide a link to a repro in stackblitz so I can have a look

@ArnaudBarre ArnaudBarre closed this as not planned Won't fix, can't repro, duplicate, stale May 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants