如何使用webpack访问全局对象(窗口)?

时间:2015-04-24 10:18:29

标签: javascript actionscript-3 global-variables externalinterface webpack

我正在尝试使用ExternalInterface和webpack将ActionScript与JavaScript连接起来。

ExternalInterface只能激发在全局对象(call)上找到的(window)函数。如何在window(全局对象)上获取webpack模块参考?

请允许我详细说明一下,我希望公司的名称空间(window.companyName)具有ExternalInterface的界面:

window.companyName = { isReady: function() { ... },
                       driver1: function() { ... }, 
                       driver2: function() { ... } }

ActionScript将驱动我的JavaScript。更基本的问题是,如何使用webpack设置全局变量以便ExternalInterface可以看到它们(最好是模块的导出)?

我尝试过使用expose-loaderexports-loader imports-loader但没有运气。理想情况下expose-loader是我需要的,但似乎不起作用。当我在我的模块中设置window.companyName并尝试在我的chrome控制台中验证它时,会产生undefined

3 个答案:

答案 0 :(得分:7)

您是否使用webpack-dev-server

因为当我尝试webpack命令时,一切正常。我在Chrome开发者工具中输入window.mySampleGlobalVariable来测试它。

当我运行webpack-dev-server命令时,我的窗口变量未定义。

我有这个示例应用程序:

<强> 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']
    }
};

答案 1 :(得分:1)

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.

答案 2 :(得分:1)

如果您使用iframe运行webpack-dev-server,则无法通过Chrome控制台访问该变量。