gpt4 book ai didi

javascript - 无法访问WebPack捆绑的功能

转载 作者:行者123 更新时间:2023-12-03 03:21:56 25 4
gpt4 key购买 nike

我有一个非常简单的 Web 应用程序,其中 WebPack 将 javascript 捆绑到一个可供各种 html 页面使用的 bundle.js 文件中。

不幸的是,即使我在 webpack 配置文件中指定我想将其用作可由脚本标记使用的独立库(libraryTargetlibrary) ,它不起作用。一切似乎都封装在模块中,因此我的功能不可用。

index.html

<!DOCTYPE html>
<html lang="EN">
<head>
<title>Play! Webpack</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app>
Loading...
</app>
<script type="text/javascript" src="/bundles/bundle.js" charset="utf-8"></script>
<button type="button" onclick="ui.helloWorld()">Click Me!</button>
</body>
</html>

我的 webpack.base.config.js 的入口和输出部分

entry: [
'./app/main.js'
],
output: {
path: buildPath,
filename: 'bundle.js',
sourceMapFilename: "bundle.map",
publicPath: '/bundles/',
libraryTarget: 'var',
library: 'ui'
},

ma​​in.js(入口点)

function helloWorld() {
alert( 'Hello, world!' );
}

当单击我的按钮时,我在控制台中收到此错误:

Uncaught TypeError: ui.helloWorld is not a function
at HTMLButtonElement.onclick (localhost/:14)

有关其他信息,我的bundle.js 文件的内容如下所示:

var ui = ...

(stuff here)

function(module, exports, __webpack_require__) {

__webpack_require__(79);

function helloWorld() {
alert('Hello, world!');
}

/***/ }

最佳答案

捆绑库导出的ui对象与入口点模块导出的对象相同。如果您没有从 webpack 中的模块显式导出函数,则该函数只会在该模块的作用域内定义(这是 JavaScript 模块的主要功能之一)。您需要将其分配给 module.exports 对象才能从模块外部访问它:

/** main.js **/

function helloWorld() {
alert( 'Hello, world!' );
}

// module.exports here (in the entrypoint module) is the same object
// as ui in the page's scope (outside webpack)
module.exports = {
helloWord: helloWorld,
};

然后您可以从其他脚本访问它:

<script>
ui.helloWorld(); // 'ui.helloWorld' is the same as
// 'module.exports.helloWorld' above
</script>

如果您没有在入口点模块中显式设置 module.exports,它将默认为空对象 { }

关于javascript - 无法访问WebPack捆绑的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com