Webpack have trouble with scopes

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-10 18:06:11

问题


There are several modules that are connected to app.js, for example the code that is inside:

var test = "TEST"; 

Here is my webpack.config:

module.exports = {
    entry: './src/app.js',
    output: {
        filename: './dist/bundle.js'
    }
};

The problem is that when I try to call my test variable in the developer console, I get an error:

Something about the scope, when I connect app.js directly - everything works, what's the problem and how to fix it?


回答1:


Yes, this is a scope problem. There are two ways to fix this:

  1. Instead of using var, use window.. (window.test = "TEST";)
  2. Forget var (dosen't work in strict mode).test = "TEST";
  3. Before the <script src="bundle.js"></script>, declare test (var test;) and then forget var.

Hope this is the anwser you're looking for.




回答2:


The default functionality of webpack is to scope files that are passed in to its configuration, see documentation here: https://webpack.js.org/configuration/output/

This means that if you set a var in the file, then bundle it with webpack, it will become available only within its scope which, in this case, is the app.js file. If you open the file in your browser by itself, no scoping will take place hence why you don't have any issues when viewing directly.

If you need to access that test variable outside of the file, you'll have to turn it into a global variable, otherwise it will remain scoped within the bundle.js file created from webpack.



来源:https://stackoverflow.com/questions/49371192/webpack-have-trouble-with-scopes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!