本文介绍了Webpack 从模块导入 javscript 函数也会导入该模块中的所有其他语句和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目使用 webpack.

I am using webpack for my project.

假设我有一个 dep.js 文件,其中包含以下代码

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();

我有一个 main.js 文件,其中包含以下代码

And I have a main.js file which has the following code

import {abc} from './dep.js';

按照导入导出的逻辑,应该只导入函数abc.但是当我在控制台中查看源代码时,我发现

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

-->所有其他语句和函数,如console.log(100)函数xyx也被导入

--> all the other statement and function like console.log(100), function xyx also got imported

--> 以及dep.js中通过xyz()调用该函数的效果也显示了main.js中的效果

--> and the effect of calling the function via xyz() in dep.js also shows the effect in main.js

为什么会这样?

推荐答案

默认情况下,这就是模块的工作方式.如果模块的任何部分至少被导入一次,整个模块就会运行它的所有顶级代码.

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.

可以删除无法通过 摇树 在 Webpack 中,但显示的模块没有任何死代码 - 它有一个导出的函数,可以使用,并且它有在顶层运行并调用的代码(console.logxyx的声明,xyx的调用).

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;
}

这里,如果 def 没有被导入或在别处使用,它可以被自动删除.

Here, if def is not imported or used elsewhere, it could be automatically removed.

(另请注意,函数定义在其后需要 ()s,即使它们不带参数)

(Also note that function definitions require ()s after them, even if they take no arguments)

这种事情就是为什么我几乎总是只导出函数 - 最好避免编写对模块顶层有副作用的代码,因为这样只会导致导入模块在那些副作用中(就像你在这里看到的).当您只有一个入口点(例如 main.js)来导入它需要的函数然后调用它们时,通常更容易构建代码.如果每个模块都运行带有副作用的代码作为顶层的一部分,事情很快就会变得非常混乱和难以管理.(这种技术也碰巧改善了摇树,但这只是一个附带好处)

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)

这篇关于Webpack 从模块导入 javscript 函数也会导入该模块中的所有其他语句和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:10