Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda