Svein Jarle
Svein Jarle

Reputation: 233

How to access a function in a Webpack bundle from a HTML script

The problem is that I would like to make a timeout function on my page. I have a silverlight app and a new react app in the page. This 2 "apps" need to have a common timer variable that I can in React read and display a <Div> if time is more then 10min.

The SilverLight app can call a JS function on every click. This works, but I'm not able to call a function inside the webpack bundled file?? Is it not possible to reach functions from a js function in a <script> from html side??

Do I have to send the Silverlight click time to the server and then do a ajax call from React every 1min or so to see if the Silverlight has been active? (does not sound like a good approach) Hope you can point me in the right direction or show me a good way to solve this problem for me :) and remember I'm new to react and webpack so I'm not able to use the right google words to find the solution myself.

Upvotes: 11

Views: 9946

Answers (2)

Shiva Pandey
Shiva Pandey

Reputation: 655

This is a very common question. There are different ways you could do this.

Method 1

If there are multiple such functions you would like to use outside of it, then you have to export the function using:

module.exports = {
      yourfunctionName
}

And then you have to configure your webpack to treat this as a library. This is how most of the libraries do. Now to access the function outside the bundled file. Simply use your library name (as configured in webpack) for e.g, let's say my library name is myLibrary then the code will be:

myLibrary.yourFunctionName

Method 2

if you don't need to export many functions or you are looking for a quick easy answer to this then you can add your functions to window object, which makes it available everywhere.

In your main file (which is going to be bundled) filename.bundle.js

window.functionName = yourFunction;

And wherever you want to access that function outside of bundle

window.functionName();

It isn't advisable to put the functions in window object, But if you are looking for quick easy fix then method 2 is good for you.

Upvotes: 10

Filip Dupanović
Filip Dupanović

Reputation: 33700

Indeed, this is a bit of a tricky question because Webpack bundles are usually self-contained and it's impossible to load modules and access their exports outside of the Webpack runtime the compilation is bound to. This was for a bit of background.

What you're looking for is the expose-loader. It will allow you to expose exports of a module to the global scope.

// Exposes the exports for file.js to the global context
// on property "libraryName".
//
// In web browsers, window.libraryName is then available.
require('expose-loader?libraryName!./file.js');

Upvotes: 0

Related Questions