Import properties from an object

2020-03-24 04:33发布

问题:

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?

回答1:

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:

  • https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
  • http://www.ecma-international.org/ecma-262/6.0/#sec-imports


回答2:

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