es6 module loaded through url cannot access “useState” as it is undefined

I am building a React library using webpack, and the library builds correctly into an es6 module. We are then trying to host this module on a CDN so we can import it through a url instead of node_modules.

We then import it like this, and I get the correct component.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import('http://example.com/test.js').then(m => console.log(m.default));
</code>
<code>import('http://example.com/test.js').then(m => console.log(m.default)); </code>
import('http://example.com/test.js').then(m => console.log(m.default));

The library has this test component which works when I display it within the application:

This is exported through the library:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export default ({ name }) => {
return <div>{name}</div>;
};
</code>
<code>export default ({ name }) => { return <div>{name}</div>; }; </code>
export default ({ name }) => {
  return <div>{name}</div>;
};

The app then implements it like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export default () => {
const [Test, setTest] = useState();
useEffect(() => {
import('http://example.com/test.js').then(m => setTest(m.default));
}, []);
return <Test name="Joe" />;
}
</code>
<code>export default () => { const [Test, setTest] = useState(); useEffect(() => { import('http://example.com/test.js').then(m => setTest(m.default)); }, []); return <Test name="Joe" />; } </code>
export default () => {
  const [Test, setTest] = useState();

  useEffect(() => {
    import('http://example.com/test.js').then(m => setTest(m.default));
  }, []);

  return <Test name="Joe" />;
}

However, when I add useState, like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { useState } from 'react';
export default ({ name }) => {
const [displayName] = useState('Billy');
return <div>{displayName}</div>;
};
</code>
<code>import { useState } from 'react'; export default ({ name }) => { const [displayName] = useState('Billy'); return <div>{displayName}</div>; }; </code>
import { useState } from 'react';
export default ({ name }) => {
  const [displayName] = useState('Billy');
  return <div>{displayName}</div>;
};

I then get these two errors:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>test.tsx:12 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
</code>
<code>test.tsx:12 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app </code>
test.tsx:12 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>react.development.js:1623 Uncaught TypeError: Cannot read properties of null (reading 'useState')
at useState (react.development.js:1623:21)
at default (test.tsx:12:76)
</code>
<code>react.development.js:1623 Uncaught TypeError: Cannot read properties of null (reading 'useState') at useState (react.development.js:1623:21) at default (test.tsx:12:76) </code>
react.development.js:1623 Uncaught TypeError: Cannot read properties of null (reading 'useState')
    at useState (react.development.js:1623:21)
    at default (test.tsx:12:76)

