I have a class (module) in another js file in the same folder which looks like this.
class MessageModule{
constructor(){
}
sayHello(){
alert('Hello from msg');
}
}
module.exports = MessageModule;
However, I am not able to require it in the main js file.
let $ = require('jquery');
global.jQuery = $;
let bootstrap = require('bootstrap');
let messageModule = require('message');
messageModule.sayHello();
How should I go about exporting this, or any class?
Thank you.
You are exporting the class definition. You'll need to create an instance to reach any non-static method there. Static methods can be reached from the class object.
So, it's either:
class MessageModule{
constructor(){
}
static sayHello(){
alert('Hello from msg');
}
}
module.exports = MessageModule;
Or:
let $ = require('jquery');
global.jQuery = $;
let bootstrap = require('bootstrap');
let messageModule = require('message')();
messageModule.sayHello();
export class MessageModule {
constructor() {
}
sayHello() {
alert('hello from msg')
}
}
Call that class in another page:
<script>
import {Message} from "/scripts/message.js";
var message = new Message();
message.sayHello();
// or
//import {MessageModule} from "/scripts/message.js";
//var message = new MessageModule();
//message.sayHello();
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.