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

112
Vistas
How can I reference JavaScript classes from an external file?

For some reason my html page is not able to find a class I placed in another js file.

In the header I referenced the file

<script type="module" src="../class1.js"></script>

In a script tag in the HTML page I try to instantiate the class

let class1 = new class1();

The class1 is a child class of base class and they looks like

class baseClass {
    constructor() {      
    }
}

class class1 extends baseClass {
    constructor() {
        super(); 
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You've loaded your file as a module. That means top-level declarations aren't globals. Instead, you would export anything the module should export, and import it where you need it. Your code sample doesn't show you doing that (though it's possible you do an export somewhere you haven't shown).

Here's an example of how you might export those (note the export keyword):

export class baseClass {
    constructor() {      
    }
}

export class class1 extends baseClass {
    constructor() {
        super(); 
    }
}

And then in code that needs to use it:

import {class1} from "./class1.js";

// ...use it here...

Note that if you have a main entry point module, you don't need to include script elements for the things it imports. Just importing is sufficient.

For instance, if the class above is in class1.js and the code using it is in main.js, this HTML is all you need to load them:

<script src="./main.js" type="module"></script>

The action of loading main.js loads the modules it depends on.


Side note: You can use any naming convention in your code you want, but when sharing code with others, it's best to stick to the overwhelmingly-common naming convention that constructor functions (like class1) start with an upper case character (Class1).

about 4 years ago · Juan Pablo Isaza 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