seaBass
seaBass

Reputation: 597

Using webpack built libraries in browser JavaScript

I am brand new to using webpack. I do not understand how to use the libraries I have created with webpack in browser based JavaScript. I have built a library with the following modules from AWS SDK JavaScript version 3.

@aws-sdk/client-cognito-identity
@aws-sdk/credential-provider-cognito-identity
@aws-sdk/client-dynamodb
@aws-sdk/client-dynamodb-streams
@aws-sdk/client-s3

Here are the contents of webpack.config.js:

const path = require('path');

module.exports = {
  entry: './aws-sdk-build.js',
  output: {
    path: path.resolve(__dirname, './src/js'),
    filename: 'aws-sdk-js-v3.js',
    library: "awssdk"
  },
  mode: 'production', //development
  target: 'web'
};

I added <script type="module" src="js/aws-sdk-js-v3.js"></script> to the head of my index.html.

What I can't figure out is how to access the modules inside aws-sdk-js-v3.js from within the browser's javascript.

Upvotes: 1

Views: 252

Answers (1)

kyle-marshall
kyle-marshall

Reputation: 56

In the entry point of your module aws-sdk-build.js, you can create some on load behavior to interact with the DOM. e.g. with JQuery:

$(() => {
   const someElement = document.getElementById("targetElement");
   if (someElement) {
      // initialize your cool thing with someElement as mount point
   }
});

You can also expose certain pieces of your code by assigning them to the window object.

For example, you can use something like this in your module entry point:

Object.assign(window, {
    MyGreatClass,
    reallyUsefulFunction
});

...and then you will be able to play with MyGreatClass / reallyUsefulFunction within that page containing the script tag (and in the dev console).

If memory serves, another alternative is to do something within that script tag:

<script type="module" src="js/aws-sdk-js-v3.js">
    // module exports can be accessed within here
</script>

Although I'm not sure on the usage for the last option or if I'm mistaken so someone please correct me.

Upvotes: 1

Related Questions