Reputation: 7472
// test.js
class Test
export Test
// index.js
import {Test} from './test'
This results in a syntax error with Unexpected token
. What is the correct way to export a predefined class?
EDIT: It is required that the class definition is separate from the export.
Upvotes: 10
Views: 8824
Reputation: 135396
To elaborate
export {A, B};
Is the same as
// old style
exports.A = A;
exports.B = B;
Which require an import
like
import {A,B} from "./somefile";
Which is the same as
// old style
var A = require("./somefile").A;
var B = require("./somefile").B;
However, you also could've also used export default
class Test {
constructor() {
console.log("it's works");
}
}
export default Test;
Which is the same as
// old style
exports["default"] = Test;
module.exports = exports["default"];
Then import it like
import Test from "./test";
new Test();
// "it works!";
Which is the same as
// old style
var Test = require("./test");
new Test();
// "it works!";
Upvotes: 8
Reputation: 2476
You can both do
class MyClass { }
export { MyClass }
or
export default MyClass // no semicolon
And then
import { MyClass as Stuff } from './modulepath';
or (if you declare export default)
import { default as MyClass } from './modulepath';
or simply
import MyClass from './modulepath';
Upvotes: 1
Reputation: 4446
You just need to change your test.js:
export class Test
Then
import {Test} from './test'
Upvotes: 0