Serverless-webpack: Unable to import module 'handler': Error revisited

Created on 19 Sep 2017  ยท  44Comments  ยท  Source: serverless-heaven/serverless-webpack

This is a Bug Report

Description

For bug reports:

  • What went wrong?
    I get Unable to import module 'handler': Error when visiting my AWS endpoint
  • What did you expect should have happened?
    Everything works fine locally. Expecting same results.
  • What was the config you used?

serverless.yml:
```service: alerts

custom:
webpackIncludeModules: true;

package:

individually: true

provider:
name: aws
runtime: nodejs6.10

you can overwrite defaults here

stage: dev
region: us-east-1

functions:
alerts:
handler: handler.alerts
events:
- http: ANY alerts
- cors: true

plugins:

  • serverless-webpack
  • serverless-offline
**webpack.config.js**
```const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: slsw.lib.entries,
  externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
  target: 'node',
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/, // in order to ignore built-in modules like path, fs, etc.
        loaders: ['babel-loader'],
        include: __dirname,
      },
    ],
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
};

package.json
```{
"name": "alerts",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "mocha handler.test.js",
"debug:offline": "SLS_DEBUG=* sls offline start",
"debug:deploy": "SLS_DEBUG=* sls deploy --verbose",
"debug": "SLS_DEBUG=* sls deploy --verbose && nodemon sls offline start",
"invoke": "serverless invoke local --function alerts",
"start": "serverless offline start",
"deploy": "sls deploy -f alerts",
"curl:local": "curl http://localhost:3000/alerts -i --header 'Content-Type: application/vnd.api+json' --header 'Accept: application/vnd.api+json'",
"curl:local:paged": "curl http://localhost:3000/alerts -i -G -d page[offset]=2 -d page[limit]=10 --header 'Content-Type: application/vnd.api+json' --header 'Accept: application/vnd.api+json'",
"git:push": "git push https://git-codecommit.us-east-1.amazonaws.com/v1/repos/alerts --all",
"mockAPI": "http-server -p 1980",
"ngrok:start": "nodemon --inspect ./ngrok/request.js --exec babel-node",
"ngrok:connect": "nodemon ./ngrok/connect.js --exec babel-node",
"ngrok": "ngrok http 3000"
},
"author": "James Fishwick",
"license": "ISC",
"engines": {
"node": "6.10.3"
},
"dependencies": {
"babel-runtime": "6.26.0",
"bluebird": "3.5.0",
"dotenv": "4.0.0",
"elasticsearch": "13.3.1",
"http-aws-es": "3.1.0",
"json-api-serializer": "1.9.1",
"ramda": "0.24.1",
"request": "2.81.0",
"request-promise": "4.2.1",
"uuid": "3.1.0"
},
"devDependencies": {
"aws-sdk": "2.118.0",
"babel-cli": "6.26.0",
"babel-core": "6.26.0",
"babel-eslint": "7.2.3",
"babel-loader": "7.1.2",
"babel-plugin-ramda": "1.4.3",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-plugin-transform-runtime": "6.23.0",
"babel-preset-env": "1.6.0",
"chai": "4.1.2",
"eslint": "4.7.1",
"eslint-config-airbnb-base": "12.0.0",
"eslint-plugin-async-await": "0.0.0",
"eslint-plugin-babel": "4.1.2",
"eslint-plugin-chai-expect": "1.1.1",
"eslint-plugin-import": "2.7.0",
"eslint-plugin-mocha": "4.11.0",
"eslint-plugin-node": "5.1.1",
"eslint-plugin-prefer-object-spread": "1.2.1",
"http-server": "0.10.0",
"mocha": "3.5.3",
"ngrok": "2.2.22",
"nodemon": "1.12.1",
"npm-run-script": "0.0.4",
"pre-commit": "1.2.2",
"serverless": "1.22.0",
"serverless-offline": "3.16.0",
"serverless-webpack": "^3.0.0-rc.1",
"webpack": "3.6.0",
"webpack-node-externals": "1.6.0"
}
}

* What stacktrace or error message from your provider did you see?
```Serverless: Bundling with Webpack...
babel-preset-env: `DEBUG` option

Using targets:
{
  "node": "6.10"
}

Modules transform: commonjs

Using plugins:
  transform-exponentiation-operator {"node":"6.10"}
  transform-async-to-generator {"node":"6.10"}
  syntax-trailing-function-commas {"node":"6.10"}