my webpack looks like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export default {
// module rules and entry snipped out
output: {
path: path.resolve(__dirname, '../../dist'),
filename: 'test.js',
library: {
type: 'module',
},
},
experiments: {
outputModule: true,
}
}
</code>
<code>export default { // module rules and entry snipped out output: { path: path.resolve(__dirname, '../../dist'), filename: 'test.js', library: { type: 'module', }, }, experiments: { outputModule: true, } } </code>
export default {
  // module rules and entry snipped out

  output: {
    path: path.resolve(__dirname, '../../dist'),
    filename: 'test.js',
    library: {
      type: 'module',
    },
  },
  experiments: {
    outputModule: true,
  }
}

When I add externals: ['react', 'react-dom'] to webpack, I then get this error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".
</code>
<code>Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../". </code>
Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

Why isn’t my library able to use useState when loaded via a URL?

So, to get this to work, I needed to create a child app within the current application, so from the component that comes from a url sorce I also exported the react and react-dom so the parent application could create it:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// index.jsx
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
const _Component = ({name}) => {
const [name] = useState(name ?? 'Billy');
return <div>{name}</div>;
}
// I converted this into a reusable function:
const div = document.createElement('div');
const root = reactDOM.createRoot(div);
const info = {
component,
react,
renderer: root,
domElement: div,
};
export info as RemoteComponent;
</code>
<code>// index.jsx import React, { useState } from 'react'; import ReactDOM from 'react-dom/client'; const _Component = ({name}) => { const [name] = useState(name ?? 'Billy'); return <div>{name}</div>; } // I converted this into a reusable function: const div = document.createElement('div'); const root = reactDOM.createRoot(div); const info = { component, react, renderer: root, domElement: div, }; export info as RemoteComponent; </code>
// index.jsx
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

const _Component = ({name}) => {
  const [name] = useState(name ?? 'Billy');
  return <div>{name}</div>;
}

// I converted this into a reusable function:
const div = document.createElement('div');
const root = reactDOM.createRoot(div);

const info = {
  component,
  react,
  renderer: root,
  domElement: div,
};

export info as RemoteComponent;

Next, in the application I created a component that would bootstrap the data and display the internal application:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// widget.jsx
export const Widget = ({ widget, props }) => {
const [uuid] = useState(() => crypto.randomUUID());
const ref = useRef(null);
// If the widget changes, we need to re-render the new widget and append it to the DOM
useEffect(() => {
if (!widget || !ref.current) return;
widget.renderer.render(widget.react.createElement(widget.component, props));
ref.current.appendChild(widget.domElement);
}, [widget]);
// If the props change, we need to re-render the widget but not append it to the DOM
useEffect(() => {
if (!widget) return;
widget.renderer.render(widget.react.createElement(widget.component, props));
}, [props]);
return <div ref={ref} id={uuid}></div>;
};
</code>
<code>// widget.jsx export const Widget = ({ widget, props }) => { const [uuid] = useState(() => crypto.randomUUID()); const ref = useRef(null); // If the widget changes, we need to re-render the new widget and append it to the DOM useEffect(() => { if (!widget || !ref.current) return; widget.renderer.render(widget.react.createElement(widget.component, props)); ref.current.appendChild(widget.domElement); }, [widget]); // If the props change, we need to re-render the widget but not append it to the DOM useEffect(() => { if (!widget) return; widget.renderer.render(widget.react.createElement(widget.component, props)); }, [props]); return <div ref={ref} id={uuid}></div>; }; </code>
// widget.jsx
export const Widget = ({ widget, props }) => {
  const [uuid] = useState(() => crypto.randomUUID());
  const ref = useRef(null);

  // If the widget changes, we need to re-render the new widget and append it to the DOM
  useEffect(() => {
    if (!widget || !ref.current) return;
    widget.renderer.render(widget.react.createElement(widget.component, props));
    ref.current.appendChild(widget.domElement);
  }, [widget]);

  // If the props change, we need to re-render the widget but not append it to the DOM
  useEffect(() => {
    if (!widget) return;
    widget.renderer.render(widget.react.createElement(widget.component, props));
  }, [props]);

  return <div ref={ref} id={uuid}></div>;
};

Lastly, I load the component from the remote and and pass it to the Widget. The widget then creates an application as a child of the current application:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// app.jsx
export default function App() {
const [module, setModule] = useState({});
useEffect(() => {
const endpoint = 'http://example.com/library.js';
import(endpoint).then(setModule);
// This contains:
// {
// RemoteComponent: {domElement, renderer, react, component}
// }
}, []);
return (
<>
External Widget:
<Widget widget={module} props={{name: 'Joe'}} />
</>
);
}
</code>
<code>// app.jsx export default function App() { const [module, setModule] = useState({}); useEffect(() => { const endpoint = 'http://example.com/library.js'; import(endpoint).then(setModule); // This contains: // { // RemoteComponent: {domElement, renderer, react, component} // } }, []); return ( <> External Widget: <Widget widget={module} props={{name: 'Joe'}} /> </> ); } </code>
// app.jsx
export default function App() {
  const [module, setModule] = useState({});

  useEffect(() => {
    const endpoint = 'http://example.com/library.js';
    import(endpoint).then(setModule);
    // This contains:
    // {
    //   RemoteComponent: {domElement, renderer, react, component}
    // }
  }, []);

  return (
    <>
      External Widget:
      <Widget widget={module} props={{name: 'Joe'}} />
    </>
  );
}

Looks like you haven’t excluded React packages from your library

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>//webpack.config.js
externals: {
'react': 'react',
'react-dom' : 'reactDOM'
}
</code>
<code>//webpack.config.js externals: { 'react': 'react', 'react-dom' : 'reactDOM' } </code>
//webpack.config.js
externals: {
 'react': 'react', 
 'react-dom' : 'reactDOM'
}

7

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật