从对象导入属性 [英] Import properties from an object
问题描述
我正在尝试从函数文件导入一个函数。函数文件看起来像这样。
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>
- https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/声明/导入
- http://www.ecma-international.org/ecma-262/6.0/#sec-imports
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:
- 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
这篇关于从对象导入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!