Use aws-sdk with Webpack

October 19th, 2015

If you are using webpack and you thought you could just import AWS from 'aws-sdk' or require('aws-sdk')... you are out of luck. You'll see one of these errors:

Module not found: Error: Cannot resolve module 'fs' in ...

the request of a dependency is an expression

region_config.json Line 2: Unexpected token : You may need an appropriate loader to handle this file type.

Uncaught Error: Cannot find module "./region_config.json"

AWS.S3 is not a function AWS.Firehose is not a function AWS.EC2 is not a function ... etc

What Not To Do

Don't take these errors at face value and go installing the fs module or adding the json-loader. It won't help.

The aws-sdk module passes expressions to require(), and webpack does not support that - whether you install fs or not.

The Solution

Use the pre-built version of the aws-sdk. Using it sidesteps these require() issues because all the dependencies have been included in a single file.

In the aws-sdk node module, the pre-built file is located at dist/aws-sdk.js. You can import it with require('aws-sdk/dist/aws-sdk').

There's one more problem - the pre-built file doesn't export any variables, but instead just adds AWS to the window object.

Here's the full solution:

var AWS = window.AWS;

ES6 version:

import "aws-sdk/dist/aws-sdk";
const AWS = window.AWS;

By the way, I would be the first to agree that this solution isn't ideal. If you don't like this solution, you can file an issue on the 'aws-sdk-js' repo, but they probably won't fix it.

Fixing the Warning

Everything should be working now, but Webpack still has one more complaint:

This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.

To fix this, you'll need to add the noParse setting in your webpack.config.js:

module: {
  noParse: [/aws\-sdk/];

The above tells Webpack that this file has already been processed and it should be included as-is. That's it!