Dovre
Dovre

Reputation: 71

Export a class import an object

Here is my code (vanillaJS):

// app.js
import Block from './models/index';
console.log(typeof(Block));
let block = new Block();

// /models/block.js
export default class Block {
    constructor() {
    }
};

// /models/index.js
import Block from './block';
export default { 
    Block
};

The console.log in app.js tell me that Block is an object.

I want to import Block as a class not an object.

What did I do wrong? Is it possible?

Good day.

Upvotes: 1

Views: 60

Answers (2)

Bergi
Bergi

Reputation: 665554

As already explained, { Block } - the thing you exported - is an object indeed. However, I would recommend not to default-export anything from models/index.js as the solution.
I think you were looking for named exports here:

// /models/index.js
import Block from './block';
export { // <- this is not an object literal
    Block // short for: `Block as Block`
};
// or in one line:
export { default as Block } from './block';

// app.js
import { Block } from './models/index';
//     ^       ^
console.log(typeof(Block));
let block = new Block();

Upvotes: 1

dfsq
dfsq

Reputation: 193301

Here

// /models/index.js
import Block from './block';
export default { 
    Block
};

you indeed export an object (with property Block). To export class just do:

// /models/index.js
import Block from './block';
export default Block

// or in one line: export { default } from './block'

Upvotes: 2

Related Questions