Reputation: 11
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'
Upvotes: 1
Views: 2678
Reputation: 4007
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');
}
Upvotes: 1
Reputation: 664538
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.
Upvotes: 3