简体   繁体   中英

Node JS: how to get access to ES6 class from another file?

Good day. I have 3 different files: app.js, task.js, index.html.

task.js - model of the task. It contains:

module.exports = class Task {
    constructor(author, header, priority, description, id) {
        //...
    }

    //...
};

app.js contains:

const Task = require("./js/models/Task");

I can create an instance of the task in app.js:

const task = new Task();

But when i try to attach task.js to index.html:

<script src="../js/models/Task.js" type="text/javascript"></script>

and run the server, i get an error:

ReferenceError: module is not defined   
module.exports = class Task

How i can create an instance of the Task?

The CommonJS module syntax is only supported natively by Node. It's not supported natively by the browser. You can use Browserify to bundle up CommonJS modules to a format your browser understands, should you want the syntax to work on the browser.

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