1

My sum.js file as below

var mathOp = {
            sum : function(a,b){
                return a+b;
            }
        }     
export default mathOp;

My index.js file as below (It will have multiple import file and tree shaking later point of time)

import mathOp from "./sum";
export default mathOp;

I have made a bundle file bundle.js using webpack for above two files and called bundle.js in an index.html file as below

<script type="text/javascript" src="/bundle.js"></script></body>

Now I wanted to call mathOp.sum function in my index.html file as below

 <script type="text/javascript">
    $(document).ready(function(){
      var result = mathOp.sum(2,5);
      console.log(result); 
 });        
 </script>

But I am not able to do it? can any one guide me how to do it?

Parth Patel
  • 167
  • 3
  • 19

1 Answers1

1

As pointed out by @loganfsmyth By default, webpack can not expose any of function from bundle.js

To do that, we need to configure the JS file as the library in webpack.config.js as below

module.exports = {
  //...
  output: {
    library: 'MyBundle'
  }
}

Now We can able to use sum function as below

<script type="text/javascript">
    $(document).ready(function(){
      var result = MyBundle.mathOp.sum(2,5);
      console.log(result); 
 });        
</script>

For further reference, Please refer https://webpack.js.org/configuration/output/#output-library

Parth Patel
  • 167
  • 3
  • 19