我有一个文件something.js
,它有一个功能:
someFunction: function(arg1, arg2){
//code blocks
}
在我的app.js
文件中,我想在app
类中调用此函数。我已导入something.js
这样的文件import { someFunction } from './something.js';
。现在我试图在app
类
var res = someFunction("abc", 2);
console.log(res);`
我收到错误Uncaught TypeError: (0 , _something.someFunction) is not a function
一些帮助将不胜感激。
答案 0 :(得分:4)
您可以:在something.js
文件中执行:module.exports = function(){}..
并在您的app.js
文件中:
const functionName = require('./path_to_your_file');
或export default somethingFunction = {}
以及app.js
:
import {somethingFunction} from '/.path_to_your_file'
让我知道这是否成功! :)
答案 1 :(得分:3)
要导入某些内容,您需要从其他模块导出它。
例如,您可以在something.js。{/ p>中export class YourComponent extends React.Component
然后在另一个文件中,您可以import { YourComponent } from './something'
例如,您可以在something.js
中执行类似
const MyClass = {
methodName() { return true; }
}
export { MyClass as default } // no semi-colon
然后在另一个文件中
import WhateverIWant from 'something';
WhateverIWant.methodName(); // will return true
编辑: 使用大量示例is available here进行深入解释。
答案 2 :(得分:3)
你需要这样写:
something.js
档案 -
module.exports = {
A: funtion(){
},
B: funtion(){
}
}
然后像这样导入:
import {A} from 'something';
或者像这样使用它:
something.js
档案 -
export A(){
}
export B(){
}
然后像这样导入:
import {A} from 'something';
阅读这篇文章:https://danmartensen.svbtle.com/build-better-apps-with-es6-modules
答案 3 :(得分:0)
在something.js
文件中,您可以在文件底部附近添加export someFunction
。然后,这将允许您使用之前的import { someFunction } from './something.js';
导入该功能。