Reputation: 254
I am using webpack for my project.
Suppose I have a dep.js
file which has the following code
export function abc() {
var a = 10;
}
console.log(100);
function xyz(){
var b = 11;
}
xyx();
And I have a main.js
file which has the following code
import {abc} from './dep.js';
According to the logic of import and export, only the function abc
should be imported.
But when i check the source in console i found that
--> all the other statement and function like console.log(100)
, function xyx
also got imported
--> and the effect of calling the function via xyz()
in dep.js
also shows the effect in main.js
Why this is happening?
Upvotes: 1
Views: 1150
Reputation: 371019
That's how modules work, by default. If any part of the module is imported at least once, the whole module runs all of its top level code.
It's possible to remove dead code that doesn't get run with tree shaking in Webpack, but the module shown doesn't have any dead code - it has an exported function, which gets used, and it has code which is run on the top level and called (the console.log
, the declaration of xyx
, and the call of xyx
).
If you exported something which wasn't used elsewhere in the module, it could be dropped with tree shaking, eg:
export function abc(){
var a = 10;
}
export function def(){
var a = 10;
}
Here, if def
is not imported or used elsewhere, it could be automatically removed.
(Also note that function definitions require ()
s after them, even if they take no arguments)
This sort of thing is why I almost always export functions only - it's good to avoid writing code that has side-effects on the top level of a module, because then just importing the module will result in those side-effects (like you're seeing here). It's generally easier to structure code when you have a single entry point (eg main.js
) which imports the functions it needs and then calls them. If every module runs code with side-effects as part of the top level, things can quickly become very confusing and unmanageable. (This technique also happens to improve tree shaking, but that's just a side benefit)
Upvotes: 8