Time: 864ms
     Asset     Size  Chunks             Chunk Names
handler.js  13.3 kB       0  [emitted]  handler
   [0] external "dotenv" 42 bytes {0} [not cacheable]
   [1] ./handler.js 1.43 kB {0} [built]
   [2] ./main.js 6.96 kB {0} [built]
   [3] external "babel-runtime/core-js/json/stringify" 42 bytes {0} [not cacheable]
   [4] external "babel-runtime/helpers/extends" 42 bytes {0} [not cacheable]
   [5] external "babel-runtime/helpers/asyncToGenerator" 42 bytes {0} [not cacheable]
   [6] external "url" 42 bytes {0} [not cacheable]
   [7] external "bluebird" 42 bytes {0} [not cacheable]
   [8] external "request-promise" 42 bytes {0} [not cacheable]
   [9] external "uuid/v5" 42 bytes {0} [not cacheable]
  [10] ./serializer.js 724 bytes {0} [built]
  [11] external "json-api-serializer" 42 bytes {0} [not cacheable]
  [12] ./pplog.js 409 bytes {0} [built]
  [13] external "util" 42 bytes {0} [not cacheable]
Serverless: Fetch dependency graph from /Users/jamesfishwick/Documents/alerts/package.json
Serverless: Packing external modules: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]
Serverless: Package took [4104 ms]
Serverless: Copy modules: /Users/jamesfishwick/Documents/alerts/.webpack/service [1921 ms]
Serverless: Prune: /Users/jamesfishwick/Documents/alerts/.webpack/service [1725 ms]
Serverless: Zip service: /Users/jamesfishwick/Documents/alerts/.webpack/service [3625 ms]
Serverless: Packaging service...
Serverless: Remove /Users/jamesfishwick/Documents/alerts/.webpack
Serverless: Invoke aws:package:finalize
Serverless: Invoke aws:common:moveArtifactsToPackage
Serverless: Invoke aws:common:validate
Serverless: Invoke aws:deploy:deploy
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
CloudFormation - UPDATE_IN_PROGRESS - AWS::CloudFormation::Stack - alerts-dev
CloudFormation - UPDATE_IN_PROGRESS - AWS::Lambda::Function - AlertsLambdaFunction
CloudFormation - UPDATE_COMPLETE - AWS::Lambda::Function - AlertsLambdaFunction
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1505851381038
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1505851381038
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Deployment - ApiGatewayDeployment1505851381038
CloudFormation - UPDATE_COMPLETE_CLEANUP_IN_PROGRESS - AWS::CloudFormation::Stack - alerts-dev
CloudFormation - DELETE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1505851297621
CloudFormation - DELETE_COMPLETE - AWS::ApiGateway::Deployment - ApiGatewayDeployment1505851297621
CloudFormation - UPDATE_COMPLETE - AWS::CloudFormation::Stack - alerts-dev
Serverless: Stack update finished...
Serverless: Invoke aws:info
Service Information
service: alerts
stage: dev
region: us-east-1
stack: alerts-dev
api keys:
  None
endpoints:
  ANY - https://xxx.execute-api.us-east-1.amazonaws.com/dev/alerts
functions:
  alerts: alerts-dev-alerts

Stack Outputs
AlertsLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:xxx:function:alerts-dev-alerts:6
ServiceEndpoint: https://xxx.execute-api.us-east-1.amazonaws.com/dev
ServerlessDeploymentBucketName: alerts-dev-serverlessdeploymentbucket-18jzstz1xn4qa

Serverless: Publish service to Serverless Platform...
Service successfully published! Your service details are available at:
https://platform.serverless.com/services/two7sclash/alerts
Serverless: Invoke aws:deploy:finalize
Serverless: Removing old service versions...

then:

curl https://xxx.execute-api.us-east-1.amazonaws.com/dev/alerts gives {"message": "Internal server error"}

Stack trace is:

Unable to import module 'handler': Error
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /var/task/node_modules/request-promise/lib/rp.js:11:16
at module.exports (/var/task/node_modules/stealthy-require/lib/index.js:62:23)
at Object.<anonymous> (/var/task/node_modules/request-promise/lib/rp.js:10:19)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/handler.js:370:18)
at __webpack_require__ (/var/task/handler.js:20:30)
at Object.<anonymous> (/var/task/handler.js:162:17)
at __webpack_require__ (/var/task/handler.js:20:30)
at Object.<anonymous> (/var/task/handler.js:80:14)
at __webpack_require__ (/var/task/handler.js:20:30)
at /var/task/handler.js:63:18
at Object.<anonymous> (/var/task/handler.js:66:10)

Similar or dependent issue(s):
*#43

Additional Data

  • Serverless-Webpack Version you're using: ^3.0.0-rc.1
  • Webpack version you're using: 3.6.0
  • Serverless Framework Version you're using: 1.22.0
  • Operating System: macOS Sierra 10.12.6 16G29 x86_64
duplicate documentation issuunder-investigation

Most helpful comment

@jkruse14: Unable to import module 'handler' usually occurs due to missing dependencies. The error is misleading in this case, but you can think of it as Lambda (the Node.js runtime) trying to import your handler. If there are any syntax errors, missing modules or similar, Unable to import module 'handler' gets thrown.

To debug this, do a serverless package and check what is packaged in the zip-archive (in the .serverless directory). Make sure that everything you import or require in your bundle is available in the node_modules directory within the zip-archive.

I suppose you can try extracting the zip-archive and do a node bundle.js where your working directory is where the node_modules directory is. You should then get similar errors to Unable to import module 'handler', but hopefully with more information.

All 44 comments

Hi @two7sclash . Thanks for submitting the issue and the very detailed information ๐Ÿ‘ .

After a very quick check of the configuration you posted I see nothing obvious at the first sight that could cause the problem. Can you try to do a serverless package and check the created zip file in .serverless, especially what is packaged in there (the zip is the same as the one deployed to AWS)?
Can you also check, what exactly the CloudWatch logs tell about the error (the curl call attempt should be logged and lead to a more detailed error there).

@HyperBrain added the stack trace from CloudWatch logs.

@HyperBrain inside the package I see: handler.js, node_modules, package-lock.json, package.json. Inside the handler file, I see module.exports.alerts...

Ok. That helps. There is a dependency missing in the package: /var/task/node_modules/request-promise/lib/rp.js:11:16 that is needed by request-promise. I checked the request-promise package.json and the package has a peer dependency: request@^2.34.

There is currently a bug #223 that you hit here.
With the released 3.0.0 you have to do a require('request') as workaround as mentioned in #223.

With version 3.1.0 which is already in master you can do

custom:
  webpackIncludeModules:
    forceInclude:
      - request

Sorry for the inconvenience. I will try to implement a bugfix for #223 as soon as possible.

now in main.js (which gets bundled into the handler) I have:

```require('dotenv').config();
require('request');
const url = require('url');
const Promise = require('bluebird');
const request = require('request-promise');
const uuidv5 = require('uuid/v5');

const serializer = require('./serializer');
const pplog = require('./pplog');

New stack trace is:

module initialization error: TypeError
at urlParse (url.js:75:5)
at Object.urlResolve [as resolve] (url.js:631:10)
at Object. (/var/task/handler.js:170:21)
at __webpack_require__ (/var/task/handler.js:20:30)
at Object. (/var/task/handler.js:80:14)
at __webpack_require__ (/var/task/handler.js:20:30)
at /var/task/handler.js:63:18
at Object. (/var/task/handler.js:66:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
```

I'm working on a bugfix for #223 right now. Please be patient - should be available soon

Just finished the implementation. Needs some local tests. Then I'll prepare a PR that you can test with.

Serverless: Adding peer dependencies for request-promise
Serverless: Packing external modules: request-promise@^4.2.1, request@^2.82.0, b
luebird@^3.5.0

Looks good so far. However I have to check for any edge cases -> as soon as these work I'll publish the PR.

@two7sclash Can you try with the plugin version from #231 with the initial project setup and report if it solves the problem?

@HyperBrain sorry wasn't being impatient, was just trying with require('request'); and const request = require('request-promise'); -- the work around you originally suggested.

I pulled down your PR and, same error as when I use the work around:

module initialization error: TypeError
at Url.parse (url.js:81:11)
at urlParse (url.js:75:5)
at Object.urlResolve [as resolve] (url.js:631:10)
at Object.<anonymous> (/var/task/handler.js:169:21)
at __webpack_require__ (/var/task/handler.js:20:30)
at Object.<anonymous> (/var/task/handler.js:80:14)
at __webpack_require__ (/var/task/handler.js:20:30)
at /var/task/handler.js:63:18
at Object.<anonymous> (/var/task/handler.js:66:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)

