I am trying to develop a single TypeScript React component that I plan to release on NPM. I am using rollup to bundle my component into cjs, esm and iife.
I need to be able to load my component onto the browser locally to see it while I develop the react component. I am not using CRA.
The command I run to start the web server is "dev": "npm-run-all --parallel start watch"
which calls "start": "serve -s public -p 5000"
and "watch": "rollup -c -w"
I created an index.html
file that calls my dist/bundle.js
with the hope that I could see the component on screen. However, it does not show up. I was trying to interact with my component with a .window
call, and it says it doesn’t exist.
So I looked at the network tab, and for some reason its type is HTML. That is my hunch as to why this isn’t working.
Here is the relevant code of my rollup.config.mjs
{
input: 'src/component/index.tsx',
output: {
name: 'ThreeWaySwitch',
file: 'dist/bundle.js',
format: 'iife',
sourcemap: true,
globals: { react: 'React', 'react-dom': 'ReactDOM' }
},
plugins: [
external(),
resolve(),
commonjs(),
typescript({ tsconfig: './tsconfig.json' }),
babel({
exclude: 'node_modules/**',
presets: ['@babel/preset-env', '@babel/preset-react'],
babelHelpers: 'bundled'
})
]
},
my public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Three Way Switch</title>
<!-- Include React and ReactDOM scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.development.js"></script>
</head>
<body>
<div id="root"></div>
<script src="../dist/bundle.js"></script>
<script>
const React = window.React;
const ReactDOM = window.ReactDOM;
// Wait for the component to be available from bundle.js
//for some reason three way switch isnt loading figure this out later
function renderComponent() {
if (typeof window.ThreeWaySwitch !== 'undefined') {
const ThreeWaySwitch = window.ThreeWaySwitch;
const labels = [
{ title: 'Option 1', value: 'left' },
{ title: 'Option 2', value: 'center' },
{ title: 'Option 3', value: 'right' }
];
ReactDOM.render(
React.createElement(ThreeWaySwitch, { labels: labels, disabled: false }),
document.getElementById('root')
);
} else {
console.error('Failed to load ThreeWaySwitch component.');
}
}
// Call renderComponent once the script is loaded
window.onload = renderComponent;
</script>
</body>
</html>
In the console window.React and window.ReactDOM return values, but window.ThreeWaySwitch doesn’t, and my else statement gets hit.