Calling webpacked code from outside (HTML script tag) Calling webpacked code from outside (HTML script tag) typescript typescript

Calling webpacked code from outside (HTML script tag)


It seems that you want to expose the webpack bundle as a library. You can configure webpack to expose your library in the global context within a variable of your own, like EntryPoint.

I don't know TypeScript so the example uses plain JavaScript instead. But the important piece here is the webpack configuration file, and specifically the output section:

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');  }};

Then you will be able to access your library methods like you expect:

<script src="lib/yourlib.js"></script><script>  window.onload = function () {    EntryPoint.run();  };</script>

Check the gist with the actual code.


I managed to get this working without any further webpack.config.js modifications, by simply using the import statement which i called from my main/index.js file:

import EntryPoint from './EntryPoint.js';window.EntryPoint = EntryPoint;

enter image description here

For reference, here's my weback.config.js file.

Initially I tried accomplishing the same using require, however it assigned the module wrapper to window.EntryPoint as opposed to the actual class.


In my circumstance I was able to call a function from within the bundled JavaScript from another script by writing the function to the window when creating it.

// In the bundled script:function foo() {    var modal = document.createElement('div');}// Bind to the windowwindow.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>

I wasn't able to use Babel so this worked for me.