简体   繁体   中英

Calling a function from a module in ES6

I have a js module and import it into the main js app.

The js module has its own function/method.

However when I try to call that method from the main js app, I get the eslint error:
'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 error: 'testMethod' is defined but never used

console error: Uncaught Error: Module build failed: Module failed because of a eslint error

You are defining a function called testMethod which is enclosed in the scope of the test function. The testMethod function is never called in the scope in which it exists.

The testMethod function isn't exported, and is not visible outside the scope it is defined in (the enclosing function).

Based on your example in app.js , it looks like you want to export an object, one of whose properties is the testMethod function from test.js , rather than a function. Compare with the following:

// 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 is a function inside test function. It is not a property of the exporting test function.
If you need the inside testMethod function, you can export an object

export default {
  testMethod: function() {
    console.log('bar');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM