Javascript 导入函数语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43157936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript import function syntax
提问by Don Smythe
I am trying to import a function from another module but on running am getting an error:
我正在尝试从另一个模块导入一个函数,但在运行时出现错误:
TypeError: _this.getData is not a function.
data.js
数据.js
function getData() {
return [
{ id: 1,
name: 'Pluto',
type: 'Dwarf Planet'
},
{ id: 2,
name: 'Neptune',
type: 'Planet'
}
]
}
export { getData }
worker.js
工人.js
import getData from data.js
this.data = this.getData()
Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?
然后在运行时,我收到了上面提到的浏览器错误。关于我做错了什么的任何想法?
回答by Shota
Change your import as a named import like this:
将您的导入更改为命名导入,如下所示:
import { getData } from data.js
Or export getDatafunction as a default export like this:
或者getData像这样导出函数作为默认导出:
export default { getData }
回答by DNM
You should omit the "this" keyword when using "getData()" it doesn't belong on the current object.
当使用“getData()”它不属于当前对象时,你应该省略“this”关键字。
function getData() { .... }
export default getData;
import getData from "data.js"
this.data = getData();
回答by Joseph
That should be
那应该是
import { getData } from data.js
Without the brackets, you're importing the defaultexport which doesn't exist.
如果没有括号,您将导入default不存在的导出。

