假设我有这样的类(用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 config file。
发布于 2015-12-19 01:53:08
看起来您想要将webpack捆绑包公开为library。您可以将webpack配置为在您自己的变量(如EntryPoint
)中的全局上下文中公开您的库。
我不知道TypeScript,所以这个示例使用普通的JavaScript。但这里最重要的部分是webpack配置文件,特别是output
部分:
webpack.config.js
module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};
index.js
module.exports = {
run: function () {
console.log('run from library');
}
};
然后,您将能够像预期的那样访问您的库方法:
<script src="lib/yourlib.js"></script>
<script>
window.onload = function () {
EntryPoint.run();
};
</script>
用实际代码检查gist。
发布于 2015-12-18 23:05:08
通过简单地使用我从我的主/ webpack.config.js
文件中调用的import
语句,我设法在没有任何进一步的索引修改的情况下使其工作:
import EntryPoint from './EntryPoint.js';
window.EntryPoint = EntryPoint;
作为参考,下面是我的weback.config.js
文件。
最初,我尝试使用require
来完成同样的任务,但是它将模块包装器分配给了window.EntryPoint
,而不是实际的类。
发布于 2017-09-30 00:55:40
在我的环境中,通过在创建窗口时将函数写到窗口中,我能够从捆绑的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>
我不能使用巴别塔,所以这对我很有效。
https://stackoverflow.com/questions/34357489
复制相似问题