从对象导入属性 [英] Import properties from an object

查看:122
本文介绍了从对象导入属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从函数文件导入一个函数。函数文件看起来像这样。

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

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

导出默认功能;

然后我尝试导入 url 函数这样。

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

当我这样做时,我会从browserify中浏览以下错误。


未捕获TypeError:(0,_Functions.url)不是函数


根据 MDN 文档,此导入应该在 url 函数对象中工作。



我做错了什么?

解决方案

你做了什么 - 导出了一个对象。



在这种情况下,您需要导入一个对象并访问其属性:

  importfrom。 ./Utils/Functions; 
Functions.url();

如果要创建命名导出 - 您需要更改导出和定义方式:

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

函数资源(path =''){
return this.url(path);
}

export {url,asset};

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

导出函数asset(path =''){
return this.url(path);
}

另外一个注意事项:即使看起来类似,它并不是解构。该标准将其命名为 ImportsList 并定义自己的语义,与解构的语义不同。



参考文献: p>


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:

这篇关于从对象导入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