Rav*_*ven 107 html javascript typescript webpack
假设我有这样的类(用typescript编写)并将其与webpack捆绑在一起bundle.js.
export class EntryPoint {
static run() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
在我的index.html中,我将包含bundle,但是我还想调用那个静态方法.
<script src="build/bundle.js"></script>
<script>
window.onload = function() {
EntryPoint.run();
}
</script>
Run Code Online (Sandbox Code Playgroud)
但是,EntryPoint在这种情况下,未定义.我如何从另一个脚本调用捆绑的JavaScript?
补充:Webpack配置文件.
dre*_*cat 122
您似乎希望将webpack包作为库公开.您可以配置webpack以在您自己的变量中的全局上下文中公开您的库,例如EntryPoint.
我不知道TypeScript,因此该示例使用纯JavaScript.但这里重要的部分是webpack配置文件,特别是以下output部分:
module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};
Run Code Online (Sandbox Code Playgroud)
module.exports = {
run: function () {
console.log('run from library');
}
};
Run Code Online (Sandbox Code Playgroud)
然后,您将能够像您期望的那样访问您的库方法:
<script src="lib/yourlib.js"></script>
<script>
window.onload = function () {
EntryPoint.run();
};
</script>
Run Code Online (Sandbox Code Playgroud)
用实际代码检查要点.
Mat*_*att 50
webpack.config.js通过简单地使用import我从main/index.js文件调用的语句,我设法让这个工作没有任何进一步的修改:
import EntryPoint from './EntryPoint.js';
window.EntryPoint = EntryPoint;
Run Code Online (Sandbox Code Playgroud)
作为参考,这是我的weback.config.js文件.
最初我尝试使用相同的方法require,但它将模块包装器分配window.EntryPoint给实际的类.
Kur*_*iam 10
在我的情况下,我可以通过在创建窗口时将函数写入窗口,从另一个脚本的捆绑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>
Run Code Online (Sandbox Code Playgroud)
我无法使用Babel,所以这对我有用.