Calling webpacked code from outside (HTML script tag)

JavascriptHtmlTypescriptWebpack

Javascript Problem Overview


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.

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

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

Added: Webpack config file.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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 window
window.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.

Solution 4 - Javascript

I had a similar challenge, I wanted to create a bundle for multiple pages within a journey and wanted each page to have it's own entry point into the code, and without a separate bundle for each page.

Here's my approach, which is very similar to Kurt Williams but from a slightly different angle, also without changing webpack config:

JourneyMaster.js

import { getViewData } from './modules/common';
import { VIEW_DATA_API_URL } from './modules/constants';
import { createLandingPage, createAnotherPage } from './modules/components/pageBuilder';

window.landingPageInit = () => {
	getViewData(VIEW_DATA_API_URL).then(viewData => {
		createLandingPage(viewData);
	});
};

window.anotherPageInit = () => {
	getViewData(VIEW_DATA_API_URL).then(viewData => {
		createAnotherPage(viewData);
	});
};

// I appreciate the above could be one liners,
// but readable at a glance is important to me

Then an example of how I call these methods at the end of the html page:

<script src="/js/JourneyMaster.js"></script>
<script>window.landingPageInit();</script>

Solution 5 - Javascript

WEBPACK.CONFIG.JS

1.USING UMD

module.exports={
            mode:'development',
            entry:'./yourentry.js',
            output:{
                path:path.resolve(__dirname,"dist"),
                filename:'main.js',
                publicPath:'/dist/',
                libraryTarget:'umd', 
                library:'rstate',
                umdNamedDefine: true,
                libraryExport: 'default' 
            }
    }

index.html

<script src="dist/main.js"></script>
<script>
  window.onload = function () {
  rstate()=>{}
</script>

main.js

export default function rstate(){
console.log("i called from html")
}

2.USING VAR

module.exports={
            mode:'development',
            entry:'./yourentry.js',
            output:{
                path:path.resolve(__dirname,"dist"),
                filename:'main.js',
                publicPath:'/dist/',
                libraryTarget:'var', 
                library: 'EntryPoint'
            }
    }

index.html

<script>
  window.onload = function () {
  EntryPoint.rstate()=>{}
</script>

main.js

module.exports={
    rstate=function(){
        console.log("hi module")
    }
}

3.USING AMD as library we use like(for those who want to make lib)

define(['jquery', './aux-lib.js'], function ($) { ..(1).. });

Solution 6 - Javascript

Many of the answers so far work, it would only be necessary to clarify that Webpack will not recognize the library until it is built once declared. You should use npm run build right after creating your library, before continuing to work with npm start.

At least that's how it works for me, using only webpack.

Solution 7 - Javascript

Maybe this is some impostor syndrome on my part, but I think 'real' coders will cringe at my answer. Regardless, I found this solution to be the best fitting for being pragmatic about my time with my hobby project:

Chane your JS function declaration from:

function renderValue(value) {

to:

global.renderValue = function(value) {

Of course, you'll want to require('path/to/your_custom_js') as you would any file.

I found this answer here: https://www.fastruby.io/blog/rails/webpack/from-sprockets-to-webpacker.html

Solution 8 - Javascript

This took me forever to figure out as the accepted answer wasn't working for me. Just make sure the function name is the same as the library in the config and it's bundled with the config specified -- npx webpack --config webpack.config.js --mode=development -- hopefully this saves people a few hours.

index.js (function to be bundled) >>

function EntryPoint() {
    console.log('called from bundle');
}

module.exports = EntryPoint;

webpack.config.js >>

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
};

start.html (where the bundled function is called) >>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Azure SDK Storage Example</title>
    <script type="text/javascript" src="./dist/main.js"></script>
  </head>
  <body>
      <h1>Azure SDK Storage Example</h1>
  </body>
</html>

<script>
 EntryPoint();
</script>

Solution 9 - Javascript

App.ts:

namespace mytypescript.Pages {

		export class Manage {

	 public Initialise() {
	 $("#btnNewActivity").click(() => {
					alert("sdc'");
				});
		}
	}
}

mypage.html:

 <input class="button" type="button" id="btnNewActivity" value="Register New Activity" />
 
 <script type="text/javascript">
    var page = new mytypescript.Pages.Manage();
    page.Initialise();
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavenView Question on Stackoverflow
Solution 1 - JavascriptdreyescatView Answer on Stackoverflow
Solution 2 - JavascriptMattView Answer on Stackoverflow
Solution 3 - JavascriptKurt WilliamView Answer on Stackoverflow
Solution 4 - JavascriptStudioTimeView Answer on Stackoverflow
Solution 5 - JavascriptßãlãjîView Answer on Stackoverflow
Solution 6 - JavascriptAdrián SernaView Answer on Stackoverflow
Solution 7 - JavascriptianrandmckenzieView Answer on Stackoverflow
Solution 8 - JavascriptTabulaRasaView Answer on Stackoverflow
Solution 9 - JavascriptVeera InduvasiView Answer on Stackoverflow