Make global function in webpack

2020-07-03 08:11发布

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>

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) { ... }

How to make this function public?

1条回答
地球回转人心会变
2楼-- · 2020-07-03 08:34

Exporting from module does not make an entity global. You can either directly add it as a member to window:

window.init = init;

or, better still, move the init invocation to a typescript module - which in this case should be your webpack entry point.

查看更多
登录 后发表回答