1

Is there a way to import a module into another and run it only when called?

Actually i am importing like this.

import {getData, paginacao} from './restCountries.js'

2 Answers2

1

No. Importing a module always causes its initialisation code to run - otherwise there wouldn't be any values that you can use.

If there's code in a module that you don't want to run immediately, put it into a function and export that.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

there is a way to detect if your module is being imported or called directly and execute different parts of the file.

This has been answerred in this thread

if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}
Micha Roon
  • 3,957
  • 2
  • 30
  • 48