Say I have a file class.js
:
class myClass { constructor(arg){ console.log(arg); } }
And I wanted to use the myClass
class in another file. How would I go about this?
I've tried:var myClass = require('./class.js');
But it didn't work.
I've looked at module.exports
but haven't found an example that works for es6 classes.
Finally es6 classes have landed in Node.
The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error.
Either do
module.exports = class MyClass { constructor(arg){ console.log(arg); } };
and import with
var a = require("./class.js"); new a("fooBar");
or use the newish syntax (may require you to babelify your code first)
export class MyClass { constructor(arg){ console.log(arg); } };
and import with
import {myClass} from "./class.js";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With