AWS Developer Blog

Using webpack and the AWS SDK for JavaScript to Create and Bundle an Application – Part 1

We introduced support for webpack in version 2.6.1 of the AWS SDK for JavaScript. Using tools such as webpack with the SDK give you a way to bundle your JavaScript modules so that you can write modularized code for the browser.

This post will walk through how to create and bundle a simple application that displays a list of Amazon S3 objects from a bucket by using webpack and the AWS SDK for JavaScript.

Why Use webpack?

Tools such as webpack parse your application code, searching for import or require statements to create bundles that contain all the assets your application needs.

Although webpack only knows how to handle JavaScript files by default, can also configure it to handle other types, such as JSON, CSS, and even image files! This makes it great at packaging up your application’s assets so that they can be easily served through a webpage.

Using webpack, you can create bundles with only the services you need, and generate bundles that will also run in Node.js!

Prerequisites

To follow along with this post, you’ll need to have node.js and npm installed (npm comes bundled with node.js). When you have these tools, create a new directory and download the dependencies we’ll need for this project by running npm install x, where x is the following:

  • aws-sdk: the AWS SDK
  • webpack: the webpack CLI and JavaScript module
  • json-loader: a webpack plugin that tells webpack how to load JSON files

Setting Up the Application

Start by creating a directory to store the project. We’ll name our project aws-webpack.

Our application will contain three files that do the following:

  • s3.js exports a function that accepts a bucket as a string, and a callback function, and returns a list of objects to the callback function.
  • browser.js imports the s3.js module, calls the listObjects function, and displays the results.
  • index.html references the JavaScript bundle that webpack creates.

Create these files in the project’s root directory, as follows:

s3.js

Important: We’ve left configuring the credentials to you.

// Import the AWS SDK
var AWS = require('aws-sdk');

// Set credentials and region,
// which can also go directly on the service client
AWS.config.update({region: 'REGION', credentials: {/* */}});

var s3 = new AWS.S3({apiVersion: '2006-03-01'});

/**
 * This function retrieves a list of objects
 * in a bucket, then triggers the supplied callback
 * with the received error or data
 */
function listObjects(bucket, callback) {
  s3.listObjects({
    Bucket: bucket
  }, callback);
}

// Export the handler function
module.exports = listObjects;

browser.js

// Import the listObjects function
var listObjects = require('./s3');
var bucket = 'BUCKET';
// Call listObjects on the specified bucket
listObjects(bucket, function(err, data) {
  if (err) {
    alert(err);
  } else {
    var listElement = document.getElementById('list');
    var content = 'S3 Objects in ' + bucket + ':n';
    // Print the Key for each returned Object
    content +=  data.Contents.map(function(metadata) {
      return 'Key: ' + metadata.Key;
    }).join('n');
    listElement.innerText = content;
  }
});

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>AWS SDK with webpack</title>
    </head> 
    <body>
        <div id="list"></div>
        <script src="bundle.js"></script>
    </body>
</html>

At this point, we have one JavaScript file that handles making requests to Amazon S3, one JavaScript file that appends a list of S3 object keys to our webpage, and an HTML file that contains a single div tag and script tag. In this last step before our webpage will display data, we’ll use webpack to generate the bundle.js file that the script tag references.

Configuring webpack

You specify configuration options in webpack by using a plain JavaScript file. By default, webpack looks for a file named webpack.config.js in your project’s root directory. Let’s create our webpack.config.js.

webpack.config.js

// Import path for resolving file paths
var path = require('path');
module.exports = {
  // Specify the entry point for our app.
  entry: [
    path.join(__dirname, 'browser.js')
  ],
  // Specify the output file containing our bundled code
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    /**
      * Tell webpack how to load 'json' files because
      * by default, webpack only knows how to handle
      * JavaScript files.
      * When webpack encounters a 'require()' statement
      * where a 'json'' file is being imported, it will use
      * the json-loader.  
      */
    loaders: [
      {
        test: /.json$/, 
        loaders: ['json']
      }
    ]
  }
}

We specified our entry point as browser.js in webpack.config.js. The entry point is the file webpack uses to start searching for imported modules. We also defined the output as bundle.js. This bundle will contain all the JavaScript our application needs to run. We don’t’ have to specify s3.js as an entry point because webpack already knows to include it because it’s imported by browser.js. Also, webpack knows to include the aws-sdk because it was imported by s3.js!

Notice that we specified a loader to tell webpack how to handle importing JSON files, in this case by using the json-loader we installed earlier. By default, webpack only supports JavaScript, but uses loaders to add support for importing other file types as well. The AWS SDK makes heavy use of JSON files, so without this extra configuration, webpack will throw an error when generating the bundle.

Running webpack

We’re almost ready to build our application! In package.json, add "build": "webpack" to the scripts object.

{
  "name": "aws-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.6.1"
  },
  "devDependencies": {
    "json-loader": "^0.5.4",
    "webpack": "^1.13.2"
  }
}

Now run npm run build from the command line and webpack will generate a bundle.js file in your project’s root directory. The results webpack reports should look something like this:

    Version: webpack 1.13.2
    Time: 1442ms
      Asset     Size  Chunks             Chunk Names
    bundle.js  2.38 MB     0  [emitted]  main
      [0] multi main 28 bytes {0} [built]
      [1] ./browser.js 653 bytes {0} [built]
      [2] ./s3.js 760 bytes {0} [built]
       + 343 hidden modules    

 

At this point, you can open index.html in a browser and see output like that in our example.

Give It a Try!

In an upcoming post, we’ll explore some other features of using webpack with the AWS SDK for JavaScript.

We look forward to hearing what you think of this new support for webpack in the AWS SDK for JavaScript v2.6.1! Try it out and leave your feedback in the comments or on GitHub!