Import properties from an object

2020-03-24 04:39发布

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?

2条回答
叼着烟拽天下
2楼-- · 2020-03-24 04:55

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')

查看更多
家丑人穷心不美
3楼-- · 2020-03-24 05:01

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:

查看更多
登录 后发表回答