Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda