ArticleZip > How To Do Import Export A Class In Vanilla Javascript Js

How To Do Import Export A Class In Vanilla Javascript Js

Importing and exporting classes in Vanilla JavaScript is a powerful feature that allows you to organize your code more effectively and improve reusability. In this article, we will walk you through how to import and export classes in JavaScript with ease.

To get started, let's first understand how to export a class in JavaScript. When you create a class that you want to use in another file, you need to export it using the `export` keyword. Here's an example:

Javascript

// MyClass.js
export class MyClass {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

In the above code snippet, we have a class `MyClass` with a constructor and a method `sayHello`. By using `export`, we make this class accessible for import in other files.

Next, let's look at how to import the exported class into another file. To import a class, you use the `import` keyword followed by the name you used when exporting the class. Here's an example:

Javascript

// index.js
import { MyClass } from './MyClass.js';

const myObject = new MyClass('Alice');
myObject.sayHello();

In this example, we import the `MyClass` from the `MyClass.js` file and create an instance of the class. We then call the `sayHello` method on the instance, which will log "Hello, Alice!" to the console.

It's important to note that when importing and exporting classes in JavaScript, you need to specify the file extension (e.g., `.js`) for both the export and import statements. This helps the JavaScript engine to locate the correct file containing the class definition.

Additionally, you can also use the `default` keyword when exporting a class. This allows you to import the class without using curly braces. Here's how you can export and import a class using `default`:

Javascript

// MyDefaultClass.js
export default class MyDefaultClass {
  constructor() {
    console.log('Default Class instantiated');
  }
}

Javascript

// index.js
import MyDefaultClass from './MyDefaultClass.js';

const myDefaultObject = new MyDefaultClass();

In this example, we export the class `MyDefaultClass` using the `default` keyword and import it without curly braces in the `index.js` file.

By mastering the concepts of importing and exporting classes in Vanilla JavaScript, you can modularize your code and make it more maintainable. Experiment with these techniques in your projects to see the benefits firsthand. Happy coding!

×