Home > Blockchain >  Importing javascript class using type=module
Importing javascript class using type=module

Time:05-25

I want to export a class to another js file, but i cant see any output on the console on my browser? i have been following the steps of this tutorial aswell as an other tutorial: https://www.youtube.com/watch?v=cRHQNNcYf6s&t=190s and they show something similar to the code i have written. I told the browser that im using modules with type="module" aswell.

Im sorry if i missed something but the posts i can find here: How do I include a JavaScript file in another JavaScript file? deals with complicated scenarios and functions, i just need to import a Class

class 1:

import Rectangle from "./class2.js";

const rect = new Rectangle(100, 100);

rect.printHeight();

class 2:

export default class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  printHeight() {
    console.log(this.height);
  }
}

i import the script like this

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

CodePudding user response:

Change this:

import Rectangle from "./class2";

... to this:

import Rectangle from "./class2.js";

The problem is that the browser can't resolve the path to the file if you just give it the name - you need the extension as well (and it probably throws a 404 about that). Since you're not using a bundler or any other form of pre-processing, nothing would take care of that if you don't.

  • Related