简体   繁体   English

从对象导入属性

[英]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. 然后,我尝试像这样导入url函数。

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

When I do this, I get the following error in-browser from browserify. 当我这样做时,我从browserify获得了以下浏览器错误。

Uncaught TypeError: (0 , _Functions.url) is not a function 未捕获的TypeError:(0,_Functions.url)不是函数

According to MDN docs, this import should work as url is in the Functions object. 根据MDN文档,此导入应与Functions对象中的url工作。

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. 该标准将其命名为ImportsList并定义其自己的语义,这与ImportsList语义不同。

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') 实际上,您可以使用任何喜欢的标识符(不仅是“函数”)导入它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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