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

110
Views
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 answers
Answer question

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 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!