aws + serverless + webpack => cannot find module xxx in prod
Asked Answered
K

3

5

I want to create a package to deploy on AWS using serverless and webpack.

In serverless.yml I want to declare all the resources (mainly DynamoDb tables) and the functions. I want to use external node.js libraries.

The folder structure is:

|- serverless.yml
|- webpack.config.js
|- package.json
|- src 
  \ - file1.js
  | - file2.js

Extract from serverless.yml

functions:
  function1:
    handler: src/file1.f1
  function2:
    handler: src/file2.f2

Extract from webpack.congfig.js

module.exports = {
  entry: {
    file1: './src/file1.js',
    file2: './src/file2.js',
  },
  target: 'node',
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loaders: ['json-loader'],
      },
    ],
  },
};

When doing a serverless deploy everything is ok, but when testing the lambda I get an error:

{
  "errorMessage": "Cannot find module '/var/task/src/file1'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._load (module.js:276:25)",
    "Module.require (module.js:353:17)",
    "require (internal/module.js:12:17)"
  ]
}

Can you tell me what am I doing wrong?

Given that I am a newbie with serverless, can you suggest me some "better practice" for the code and development organisation? (serverless and nodejs are imposed, webpack and everything else is not)

Kure answered 20/3, 2017 at 17:49 Comment(0)
L
5

I would recommend using the serverless-webpack plugin. It's hard to tell without seeing the entire serverless.yml file, but I would assume that serverless is trying to deploy the functions listed under functions:, which in your case are written in a syntax not understood by the Node.js 4.3 runtime on AWS lambda.

A good walk through on how to set up a project using the serverless-webpack plugin has been detailed by Serverless Stack:

  1. Setup the Serverless Framework
  2. Add Support for ES6 JavaScript
Lobbyism answered 20/3, 2017 at 21:31 Comment(1)
By reading the links things are getting more clear. I've solved my blocking situation by removing the src/ of handler in serverless.yml file.Kure
U
3

Check the node version

node --version

Run

serverless plugin install --name serverless-webpack

Unsnarl answered 12/3, 2019 at 19:12 Comment(0)
K
1

One possible solution to the error is to remove the src/ from the handler of the function in serverless.yml file.

This approach has the side effect that when automatically creating tests with serverless-mocha-plugin the src/ is no longer considered and it must be added manually in const mod = require('../src/user.js');.

There may be other side effects, absence of evidence is not evidence of absence! :)

So, I'm still looking for a solution without side effects.

Kure answered 21/3, 2017 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.