Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Import dynamically external JavaScript module in React component

I have a Javascript module that looks like:

export function test() {
  return "Hello";
}

I need to import this script in React. This is what I tried:

  1. Defined a useScript method:
const useScript = ({ onLoad } : { onLoad: any }) => {
  useEffect(() => {
    const script = document.createElement('script');
    script.type = "module";
    script.src = "remote/path/to/test.js";
    script.onload = onLoad
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    }
  }, [onLoad]);
};
  1. Use it to load the script in React component:
const getTest = () => {
    window["test"]();
 }

useScript({
  onLoad: getTest
});

This gives me the error:

window.test is not a function

Note, that if I remove export from the JS file then it works. However, I need the export and not sure why adding export breaks it. Any clues?

Edit: Tried using import like this:

  useEffect(() => {
      const getTest = async function() {
        const uri = "https://remote/path/to/test.js";
        const { test } = await import(uri);
        console.log(test());
      }
      getTest();
    }
  }, []);

However, this gives the error:

Unhandled Rejection (Error): Cannot find module
almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

import React, { lazy, Suspense } from 'react';
import ExternalComponent from './ExternalComponent';  
// Importa ExternalComponent utilizando import() para cargarlo dinámicamente
const ExternalComponent = lazy(() => import('./ExternalComponent'));

function App() {
  return (
    <div>
      <h1>Aplicación con Carga Diferida</h1>
      <Suspense fallback={<div>Cargando...</div>}>
        <ExternalComponent />
      </Suspense>
    </div>
  );
}

export default App;



almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!