So the "request" issue is resolved methinks?

This error seems to imply that webpack isn't handling the native url module for node v6 correctly. Or am I misreading? Again, everything works fine locally.

No problem ๐Ÿ˜„ , I think the peer dependency issue is then resolved with the PR as request is added now as it is added automatically.

You could be right, that the issue has something to do with the handling of the native url module. Which Node version do you use locally? Maybe the Node version used locally and on AWS Lambda are different, so that the compiled code breaks online - just a guess.

According to the AWS docs:

AWS Lambda supports the following runtime versions:
Node.js โ€“ v4.3.2 and 6.10.3
Java โ€“ Java 8
Python โ€“ Python 3.6 and 2.7
.NET Core โ€“ .NET Core 1.0.1 (C#)

Can you try to use Node 6.10.3 locally so that it exactly reflects the AWS runtime?

yeah, I'm already using 6.10.3 locally :/ no problems using serverless-offline against the webpacked handler

Just checked the callstack again: It seems that the url module has been loaded and the crash appears within the module and not your code. That hints me to something with the parameters of Url.parse() being wrong. Can you double check if the passed parameters are as expected? I'm not sure if serverless-offline or the Serverless framework itself would hide these errors. I know that the Serverless framework implements exception handlers, but I do not know how deep that integrates.

Just cleared the flags as the peer dependency require is solved by #231 .
The crash in Url.parse() has to be investigated and analyzed.

taking a look this AM, more soon.

problem was that the url module was choking on const selfApi = url.resolve(process.env.API_URL, 'alerts');. I simply wasn't doing env variables correctly. Read https://medium.com/@purplecones/serverless-environment-variables-4ec818f67388 and all is well.

I am getting roughly the same error and it happens if I have _any_ require statement at all.

@stevenmwade Could you elaborate on this a bit more and post a code sample (configs)?

@HyperBrain I'm getting this issue and have tried all the obvious fixes. I'm on v3.1.2. Is there any more stable version I should switch to?

** this issue only cropped up when I switched to using the webpackIncludeModules custom switch due to a mySql incompatibility, if that helps.

Can you post the function definitions and the webpackIncludeModules part of your serverless.yml and your webpack.conf.js?

If you do not set webpackIncludeModules at all, there will be NO module packaging. 3.1.2 is stable, and there are currently no known issues in that area. It should be merely a configuration issue, but we can find that out by looking at the files.

Sure thing!

serverless.yml > functions ::

functions:
  foo_adapter:
    handler: functions/foo_adapter/foo_adapter.handler
    name: foo_adapter__${self:custom.myStage}
    package:
      include:
        - functions/foo_adapter/**

serverless.yml >> custom ::

custom:
  webpackIncludeModules: true

webpack.dev.config.js

module.exports = {
  devtool: 'sourcemap',
  entry: slsw.lib.entries,
  target: 'node',
  externals: [nodeExternals()],
  plugins: [
    new webpack.LoaderOptionsPlugin({
      debug: true
    }),
    new webpack.DefinePlugin({
      '__DEV__': true,
      'process.env.NODE_ENV': JSON.stringify('dev')
    }),
    new Dotenv({
      path: './dev.env'
    }),
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false
    })
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['es2015'],
              compact: false,
              sourceMaps: true
            }
          }
        ],
      }
    ]
  },
  output: {
    devtoolModuleFilenameTemplate: '[absolute-resource-path]',
    devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]',
    libraryTarget: 'commonjs',
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    modules: [
      path.resolve(__dirname, './libs'),
      path.resolve(__dirname, './node_modules')
    ]
  }
}

Project structure ::

  functions
    foo_adapter
      foo_adapter.js

Cloudwatch logs errror ::

Unable to import module 'functions/foo_adapter/foo_adapter': Error
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/functions/foo_adapter/foo_adapter.js:1:63)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Completely agree that it must be a config issue but this was working before I switched over to webpackIncludeModules: true as I said above. Thanks again for taking a look.

Oh man you must get tired of this. I had added the banner plugin for sourcemaps and that was not a dependency that was included in the build, but present in my local... Sorry for that @HyperBrain

    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false
    })

feel free to mark my issue as resolved.

Hey @btburton42 , even if some issues turn out to be a missing configuration, it is quite helpful to have them documented here in the GitHub issues. This will help others who run into the same to have a variety of possible things to check ๐Ÿ‘ .

However a Wiki might be better to collect them and extract them as Problem->Solution pairs from the issues. As I'm not very used in how to setup a good wiki in GitHub, I could need some help there ๐Ÿ˜„ .

I wish to add my name to the list of folks struggling with this issue. It runs fine locally, but gives this error after deploying to AWS. All of the source is here: https://github.com/RALifeCoach/lb-data-engine.git. The actual error is:

CONFIGURATIONUnable to import module 'leaderboard': Error at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.defineProperty.value (/var/task/leaderboard.js:299:18) at __webpack_require__ (/var/task/leaderboard.js:20:30) at Object.<anonymous> (/var/task/leaderboard.js:73:16) at __webpack_require__ (/var/task/leaderboard.js:20:30) at /var/task/leaderboard.js:63:18 at Object.<anonymous> (/var/task/leaderboard.js:66:10)

First occurence: 2017-11-14T14:33:13+00:00

ID: aa35537f7042e676e61f47a1231a1cdf
Exception:

Unable to import module 'leaderboard': Error
            at Function.Module._resolveFilename (module.js:469:15)
            at Function.Module._load (module.js:417:25)
            at Module.require (module.js:497:17)
            at require (internal/module.js:20:19)
            at Object.defineProperty.value (/var/task/leaderboard.js:299:18)
            at __webpack_require__ (/var/task/leaderboard.js:20:30)
            at Object.<anonymous> (/var/task/leaderboard.js:73:16)
            at __webpack_require__ (/var/task/leaderboard.js:20:30)
            at /var/task/leaderboard.js:63:18
            at Object.<anonymous> (/var/task/leaderboard.js:66:10)

Hi @RALifeCoach , thanks for the post. I will check the source. It looks like there is something wrong with the webpack configuration (so that it did not bundle/reference a module correctly).

What I saw on the first sight is this:

plugins:
  - serverless-offline
  - serverless-webpack

You have to revert the order - to make offline work correctly, webpack has to be listed before offline, because that detemines the order of execution (see also the README).

I'll let you know if I found something.

Thanks for looking at this so quickly. I appreciate your time in this matter.

I have reversed the order of the plug-ins. However, the error is still happening.

@RALifeCoach I already have an idea, why. You should use the entry auto-resolution with slsw.lib.entries (for details see the README) and set the outputname then to [name].js.

I can try to submit a PR for your repo tomorrow if that's ok for you.

Thanks, I will try that and report back to you.

On Wed, Nov 15, 2017 at 6:17 AM, Frank Schmid notifications@github.com
wrote:

@RALifeCoach https://github.com/ralifecoach I already have an idea,
why. You should use the entry auto-resolution with slsw.lib.entries (for
details see the README) and set the outputname then to [name].js.

I can try to submit a PR for your repo tomorrow if that's ok for you.

โ€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless-heaven/serverless-webpack/issues/230#issuecomment-344432594,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ADrayP-MuQX-cXaBN_PwEfx1sNMWfXhHks5s2h-DgaJpZM4Pc9Wx
.

--
Christopher Oliphant
+1 647 972 4549

I made those 2 changes to the webpack.config.js. I am still getting an error. However, it is nice to know I am moving forward and clearing up the obvious problems of one who fails to read the documentation carefully enough.

Can you post the current webpack.config? ... and the error (if it is different than before) ๐Ÿ˜„

My changes to webpack config and serverless.yml have been pushed.

On Wed, Nov 15, 2017 at 6:31 AM, Frank Schmid notifications@github.com
wrote:

Can you post the current webpack.config?

โ€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless-heaven/serverless-webpack/issues/230#issuecomment-344435474,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ADrayH8iYpIU94QqK41oj2XIQdcgGcJnks5s2iK5gaJpZM4Pc9Wx
.

--
Christopher Oliphant
+1 647 972 4549

Thanks

@RALifeCoach I think I found your remaining problem. Just checked out the repo and tried. The external modules were not packaged - the ones detected by node-externals.
The solution is to enable the plugin's external module packaging in serverless.yml:

# serverless.yml
custom:
  webpackIncludeModules: true

Then the output should be functional.

The packaged Lambda ZIP then contains everything:
image

That fixed it. You are wonderful. Thank-you.

On Wed, Nov 15, 2017 at 7:28 AM, Frank Schmid notifications@github.com
wrote:

@RALifeCoach https://github.com/ralifecoach I think I found your
remaining problem. Just checked out the repo and tried. The external
modules were not packaged - the ones detected by node-externals.
The solution is to enable the plugin's external module packaging:

custom:
webpackIncludeModules: true

Then the output should be functional.

โ€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless-heaven/serverless-webpack/issues/230#issuecomment-344446193,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ADrayNwXABxPucMkmcXJN1JMgxE7O-b5ks5s2jAqgaJpZM4Pc9Wx
.

--
Christopher Oliphant
+1 647 972 4549

@RALifeCoach You're welcome

I apologize for resurrecting this issue, but I'm facing (what looks to be) the same thing. I'm using serverless aws with webpack and typescript. It was working just a few days ago, and I'm not sure what I changed that caused this to happen. Everything works find locally.

webpack.confi.js

const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');

console.log('slsw lib entries', slsw.lib.entries);
module.exports = {
    entry: slsw.lib.entries,
    resolve: {
        extensions: [
            '.js',
            '.jsx',
            '.json',
            '.ts',
            '.tsx',
        ],
    },
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, '.webpack'),
        filename: '[name].js',
    },
    target: 'node',
    externals: [nodeExternals({
        whitelist: ['/@types/', '/^lodash/', 'bluebird', 'request', 'request-promise', 'pg'],
    })], // in order to ignore all modules in node_modules folder
    module: {
        loaders: [{
            test: /\.ts(x?)$/,
            loader: 'ts-loader',
        }],
    },
};

serverless.yml (snippet)

provider:
  name: aws
  runtime: nodejs6.10
  profile: myprofile
package:
  excludeDevDependencies: true
  exclude:
    - environment/**
    - .nyc_output/**
    - .vscode/**
    - .eslintrc
    - coverage/**
    - config/**
    - deploy-script*
    - package.json
    - README.md
    - scripts/**
    - serverless-offline*
    - serverless-environment*
    - src/test/**
    - swagger.y*
    - tsconfig.json
    - node_modules/serverless*/**
    - web*.env
custom:
  webpackIncludeModules:
    forceInclude:
      - request
      - request-promise
      - pg

functions
  get-teams:
    handler: src/controllers/team-controller.get
    events:
      - http:
          method: get
          path: teams
          cors: true

structure:

- controllers
-- team-controller.ts

Please let me know what other information I can provide.

Cheers,
Justin

@jkruse14: Unable to import module 'handler' usually occurs due to missing dependencies. The error is misleading in this case, but you can think of it as Lambda (the Node.js runtime) trying to import your handler. If there are any syntax errors, missing modules or similar, Unable to import module 'handler' gets thrown.

To debug this, do a serverless package and check what is packaged in the zip-archive (in the .serverless directory). Make sure that everything you import or require in your bundle is available in the node_modules directory within the zip-archive.

I suppose you can try extracting the zip-archive and do a node bundle.js where your working directory is where the node_modules directory is. You should then get similar errors to Unable to import module 'handler', but hopefully with more information.

Thanks @martinjlowm! I had two modules which I must not have installed with the --save recently. I added those and everything is working - thanks for your help!

I had this same issue and the only way to fix it was changing to node v6 (via nvm) to compile.

ListAllObjects_test.zip

Hi I need a help, Am new to this node.js and aws lambda, i am just trying a simple way to list out the S3 objects, but am getting the exception as given below

Unable to import module 'index': Error
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)

Can someone help me on this.

If i edit the working aws template then also i receive same error. Unable to understand.
ListAllObjects_test.zip

Same issue
Need help .
Stuck badly

Just FWIW... I've also been fighting this issues for some hours (which appeared after adding babel to my build chain btw.). Earlier I had the following in my Lambda handler:

module.exports.getVersion = async event => {
    return {
    statusCode: 200,
    body: JSON.stringify({"version":1.2})
  };
};

Adding babel to webpack and the code above stopped working, TypeError: Cannot set property 'getVersion' of undefined

Changing the handler method signature to export const getVersion ... and it works again. Just if someone has the same issue..

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tommedema picture tommedema  ยท  4Comments

bericp1 picture bericp1  ยท  5Comments

deftomat picture deftomat  ยท  5Comments

slushnys picture slushnys  ยท  5Comments

serverlesspolska picture serverlesspolska  ยท  4Comments