在webpack中创建全局功能 [英] Make global function in webpack
问题描述
我正在使用webpack制作一个打字稿插件。一切都运作良好,但我有一个问题,从外面看到它。例如,我有文件:
I'm making a typescript plugin with webpack. Everything works well but I have a problem with making it visible from outside. For example, I have files:
/* ./src/a.ts */
class A {
constructor(args) {...}
}
export default A;
/* ./src/app.ts */
import A from "./a.ts";
function init(args) {
new A(args);
}
export { init };
/* ./index.html */
<html>
<head>...</head>
<body>
...
<!-- webpack bundle ts files into ./dist/app.js -->
<script src="./dist/app.js"></script>
<script>init({...});</script>
</body>
</html>
有了这个,我得到了未捕获的ReferenceError:init未定义
。在捆绑文件中我可以看到这个函数不是全局的,但在其他函数中如下:
With this I got Uncaught ReferenceError: init is not defined
. In bundled file I can see that this function is not global, but inside other function like this:
/* 1 */
/***/ function(module, exports) { ... }
如何将此函数公开?
推荐答案
从模块导出不会使实体成为全局。您可以直接将其作为成员添加到窗口:
Exporting from module does not make an entity global. You can either directly add it as a member to window:
window.init = init;
或者更好的是,将init调用移动到打字稿模块 - 在这种情况下应该是你的webpack入口点。
or, better still, move the init invocation to a typescript module - which in this case should be your webpack entry point.
这篇关于在webpack中创建全局功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!