问题
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:
- Instead of using
var
, usewindow.
. (window.test = "TEST";
) - Forget
var
(dosen't work in strict mode).test = "TEST";
- Before the
<script src="bundle.js"></script>
, declaretest
(var test;
) and then forgetvar
.
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