简体   繁体   中英

How to set class and export correctly in javascript and Node.js

I use node.js and I loaded js file in ejs

When main.js will be loaded,script will be functioned. while then,

    <script type="text/javascript" src=../javascripts/functions.js></script>
    <script type="text/javascript" src=../javascripts/quiz.js></script>
    <script type="text/javascript" src=../javascripts/main.js></script>

I have some issues like Uncaught ReferenceError: module is not defined in quiz.js

How to set export correctly?

I'd like to export quiz class correctly. Is this issue comes from ES6 ?

If someone has opinion,please let me know.

Thanks

quiz.js

class Quiz {
  
    constructor(quizData){
        this._quizzes = quizData.results;
        this._correctAnswersNum = 0;
    }
 
    getQuestion(index){
        return this._quizzes[index-1].question;
    }
    
}

module.exports = Quiz;

main.js


(()=>{
      const url = "/quiz-data";

      fetch(url)
      .then(response => response.json())
      .then(json => {
        const quiz = new Quiz(json);
        console.log("json",json);
        console.log("quiz",quiz);
        displayQuiz(quiz,1);
      });
})();

Client-side JS does not support Node.js style CommonJS modules .


If you want to use modules client-side, then write ES6 modules .


If you just want to use shared globals, then write the code as you have it now only without the module.exports line.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM