user2952238
user2952238

Reputation: 787

ES6 export and import problems

I'm trying to export functions in ES6 to access them from other files. But I can't figure out how.

file 1: (import)

import components from './components/components';
console.log(components.hej);

file 2: (export)

var hej = () => {
    console.log('HEj'); 
};

export var hej;

Why can't I access the function "hej" declared in file 2 from file 1? It does not make sense for me.

Please help!

Upvotes: 1

Views: 1214

Answers (1)

Joe Clay
Joe Clay

Reputation: 35837

You're doing a named export, not a default export, so that import syntax won't work. To import hej as it stands, you'd have to do:

// Imports a single object by name
import { hej } from './components/components';
console.log(hej);

Or:

// Imports all exported objects grouped together under the specified name
import * as components from './components/components';
console.log(components.hej);

Also, your export syntax isn't right - export var hej should be export { hej }, as you're not defining a new variable there, you're using the existing one. Alternatively, you could change your function declaration to export var hej = () => { ... };, and that would have the same effect.

Upvotes: 4

Related Questions