Export class after definition in ES6

// 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.

+3


source to share


4 answers


To develop

export {A, B};

      

Same as

// old style
exports.A = A;
exports.B = B;

      

What is required import

as

import {A,B} from "./somefile";

      

Same as

// old style
var A = require("./somefile").A;
var B = require("./somefile").B;

      




However, you could also use export default

class Test {
  constructor() {
    console.log("it works");
  }
}

export default Test;

      

Same as

// old style
exports["default"] = Test;
module.exports = exports["default"];

      

Then import it like

import Test from "./test";
new Test();
// "it works!";

      

Same as

// old style
var Test = require("./test");
new Test();
// "it works!";

      

+6


source


The correct way to do this is to use export {Test}

.



+2


source


You just need to change test.js:

export class Test

      

Then

import {Test} from './test'

      

0


source


You can do

class MyClass { }

export { MyClass }

      

or

export default MyClass // no semicolon

      

And then

import { MyClass as Stuff } from './modulepath';

      

or (if you declare a default export)

import { default as MyClass } from './modulepath';

      

or simply

import MyClass from './modulepath';

      

-1


source







All Articles