Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling webpacked code from outside (HTML script tag)

People also ask

How do you call a script in HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can I put script tag anywhere in HTML?

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.

Can we use script tag in HTML?

Definition and UsageThe <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.

How do you put a tag in a script tag in HTML?

The <script> tag in HTML is used to define the client-side script. The <script> tag contains the scripting statements, or it points to an external script file. The JavaScript is mainly used in form validation, dynamic changes of content, image manipulation, etc. Attributes: Many attribute associated with 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 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.


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>

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