I’m working on a Next.js React application where I need to dynamically load and use a JavaScript file hosted on an external server (which I’m unable to modify). The script contains a React component that I need to integrate into my application.
When I load script dynamically, I keep encountering the following error in my console:
ReferenceError: exports is not defined:3:23)
This is beginning of the contents of the file externalfile
:
'use strict';
Object.defineProperty(exports, '__esModule', { value: true }); // error here
var React$1 = require('react');
var require$$1$1$1 = require('react-dom');
//...
To load the file, I use a hook shown below:
import { useEffect } from 'react';
const useScriptHook = (path: string): void => {
useEffect(() => {
const script = document.createElement('script');
script.src = `${window.location.origin}${path}`;
script.type = 'module';
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [path]);
};
export default useScriptHook;
Here is how I use it:
// components/HomePage.tsx
import React, { useEffect, useState } from 'react';
import useScriptHook from './use-script-hook';
interface MyComponentProps {
exclude?: boolean;
isWidget?: boolean;
color?: 'blue' | 'red';
}
type MyComponentType = React.FC<MyComponentProps>;
const HomePage: React.FC = () => {
const [MyComponent, setMyComponent] = useState<MyComponentType | null>(null);
useScriptHook('/api/static-assets/externalfile');
useEffect(() => {
if ((window as any).MyComponent) {
setMyComponent(() => (window as any).MyComponent);
}
}, []);
if (!MyComponent) {
return <div>Loading...</div>;
}
return (
<div>
<MyComponent exclude={true} isWidget={true} color="blue" />
</div>
);
};
export default HomePage;
How can I correctly load the script dynamically in a Next.js React application?
I also tried changing the script.type
to text/javascript
but with no success