简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM