Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack and AWS Lambda issue - handler missing on module

I'm using ES6, babel and Webpack 2 to bundle an AWS Lambda. I am then running/testing it using AWS SAM local. I get the following error when I hit the api -

Handler 'handler' missing on module 'dist/main'

Here is my webpack.config.js -

const path = require('path');

module.exports = {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: [require('babel-plugin-transform-flow-strip-types')],
          presets: [
            [
              'env',
              {
                target: { node: 6.10 }, // Node version on AWS Lambda
                useBuiltIns: false,
                loose: false,
                exclude: [],
                debug: false
              },
            ],
          ],
        },
      }
    ],
  }
};

And here is a snippet of the compiled main.js -

/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.handler = handler;

var _amazonCognitoIdentityJs = __webpack_require__(60);

var _aws_profile = __webpack_require__(290);

// A signin Lambda function
function handler(event, context, callback) {
        switch (event.httpMethod) {
        case "GET":

A little background.... this is a Lambda I initially wrote NOT in ES6 and not bundling using Webpack and it was working. I now need for it to be in ES6 and work with Webpack. N.B. this is Webpack 2

Much thanks...

like image 993
SamBrick Avatar asked Nov 13 '17 16:11

SamBrick


2 Answers

To fix this issue I had to specify a library property and change the libraryTarget to commonjs2. The webpack.config.js file output now looks like this -

output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    library: 'main',
    libraryTarget: 'commonjs2'
  },
like image 123
SamBrick Avatar answered Nov 04 '22 02:11

SamBrick


I ran into this issue as well. However, I believe my situation was the inverse of what SamBrick shares. I was moving from transpiling ES6 with babel to run on lambda/node 6.10 to no transpiling and targeting lambda/node 8.10. Removing the library field and changing to the libraryTarget: 'commonjs' solved the problem for me.

Props to this guy: https://gist.github.com/nirnanaaa/d7f40deb38f1cf7f931dc7ef0c582bf0

like image 9
Ted_Zactly Avatar answered Nov 04 '22 03:11

Ted_Zactly