AWS Developer Tools Blog
Using webpack and the AWS SDK for JavaScript to Create and Bundle an Application – Part 2
In the previous post in this series, we introduced how to use webpack and the AWS SDK for JavaScript to create and bundle an application.
In this post, we’re going to dig a little bit into other features, such as creating bundles with only the AWS services you need, and generating bundles that will also run in Node.js.
Importing Individual Services
One of the benefits of using webpack is that it can parse your dependencies and include only the code your application needs. You might have noticed that in our previous project, webpack generated a bundle that was 2.38 MB. That’s because webpack is currently importing the entire AWS SDK for JavaScript based on the following statement in s3.js
.
var AWS = require('aws-sdk');
We can help webpack include only the Amazon S3 service if we update our require statement to the following:
var S3 = require('aws-sdk/clients/s3');
All the AWS SDK configuration options that are available using AWS.config can also be set when instantiating a service. We can still access the AWS
namespace to set global configuration across all services with the following:
var AWS = require('aws-sdk/global');
Here’s an example of what our s3.js
file would look like with these changes.
s3.js
Now when we run npm run build
, webpack reports the following:
Now, our generated bundle has dropped from 2.38 MB to 797 KB.
You can configure webpack to minify the generated code to reduce the final size even more!
Generating Node.js Bundles
You can use webpack to generate bundles that run in Node.js by specifying target: 'node'
in the configuration. This can be useful when you’re running a Node.js application in an environment where your disk space is limited.
Let’s update our project to build a Node.js bundle by creating a file called node.js
. This file will be nearly identical to browser.js
, however, instead of listing S3 objects in the DOM, it will output them to the console.
node.js
Next, we’ll update our webpack.config.js
to use node.js
as the entry point, and add a new field, target: "node"
to let webpack know it should generate a Node.js bundle.
webpack.config.js
Run npm run build
to generate the new bundle. You can test this code on the command line by running node bundle.js
. This should output a list of S3 objects in the console!
Give It a Try!
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!