从 ES6 中的模块调用函数
Calling a function from a module in ES6
我有一个 js 模块并将其导入到主 js 应用程序中。
js模块自带function/method.
然而,当我尝试从主 js 应用程序调用该方法时,出现 eslint 错误:
'testMethod' is defined but never used
test.js:
export default function test() {
console.log('foo');
function testMethod() {
console.log('bar');
}
}
app.js
import test from './test';
test.testMethod();
eslint 错误:'testMethod' is defined but never used
控制台错误:Uncaught Error: Module build failed: Module failed because of a eslint error
您正在定义一个名为 testMethod
的函数,它包含在 test
函数的范围内。 testMethod
函数永远不会在它存在的范围内被调用。
testMethod
函数未导出,并且在其定义的范围(封闭函数)之外不可见。
根据您在 app.js
中的示例,您似乎想要导出一个对象,其属性之一是 test.js
中的 testMethod
函数,而不是函数。与以下比较:
// test.js
export function testMethod() {
return "Hello";
}
// app.js
import { testMethod } from './test';
// or
import test from './test';
console.log(testMethod());
console.log(test.testMethod());
testMethod
是 test
函数中的一个函数。它不是导出 test
函数的 属性。
如果需要里面的testMethod
函数,可以导出一个对象
export default {
testMethod: function() {
console.log('bar');
}
}
我有一个 js 模块并将其导入到主 js 应用程序中。
js模块自带function/method.
然而,当我尝试从主 js 应用程序调用该方法时,出现 eslint 错误:
'testMethod' is defined but never used
test.js:
export default function test() {
console.log('foo');
function testMethod() {
console.log('bar');
}
}
app.js
import test from './test';
test.testMethod();
eslint 错误:'testMethod' is defined but never used
控制台错误:Uncaught Error: Module build failed: Module failed because of a eslint error
您正在定义一个名为 testMethod
的函数,它包含在 test
函数的范围内。 testMethod
函数永远不会在它存在的范围内被调用。
testMethod
函数未导出,并且在其定义的范围(封闭函数)之外不可见。
根据您在 app.js
中的示例,您似乎想要导出一个对象,其属性之一是 test.js
中的 testMethod
函数,而不是函数。与以下比较:
// test.js
export function testMethod() {
return "Hello";
}
// app.js
import { testMethod } from './test';
// or
import test from './test';
console.log(testMethod());
console.log(test.testMethod());
testMethod
是 test
函数中的一个函数。它不是导出 test
函数的 属性。
如果需要里面的testMethod
函数,可以导出一个对象
export default {
testMethod: function() {
console.log('bar');
}
}