简体   繁体   中英

Import properties from an object

I am trying to import a single function from a functions file. The functions file looks like this.

const Functions = {
    url(path = '') {
        path = path.replace(/^\/+/, '');
        return `${document.baseURI}/${path}`;
    },

    asset(path = '') {
        return this.url(path);
    }
};

export default Functions;

I then try to import the url function like this.

import {url} from "../Utils/Functions";

When I do this, I get the following error in-browser from browserify.

Uncaught TypeError: (0 , _Functions.url) is not a function

According to MDN docs, this import should work as url is in the Functions object.

What am I doing wrong?

What you have done - is exported an object.

In that case you need to import an object and access its property:

import Functions from "../Utils/Functions";
Functions.url();

If you want to make named export - you need to change the way you're exporting and defining it:

function url(path = '') {
    path = path.replace(/^\/+/, '');
    return `${document.baseURI}/${path}`;
}

function asset(path = '') {
    return this.url(path);
}

export { url, asset };

or

export function url(path = '') {
    path = path.replace(/^\/+/, '');
    return `${document.baseURI}/${path}`;
}

export function asset(path = '') {
    return this.url(path);
}

As another note: it is not destructuring, even though it looks similar. The standard names it as ImportsList and defines its own semantic, different from the destructuring one.

References:

If you use 'default export' then the import should be:

import Functions from "../Utils/Functions";

Actually, you can import it with any identifier you like (not only 'Functions')

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