How do I access the global object (window) using webpack?

和自甴很熟 提交于 2019-12-03 10:02:53

Aren't you using webpack-dev-server?

Because when I try webpack command everything is working fine. I'm testing it by typing window.mySampleGlobalVariable in chrome developer tools.

BUT when I run webpack-dev-server command then my window variable is undefined.

I have this sample app:

app.js

window.mySampleGlobalVariable = 'TEST';
console.log('App is ready');

index.html

<!DOCTYPE HTML>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Webpack test</title>
    </head>

    <body>
        Webpack test
        <script src="bundle.js"></script>
    </body>

</html>

webpack.config.js

var path = require('path');

module.exports = {
    entry: './app.js',
    output: {
        filename: './bundle.js'
    },
    resolve: {
        extensions: ['', '.js']
    }
};

If you running webpack-dev-server with the iframe you cannot access the variable via the Chrome console.

Ricardo Stuven

You do have access to window object from your webpacked script. Webpack does not interfere with it since the wrapper function only injects module, exports and __webpack_require__ arguments.

Try it writing a script with a single line accessing window object and then check out the output script.

Your assignment should work, unless the execution never reaches it or some loader is altering the relevant code.

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