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?
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
Here, starts the function declaration of __webpack_require__ . It takes moduleId as a parameter and whenever this function is invoked when the cache is being checked if the module is already loaded or not. If yes then the module is returned from the cache else we load the module. . exports is not native module export .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With