从外部调用Webpacked代码(HTML脚本标记)

JavaScript Webpack

Gil

2020-03-23

假设我有这样的类(用TypeScript编写),并将其与webpack捆绑在一起bundle.js

export class EntryPoint {
    static run() {
        ...
    }
}

在我的index.html中,我将包含该捆绑包,但随后我也想调用该静态方法。

<script src="build/bundle.js"></script>
<script>
    window.onload = function() {
        EntryPoint.run();
    }
</script>

但是,EntryPoint在这种情况下未定义。那我该如何从另一个脚本中调用捆绑的javascript?

补充Webpack配置文件

第2607篇《从外部调用Webpacked代码(HTML脚本标记)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
樱小胖Mandy 2020.03.23

在我的情况下,我可以通过在创建脚本时将函数写入窗口来从另一个脚本从捆绑的JavaScript中调用函数。

// In the bundled script:
function foo() {
    var modal = document.createElement('div');
}
// Bind to the window
window.foo = foo;
// Then, in the other script where I want to reference the bundled function I just call it as a normal function
<button onClick="window.foo()">Click Me</button>

我无法使用Babel,因此对我有用。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android