1

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(); 
    }
}
3
  • How did you know that didnt work Commented Oct 20, 2021 at 18:15
  • 1
    You're not doing any importing or exporting which is what I would expect from a module. Commented Oct 20, 2021 at 18:16
  • 1
    @Andy scratch that, i just saw the "module" Commented Oct 20, 2021 at 18:16

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.