Question:
When using Node.js
to import a serious class:
var Comprobador = require('./comprobador.js');
let comprobador=new Comprobador();
But in pure JavaScript on the client side what would it be like?
Answer:
In previous versions of JavaScript there was no way to include JavaScript
either by import
or require
.
Newer versions added import and export functionality to meet this point making use of standards like ES6 Modules , just keep in mind that currently, browser support for ES6
modules is not very good. To improve this, compilation or transpilation tools are used, which would be the most recommended.
With these tools it will be simpler and the syntax will be similar in some cases the same as the one used in Node
A base example for creating a class in one file and importing them into another. We create the Person class with a parameter in the constructor and a method
class Persona {
constructor(nombre) {
this.nombre = nombre;
}
saludar() {
return "Hola mi nombre es " + this.nombre;
}
}
export default Persona;
or simply.
export default class Persona {
constructor(nombre) {
this.nombre = nombre;
}
saludar() {
return "Hola mi nombre es " + this.nombre;
}
}
To call in the other file it will be enough as in your example
import Persona from "./Persona"; // Ruta correcta al archivo Js
let per= new Persona("Stack");
console.log(per.saludar());