Javascipt by Rasik Bihari Tiwari

How to import/export a class in Vanilla JavaScript (JS)

I’m using Vanilla JavaScript (JS). Now, I’m trying to leverage the concept of import/export class and module which came as part of ECMA-2015 (ECMA-6) release. Please see the code snippet below: rectangle.js:

export default class Rectangle < constructor(height, width) < this.height = height; this.width = width; >> 
import Rectangle from 'rectangle.js'; class MyHiFiRectangle extends Rectangle < constructor(height, width) < super(height,width); this.foo= "bar"; >> 

I’m trying to refer above mentioned JS files in an HTML page named test.html (Refer code snippet):

         

Then, I tried loading test.html in browser. The result is different on different browsers. On Google Chrome I get below error:

SyntaxError: export declarations may only appear at top level of a module SyntaxError: import declarations may only appear at top level of a module ReferenceError: MyHiFiRectangle is not defined[Learn More]

I tried reordering the JS files which are referred in the head tag of the HTML file but it had no impact. Note: To be clear again, I’m not using any transpilers like Babel. I’m trying to check the native support of export/import class and module constructs in Vanilla JS and how it works.

Remove and replace with . That fixes one problem. The other is that myHifiRectangle.js does not create a global variable (which you should stop using anyway). To get that, add window.MyHiFiRectangle = MyHiFiRectangle; at the end of myHifiRectangle.js .

4 Answers 4

I went through this and I’ve a solution with a third js file as module. rectangle.js will be same and myHifiRectangle.js file have only one modification.

import Rectangle from './rectangle.js'; export default class MyHiFiRectangle extends Rectangle < constructor(height, width) < super(height,width); this.foo= "bar"; >> 

Now, we need a third file which will be a module file, let say, script.js

import MyHiFiRectangle from './myHifiRectangle.js' var v = new MyHiFiRectangle(2,4); console.log(v.foo); 

Now, the third file, script.js should be made a module. More on modules here. I have all three files under modelJS folder.

Now, when you run, you should see ‘bar’ getting printed in the developer tool’s console tab.

Great! I wasn’t aware of this module attribute. May be Chrome hadn’t implemented it at the time of writing this question. Btw, I was able to achieve it using module attribute in my HTML file itself as mentioned my own answer. I didn’t require a separate script.js files to call my modules. I really appreciate you for putting effort on my old question. I learned something new today.

I’m also adding an answer after getting hint from curiou.netter’s answer in this thread.

I will point out the errors in precise sequential manner in the original code files. By the way, I was able to fix the issue without involving additional script.js file:

    While referring to JS modules, the script type should be module instead. I was referring to myHiFiRectancle.js like a regular JS file using src tag as:

src="https://stackoverflow.com/questions/44490627/Scripts/myHiFiRectangle.js" 

I also imported MyHiFiRectangle module. Here is how the head tag now looks in the test.html file after fixing this error:

     
import Rectangle from './rectangle.js'; export default class MyHiFiRectangle extends Rectangle < constructor(height, width) < super(height,width); this.foo= "bar"; >> 
import Rectangle from 'rectangle.js'; import MyHiFiRectangle from '/scripts/myHiFirectangle.js'; 

Uncaught TypeError: Failed to resolve module specifier «rectangle.js». Relative references must start with either «/», «./», or «../».

import Rectangle from './rectangle.js'; import MyHiFiRectangle from './scripts/myHiFirectangle.js'; 

Источник

Mastering JavaScript Classes: How to use and store them in external files

Learn how to properly use and store JavaScript classes in external files using Node.js and ES6 import/export statements. Improve organization and maintainability with best practices. Get started now.

  • Making the File a Module in Node.js
  • Exporting and Importing Classes
  • Where to Place your Javascript Code
  • Ensuring Correct Loading Order
  • Embedding JavaScript Files
  • ES6 Import and Export Statements
  • Examples of other simple JavaScript class code for external files
  • Conclusion
  • How to use a class in another file in JavaScript?
  • How to export a class in JavaScript?
  • How to write an external JavaScript file?
  • How to import JavaScript class in HTML?

JavaScript is an essential programming language for web development, and classes are a fundamental part of object-oriented programming (OOP) in JavaScript. Classes allow developers to create reusable code and structure their projects in a logical way. However, in some cases, it may be necessary to store classes in separate files. This guide will explain how to instantiate a JavaScript class in an external file.

Making the File a Module in Node.js

To use a class in a separate file, that file must be loaded as a module in Node.js. This can be done using the require function. The require function is a built-in Node.js function that allows you to load modules that are installed in your project.

Here’s how you can use require to load a class from an external file:

const MyClass = require('./MyClass.js'); 

In this example, we are loading the MyClass class from the MyClass.js file in the same directory. The ./ at the beginning of the file path tells Node.js to look in the current directory.

Exporting and Importing Classes

To use a class in another file, it must be exported from the original file and imported into the new file. This can be done using the module.exports and require statements.

Here’s how you can export a class from the original file:

class MyClass < // class definition >module.exports = MyClass; 

In this example, we define the MyClass class and then export it using the module.exports statement.

Here’s how you can import the MyClass class into another file:

const MyClass = require('./MyClass.js'); 

