HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Calling webpacked code from outside (HTML script tag)

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromcodescripttagcallinghtmloutsidewebpacked

Problem

Suppose that I have class like this (written in typescript) and I bundle it with webpack into bundle.js.

export class EntryPoint {
    static run() {
        ...
    }
}


In my index.html I will include the bundle, but then I would also like to call that static method.


    window.onload = function() {
        EntryPoint.run();
    }


However, the EntryPoint is undefined in this case. How would I call the bundled javascript from another script then?

Added: Webpack config file.

Solution

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:


  window.onload = function () {
    EntryPoint.run();
  };


Check the gist with the actual code.

Code Snippets

module.exports = {
  entry: './index.js',
  output: {
    path: './lib',
    filename: 'yourlib.js',
    libraryTarget: 'var',
    library: 'EntryPoint'
  }
};
module.exports = {
  run: function () {
    console.log('run from library');
  }
};
<script src="lib/yourlib.js"></script>
<script>
  window.onload = function () {
    EntryPoint.run();
  };
</script>

Context

Stack Overflow Q#34357489, score: 180

Revisions (0)

No revisions yet.