In this example, we use the require statement to load the MyClass class from the MyClass.js file in the same directory.

Where to Place your Javascript Code

In this video, you will learn -1. Where and how to write javascript code within the HTML Duration: 14:14

Ensuring Correct Loading Order

When using classes in external files, it is important to ensure that the class file is loaded before the file that references it. This can be done by making sure that the import statement is written after the class file is loaded.

Here’s an example of how to do this in an HTML file:

In this example, we load the MyClass.js file in the HTML file. We then reference the MyClass class in a separate JavaScript file:

import MyClass from './MyClass.js'; 

By importing the MyClass class after the MyClass.js file is loaded, we ensure that the class is available for use.

Embedding JavaScript Files

To increase speed, it is recommended to embed all JavaScript files into a single file. This can be done using tools such as Webpack or Browserify.

Here’s how you can import a class from an embedded JavaScript file:

import MyClass from './bundle.js'; 

In this example, we import the MyClass class from the bundle.js file, which contains all of the JavaScript code for our project.

ES6 Import and Export Statements

ES6 introduced the ability to use the export and import statements to share code between files. This allows for more flexibility in how classes are shared between files.

Here’s how you can export a class using the export statement:

export default class MyClass < // class definition >

In this example, we use the export statement to export the MyClass class.

Here’s how you can import the MyClass class using the import statement:

import MyClass from './MyClass.js'; 

In this example, we use the import statement to import the MyClass class from the MyClass.js file in the same directory.

Examples of other simple JavaScript class code for external files

In Javascript as proof, javascript class in external file code sample

class User < //. >module.exports = User 

Conclusion

JavaScript classes can be stored in external files using the require and module.exports statements in Node.js or the import and export statements in ES6. Best practices should be followed to ensure that external files are loaded in the correct order and to avoid common issues. Using external files can improve organization and maintainability, but can also come with potential security risks.

By following the guidelines outlined in this article, you can master JavaScript classes and use them effectively in your projects. With a solid understanding of classes and how to use them in external files, you can create more efficient and maintainable code.

Frequently Asked Questions — FAQs

How can I store JavaScript classes in separate files using Node.js?

To store JavaScript classes in external files using Node.js, you must first make the file a module by using the `require` function. Then, you can export the class from the original file and import it into a new file using the `module.exports` and `require` statements.

To ensure that external files are loaded in the correct order, it is important to load the class file before the file that references it. This can be done by making sure that the import statement is written after the class file is loaded.

Can I use ES6 import/export statements to share JavaScript classes between files?

Yes, ES6 introduced the ability to use the `export` and `import` statements to share code between files. This allows for more flexibility in how classes are shared between files.

What are some best practices for using external files with JavaScript classes?

Some best practices for using external files with JavaScript classes include ensuring correct loading order, embedding all JavaScript files into a single file using tools such as Webpack or Browserify, and following security protocols to avoid potential risks.

How can using external files improve organization and maintainability of JavaScript code?

Using external files can improve organization and maintainability of JavaScript code by keeping related classes and functions in separate files, making it easier to locate and modify code, and reducing the risk of errors caused by code duplication.

Are there any security risks associated with using external files for JavaScript classes?

Yes, using external files for JavaScript classes can come with potential security risks such as code injection and cross-site scripting (XSS) attacks. It is important to follow best practices and security protocols to mitigate these risks.

Источник

Including JavaScript class definition from another file in Node.js

Since Node.js version 14 it’s possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.

user.mjs (👈 extension is important)

export default class User <> 
import User from './user.mjs' let user = new User() 

what if, User had some input parameters, like module.exports = function User(data). Then the var user = new User(); whould have been changed to var user = new User(data);?

You don’t need to create the constant User in server.js. Change the last line of users.js into module.exports = new User(); This will create a new instance of User each time the module is required. Then you can simply require the module for each variable like this: let user = require(‘./user.js’); .

Using ES6, you can have user.js :

export default class User < constructor() < . >> 

And then use it in server.js

const User = require('./user.js').default; const user = new User(); 

i get an SyntaxError: Unexpected token export when i do as you described. i have node version v10.16.3

Modify your class definition to read like this:

exports.User = function (socket) < . >; 

Then rename the file to user.js . Assuming it’s in the root directory of your main script, you can include it like this:

var user = require('./user'); var someUser = new user.User(); 

That’s the quick and dirty version. Read about CommonJS Modules if you’d like to learn more.

Another way in addition to the ones provided here for ES6

module.exports = class TEST < constructor(size) < this.map = new MAp(); this.size = size; >get(key) < return this.map.get(key); >length() < return this.map.size; >> 
var TEST= require('./TEST'); var test = new TEST(1); 

If you append this to user.js :

then in server.js you can do:

var userFile = require('./user.js'); var User = userFile.User; 

then this would be enough in server.js :

To build upon Paul Rumkin answer(the first answer), you can use the ES Modules class with the .js extension and don’t have to use the .mjs extension.

To do that, make sure you have the package.json file. If you don’t have one, run the following command to create it:

Add «type»: «module» at the end of your the package.json file:

Create user.js file and export a class from it:

export default class User <> 

Import the class in server.js:

import User from './user.js' let user = new User() 

Источник

Читайте также:  How to create objects in javascript
Оцените статью