Code Monkey home page Code Monkey logo

serverless-webpack's People

Contributors

asprouse avatar ceilfors avatar cfroese avatar coyoteecd avatar cyyuen avatar dependabot[bot] avatar designfrontier avatar dwelch2344 avatar franciscocpg avatar francisu avatar github-actions[bot] avatar gregoirevda avatar hassankhan avatar hieuunguyeen avatar hyperbrain avatar j0k3r avatar jamesmbourne avatar janicduplessis avatar liron-strattic avatar medikoo avatar miguel-a-calles-mba avatar neilime avatar nidin avatar pcowgill avatar rogersgt avatar stevemao avatar thenikso avatar todda00 avatar vicary avatar vkkis93 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-webpack's Issues

invoke doesn't work if the file isn't in the project root (for multiple entries)

I was having problems invoking my functions after using the plugin, so I took further steps to better isolate the problem.
I cloned the repository and tried the "multiple-entries" example, everything works fine.
I then moved one of the functions inside a folder "functions", and updated serverless.yaml accordingly:

  first:
    handler: functions/first.hello

Same for webpack.config.js:

  entry: {
    first: './functions/first.js',
    second: './second.js'
  },

After deployment, if I sls invoke local -f first everything works, if I sls invoke -f first I get an error:

{
    "errorMessage": "Cannot find module '/var/task/functions/first'",
    "errorType": "Error",
    "stackTrace": [
        "Module.require (module.js:353:17)",
        "require (internal/module.js:12:17)"
    ]
}

With the second function, in the project root, everything works as expected.
Also, if I disable the plugin, everything work as expected.
Am I missing something or is there a bug?

Thank you! :)

Take integration into account when using serve command

Hey thanks for the great work with this!

Serverless have made Lambda Proxy Integration the default - see https://serverless.com/framework/docs/providers/aws/events/apigateway. This means that the full content of the HTTP request (headers, body, etc.) is passed to the Lambda function and the full response (headers, status code, body) must be returned from the Lambda function.

As far as I can see serverless webpack serve does not take this into account. This causes a mismatch between what the event object contains when running locally and when running on AWS. I'm using serverless-webpack in a project which uses the lambda-proxy integration and have worked around this by utilising NODE_ENV (e.g. https://github.com/jch254/serverless-es6-dynamodb-webapi/blob/master/src/handler.js#L125).

It'd be great to support both integrations.

Cannot POST to local simulated API Gateway ?

I've executed this command:

serverless webpack serve

Output is like:

c:\my-folder>serverless webpack serve
Serverless: Serving functions...
ts-loader: Using [email protected] and c:\my-folder\tsconfig.json

However when using Postman to post to http://localhost:8000 with correct Accept and Content-Type, I get an error in Postman:

Cannot POST /

I checked that it's listening to port 8000 on my sytstem.

[1.0.0-rc3] 'core undefined' error on sls webpack serve

Hi, love the project! Just upgraded to the newest version so I could check out the integration with serverless-offline and I get the following error:

Serverless: Serving functions...
  GET - http://localhost:8000/myapp
  GET - http://localhost:8000/myapp/resource1
  GET - http://localhost:8000/myapp/resource2
core undefined
core undefined
core undefined

All I did was update from 1.0.0-rc2 to rc3, and downgrading resolves the problem.

serverless include/exclude is not processed

as i have seen there are/were already issues where part of this problem were discussed.

does it make sense at all? in my special case i needed the package.json (and especially the name and version)-property inside AWS.

i achieved it using the existing packExternalModules-functionality and using the existing package.json-Content without all dependencies for the tmpPackageJson. see commit here

This works for my special Case (maybe it is generally i good way to do this, if you too think i can provide a pull request for this).

What would be better i think is to make the include from serverless work. If you think this would make sense, i'm willing to contribute and make a pull request for that one. just let me know in this issue!

Typescript

Hi,

Im trying to use your excellent plugin with typescript.

My package.json:

{
  "name": "my-second-service",
  "version": "1.0.0",
  "description": "Me messing around with lambdas",
  "private": true,
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Mike cann",
  "license": "MIT",
  "devDependencies": {
    "aws-sdk-typescript": "0.0.3",
    "serverless-webpack": "^1.0.0-beta.2",
    "ts-loader": "^0.8.2",
    "typescript": "^1.8.10",
    "webpack": "^1.13.1"
  },
  "dependencies": {}
}

My webpack.config.js:

module.exports = {
  entry: './handler.ts',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' }
    ]
  }
};

in serverless.yml:

service: my-second-service

plugins:
  - serverless-webpack

provider:
  name: aws
  runtime: nodejs4.3

functions:
  hello:
    handler: handler.hello
    events:
        - http:
            path: greet
            method: get

and handler.ts:

export const hello = (event, context, cb) => cb(null,
  { message: 'Go Serverless Webpack v1.0! Your function executed successfully!', event }
);

Now this all runs fine when doing serverless webpack serve I am able to test in the browser. But when I deploy it to AWS I get errors like:

{"errorMessage":"Cannot find module 'handler'","errorType":"Error","stackTrace":["Module.require (module.js:353:17)","require (internal/module.js:12:17)"]}

So I ran serverless webpack --out dist so I could inspect the contents. For some reason instead of "handler.js" being in there like I expected, there was "handler.ts", so no wonder im getting an error about cannot find module.

So I modified my webpack.config.js to be:

module.exports = {
  entry: './handler.ts',
  output: {
    filename: "handler.js"
  },
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' }
    ]
  }
};

when running serverless webpack --out dist I now correctly get handler.js in the dist dir but when I try to run serverless webpack serve or deploy I get the following console error:

  Assertion Error ----------------------------------------

     rimraf: missing path

     For debugging logs, run again after setting SLS_DEBUG env var.

  Get Support --------------------------------------------
     Docs:          v1.docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues

     Please report this error. We think it might be a bug.

Any ideas whats going on here?

Cheers.

Implement a webpack watch command over all functions

As I mentioned in #55, with the serverless-offline plugin the current Simulate API Gateway locally feature is pretty outdated and doesn't have so reach features as serverless-offline has. Nevertheless this plugin is great for bundling functions with webpack.
By working with this plugin and serverless-offline the only feature I miss is a watcher for changes in functions code with auto rebuilding.
This plugin has a watch command for separate function only. And a serve is overkill as it not only watches changes but hosts functions too.
It would be great to have a command for watching changes of the whole project code. In this case we probably want the plugin to run separately from serverless-offline so both can do their jobs.

Shorthand http event syntax throws "Cannot read property 'toLowerCase' of undefined"

serverless-webpack 1.0.0-rc.2 at this line assumes a serverless.yml event format like this:

functions:
  myfunction:
    handler: handlers.myfunction
    events:
      - http:
          method: POST       # method and path are
          path: myfunction   # defined as separate keys

However using the http event string shorthand...

functions:
  myfunction:
    handler: handlers.myfunction
    events:
      - http: POST myfunction

...throws the error...

Cannot read property 'toLowerCase' of undefined
... serverless-webpack/lib/serve.js:45:40 ...

toUpperCase not found

There is a case when the http event comes back unparsed as a single string, this quick check (between for and const method) should alleviate:

serve.js - line: 43:

for (let httpEvent of funcConf.events) {

    if(typeof httpEvent === 'string'){
      var split = httpEvent.split(' ');
      httpEvent = {
        path: split[1],
        method: split[0],
      }
    }

    const method = httpEvent.method.toLowerCase();
    let endpoint = `/${httpEvent.path}`;

V3: Unable to import module 'handler': Error

I often have this error and I never know where to look at to fix the issue. Is there a way/tool to have more information about the error ?

I have the SLS_DEBUG set to true but it doesn't help.

Unable to import module 'handler': Error
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/var/task/handler.js:373:19)
    at __webpack_require__ (/var/task/handler.js:20:30)
    at Object.<anonymous> (/var/task/handler.js:53:19)
    at __webpack_require__ (/var/task/handler.js:20:30)
    at /var/task/handler.js:40:18
    at Object.<anonymous> (/var/task/handler.js:43:10)

Thank you very much!
Thierry

Calling a `sls webpack serve` endpoint throws "TypeError: func is not a function"

func represents the handler function defined in serverless.yml.

It seems this block initially sets handlerFunc (later referred to as func) to null. Setting it to funcConf.handler.split('.')[0] fixes the issue.

However, it looks like we have webpack setting the handlerFunc later on. I'm not sure what loadHandler does, or why it's important.

I searched the webpack docs and source but couldn't find reference to a loadHandler.

Does not work with package:individually:true

  1. I see Error Serverless: Uploading function .zip files to S3...

    Error --------------------------------------------------
    ENOENT: no such file or directory .webpack.serverless\servicename-funtionName.zip'

  2. In zip archive I see all entry points but want only required by function handler in serverless.yml

Work with serverless-offline plugin

The serverless-offline plugin has a large support for handling most of the emulation of API Gateway. It would be great if I could use this plugin with that one to get a great offline experience and the great processing experience I am having with this plugin.

Not sure if this is something you can work with the author of that plugin on.

Allow content-type aliases for body parser

Seems like body parser correctly uses bodyParser.json, however we're not allowed to pass an alias to specify a specific content type should be parsed as JSON. As a result most webhook APIs that specify this hypermedia-like content-type (e.g application/vendorname+vendorversionmaybe-vendortypemaybe+json) result in an empty body for sls webpack serve's express app. This library should support this use case by either:

  • Interpret anything with json in the content-type as JSON.
  • Allowing client to specify response content-type aliases; correct me if I'm wrong but since API Gateway doesn't seem to have this problem for me, the culprit (and fix) seems to belong here.

EDIT: link to the specific body parser option I'm referring to: https://github.com/expressjs/body-parser#type
EDIT 2: The first scenario should be covered in the simplest way by this:

 app.use(bodyParser.json({ limit: '5mb', type: function(req) {
   return /json/.test(req.headers['content-type']);
 }}));

on lib/serve.js#_newExpressApp.

promises - getting errors ?

seem to be getting an error whenever i use a promise ? i cloned the babel example to test it and still getting the same error

$export($export.S + $export.F * !webpack_require(20), 'Object', { defineProperty: webpack_require(16).f });
^

TypeError: $export is not a function

function p1(){
  return new Promise((resolve, reject) => {
    setTimeout(_ => {
      resolve('yolo')
    },200)
  })
}

support multiple webpack config files

Currently this plugin only supports one webpack config file that is used during local development and during serverless deploy.

I would like to have two different webpack configurations, one for each of those scenarios.

These could be specified in serverless.yml like so:

custom:
  webpack: 
    dev: ./webpack.dev.config.js
    deploy: ./webpack.deploy.config.js

The default behavior would still apply: if either was not specified, 'webpack.config.js' will be used.

What do you think?

webpack'd lambda includes entire `node_modules` directory

Running serverless webpack produces my webpack'd .js file as well as a node_modules directory that contains EVERY sub-directory in my node-modules directory.

Project layout

node_modules
pages
  - handler.js
package.json
serverless.yml
webpack.config.js

pages/handler.js

'use strict';

let Rx      = require('rxjs/Rx');
let request = require('request');

var doGet = function(url) {
  return Rx.Observable.create(function(observer) {
    request(
      {
        method: 'GET'
        , uri:  url
        , gzip: true
      }, function(error, response, body) {
        if (error) {
          observer.error();
        }
        else if (response.statusCode != 200) {
          observer.error(response);
        }
        else {
          observer.next(response);
        }
        observer.complete();
      })
  });
};

var responseStream = doGet('http://mydomain/test.json')
  .mergeMap(function(response) {
    let d = JSON.parse(response.body);
    return doGet(d.Category[1].Subcategory[1].path);
  })
  .mergeMap(function(response) {
    let d = JSON.parse(response.body);
    return doGet(d.items[0].link);
  });

module.exports.hello = (event, context, callback) => {
  responseStream.subscribe(
    r => {
      const response = {
        statusCode: 200,
        body:       JSON.stringify({
          message:  'HELLO WORLD',
          httpBody: r,
          input:    event,
        }),
      };

      callback(null, response);
    },
    error => {
      callback(error);
    }
  );
};

package.json

{
  "name": "backend",
  "version": "0.0.1",
  "description": "test",
  "repository": {
    "url": "https://github.com/rynop/test"
  },
  "author": "Ryan Pendergast <[email protected]>",
  "license": "MIT",
  "dependencies": {
    "moment": "^2.15.2",
    "request": "^2.75.0",
    "rxjs": "^5.0.0-rc.1"
  },
  "devDependencies": {
    "webpack-node-externals": "^1.5.4",
    "serverless-webpack": "^1.0.0-rc.2"
  }
}

webpack.config.js

'use strict';

let nodeExternals = require('webpack-node-externals'),
    path          = require('path');

module.exports = {
  entry:     {
    pageGet: './pages/handler.js',
  },
  target:    'node',
  externals: [nodeExternals()], // exclude external modules
  output:    {
    libraryTarget: 'commonjs',
    path:          '/tmp/.webpack',
    filename:      'handler.js'
  },
};

Running serverless webpack produces (at /tmp/.webpack):

serverless webpack
Serverless: Bundling with Webpack...
Time: 48ms
     Asset     Size  Chunks             Chunk Names
handler.js  2.97 kB       0  [emitted]  pageGet
Serverless: Packing external modules: rxjs@^5.0.0-rc.1, request@^2.75.0

~ $ls -al /tmp/.webpack
handler.js
node_modules/ <--- this contains 100 dirs
package.json
  • Why does /tmp/.webpack/node_modules not just contain request andrxjs(as you can see I'm usingnodeExternals()`?
  • The smaller the code (and zip size) the quicker the lambda starts (and lowers the overall response time). How do I make it so only the files/code I use within require()d external modules, get pulled into a single webpack'd .js file? Browserify does this very nicely, can't figure out how to pull this off in webpack

Error on first serverless deploy

When deploying a new Serverless project for the first time (stack doesn't exist in CloudFormation yet) with sls deploy, I see this error:

$ sls deploy
Serverless: Creating Stack...
Serverless: Checking stack creation progress...
......
Serverless: Stack successfully created.
Serverless: Bundling with Webpack...
Time: 4537ms
       Asset    Size  Chunks             Chunk Names
./handler.js  268 kB       0  [emitted]  main
Serverless: Zipping service...

  Error --------------------------------------------------

     EEXIST: file already exists, link '/Users/kennu/Projects/xxx/xxx/services/.webpack/.serverless'
     -> '/Users/kennu/Projects/xxx/xxx/services/.serverless'

     For debugging logs, run again after setting SLS_DEBUG env var.

  Get Support --------------------------------------------
     Docs:          v1.docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues

     Please report this error. We think it might be a bug.

When I run sls deploy again, it works fine.

How do you use other NPM modules?

Suppose I want to use a third party lib such as axios how do I go about doing that?

If I import * as axios from "axios"; then run sls webpack serve I get the following error:

ReferenceError: XMLHttpRequest is not defined
    at dispatchXhrRequest (C:\Projects\Experiments\my-third-service\.webpack\handler.js:1045:24)
    at xhrAdapter (C:\Projects\Experiments\my-third-service\.webpack\handler.js:1037:11)
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

If I include axios in the externals of webpack.config.js:

externals: [
    'axios'
  ],

The code runs but after sls deploy I get the following error when I try to run the function:

{"errorMessage":"Cannot find module 'axios'","errorType":"Error","stackTrace":["Module.require (module.js:353:17)","require (internal/module.js:12:17)","Object.<anonymous> (/var/task/handler.js:132:19)","__webpack_require__ (/var/task/handler.js:20:30)","Object.<anonymous> (/var/task/handler.js:51:14)","__webpack_require__ (/var/task/handler.js:20:30)","/var/task/handler.js:40:18","Object.<anonymous> (/var/task/handler.js:43:10)"]}

Any ideas? Perhaps an example that uses a third party lib would be good?

Webpack's Node mock objects should be disabled

By default, Webpack mocks various Node.js objects, causing e.g. Buffer incompatibilities when calling native node_modules.

The default webpack.config.js should include these settings, in documentation or in some other default:

node: {
  console: false,
  global: false,
  process: false,
  Buffer: false,
  __filename: false,
  __dirname: false,
  setImmediate: false,
}

Strange behavior with Mongoose

Trying mongoose with context.callbackWaitsForEmptyEventLoop = false so the function should end after calling callback(...) works different while using serverless-webpack as a plugin and when manually packing the project with webpack.

// webpack.config.js
module.exports = {
  entry: './handler.js',
  target: 'node',
  output: {
    libraryTarget: 'commonjs',
    path: 'dist',
    filename: 'handler.js',
  },

  // Any module with native extensions has to be excluded
  externals: [
    'mongoose',
  ],
}
// handler.js
'use strict';
import mongoose from 'mongoose';
import Promise from 'bluebird';

export const UserSchema = new mongoose.Schema({
  name: String,
});
const User = mongoose.model('User', UserSchema);

const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost/lambda';
mongoose.connect(MONGO_URI);

module.exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false
  return User.find({})
    .then(results => callback(null, results))
    .catch(callback);
};

With serverless-webpack

# serverless.yml
service: users

plugins:
  - serverless-webpack

custom:
  webpackIncludeModules: true

functions:
  index:
    handler: handler.handler
    events:
      - http:
          path: users
          method: get

When calling the function it gets stuck on some event-loop and eventually it times-out on AWS.

Without serverless-webpack

# serverless.yml
service: users

package:
  include:
    - dist/**

functions:
  index:
    handler: dist/handler.handler
    events:
      - http:
          path: users
          method: get

Manually running webpack and:

cd dist 
echo "{}" > package.json 
npm i --save mongoose
cd ..

And then running it locally or on production it work as expected.

Can I put the plugins in a src directory?

I'm structuring my project so that at the root folder there is a src directory that contains all the code. I'd also like to put my package.json and the node_modules folder there including the serverless-webpack plugin.

Is it possible to have this structure? When I try this I get the error Cannot find module 'serverless-webpack' which I'm not sure how to resolve.

webpackIncludeModules ignores version in package.json

When using webpackIncludeModules to install an external node module, the version specified in the Serverless project's package.json is ignored. Instead, the directive will just install the latest version published on npm, which might be completely different.

Pack individual functions using the new packageFunction hook

Hi,

I've noticed that when trying to deploy individual functions (with package -> individually: true in serverless.yml) the change made in #48 has fixed the exception (thank you!), but the function isn't being packed.

In my use case, this leads to a ~19MB .zip being uploaded compared to a ~600kb .zip when I do a full deploy.

A Pull Request was merged and released along with the serverless 1.2.0 milestone yesterday that added a before:deploy:function:packageFunction hook, which I have (naively and probably incorrectly) added to index.js as follows:

      'before:deploy:function:packageFunction': () => BbPromise.bind(this)
        .then(this.validate)
        .then(this.compile),

So now when I run serverless deploy function --function <myFunction> it packages it (as illustrated below):

Without hook:

➜  api git:(master) ✗ serverless deploy function --function myFunction
Serverless: Deploying function: myFunction...
Serverless: Packaging function: myFunction...
Serverless: Uploading function: myFunction (19.9 MB)...
Serverless: Successfully deployed function: myFunction

With hook:

➜  api git:(master) ✗ serverless deploy function --function myFunction
Serverless: Deploying function: myFunction...
Serverless: Bundling with Webpack...
Time: 2337ms
     Asset     Size  Chunks             Chunk Names
handler.js  1.92 MB       0  [emitted]  main
Serverless: Packaging function: myFunction...
Serverless: Uploading function: myFunction (606.73 KB)...
Serverless: Successfully deployed function: myFunction

Would it be possible to please have support for this hook added at some point? I'm happy to make a pull request for it if the way I've added it is acceptable, but didn't want to just assume it was correct.

Thanks

TypeError: func is not a function

Sorry I get stuck for a while already so i would really love to have a hand on this issue.
serverless-webpack works when i run sls deploy to the cloud but not for the local server.
I guess i must have missed something.

$ sls webpack serve
Serverless: Serving functions...
  GET - http://localhost:8000/test
TypeError: func is not a function
  at /home/eric/development/first-serverless/node_modules/serverless-webpack/lib/serve.js:114:7
  at Layer.handle [as handle_request] (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/layer.js:95:5)
  at next (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/route.js:131:13)
  at Route.dispatch (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/route.js:112:3)
  at Layer.handle [as handle_request] (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/layer.js:95:5)
  at /home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:277:22
  at Function.process_params (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:330:12)
  at next (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:271:10)
  at jsonParser (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/body-parser/lib/types/json.js:103:7)
  at Layer.handle [as handle_request] (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/layer.js:95:5)
  at trim_prefix (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:312:13)
  at /home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:280:7
  at Function.process_params (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:330:12)
  at next (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:271:10)
  at expressInit (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/middleware/init.js:33:5)
  at Layer.handle [as handle_request] (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/layer.js:95:5)
  at trim_prefix (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:312:13)
  at /home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:280:7
  at Function.process_params (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:330:12)
  at next (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:271:10)
  at query (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/middleware/query.js:44:5)
  at Layer.handle [as handle_request] (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/layer.js:95:5)
  at trim_prefix (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:312:13)
  at /home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:280:7
  at Function.process_params (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:330:12)
  at next (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:271:10)
  at Function.handle (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/router/index.js:176:3)
  at EventEmitter.handle (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/application.js:173:10)
  at Server.app (/home/eric/development/first-serverless/node_modules/serverless-webpack/node_modules/express/lib/express.js:38:9)
  at emitTwo (events.js:87:13)
  at Server.emit (events.js:172:7)
  at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
  at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)

my package.json file

{
  "name": "first-serverless",
  "version": "0.0.1",
  "description": "First Serverless",
  "main": "handler.js",
  "dependencies": {
    "babel-runtime": "6.11.6",
    "babel-polyfill": "^6.16.0"
  },
  "devDependencies": {
    "aws-sdk": "^2.6.6",
    "babel-core": "^6.17.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.16.0",
    "bluebird": "^3.4.6",
    "serverless-webpack": "^1.0.0-rc.2",
    "webpack": "^1.13.2",
    "webpack-node-externals": "^1.4.3"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Eric Chan",
  "license": "ISC"
}

webpack.config.js

var nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: [
        'babel-polyfill',
        './handler.js'
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            loaders: ['babel'],
            include: __dirname,
            exclude: /node_modules/,
        }]
    },
    target: 'node',
    externals: [nodeExternals()]
};

serverless.yml

service: aws-nodejs

provider:
  name: aws
  runtime: nodejs4.3

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: test
          method: get

plugins:
  - serverless-webpack
custom:
  webpackIncludeModules: true

handler.js

export function hello (event, context, cb) {
    cb(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
}

typescript import local file fails to "find module"

Modifying the typescript example to use imports results in error.

blah.ts

export const name = 'steve';

handler.ts

import {name} from './blah';

export const hello = (event, context, cb) => cb(null,
  { message: name + 'Go Serverless Webpack (Typescript) v1.0! Your function executed successfully!', event }
);

running serverless webpack serve results in error:

Error: Cannot find module "./blah"
at webpackMissingModule (/home/myuser/Documents/git/serverless-webpack/examples/typescript/.webpack/handler.js:48:79)
at Object. (/home/myuser/Documents/git/serverless-webpack/examples/typescript/.webpack/handler.js:48:162)
at webpack_require (/home/myuser/Documents/git/serverless-webpack/examples/typescript/.webpack/handler.js:20:30)
at /home/myuser/Documents/git/serverless-webpack/examples/typescript/.webpack/handler.js:40:18
at Object. (/home/myuser/Documents/git/serverless-webpack/examples/typescript/.webpack/handler.js:43:10)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at ServerlessWebpack.loadHandler (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/serverless-webpack/lib/run.js:19:20)
at Watching.handler (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/serverless-webpack/lib/serve.js:24:39)
at Watching._done (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:81:7)
at Watching. (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:61:18)
at Compiler.emitRecords (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:282:37)
at Watching. (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:58:19)
at /home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:275:11
at Compiler.applyPluginsAsync (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/tapable/lib/Tapable.js:60:69)
at Compiler.afterEmit (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:272:8)
at Compiler. (/home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/webpack/lib/Compiler.js:267:14)
at /home/myuser/Documents/git/serverless-webpack/examples/typescript/node_modules/async/lib/async.js:52:1

Warnings when aws-sdk is processed by webpack ?

WARNING in ./~/aws-sdk/lib/api_loader.js
Critical dependencies:
13:15-59 the request of a dependency is an expression
104:12-46 the request of a dependency is an expression
108:21-58 the request of a dependency is an expression
114:18-52 the request of a dependency is an expression
 @ ./~/aws-sdk/lib/api_loader.js 13:15-59 104:12-46 108:21-58 114:18-52

WARNING in ./~/aws-sdk/lib/util.js
Critical dependencies:
40:30-45 the request of a dependency is an expression
43:11-53 the request of a dependency is an expression
 @ ./~/aws-sdk/lib/util.js 40:30-45 43:11-53

Any clue?

Deploy function not executing webpack and deploys bogus ES6 functions

sls deploy function -f funcName does not run webpack and deploys bogus (incomplete) functions that are missing imported code. sls deploy works correctly and deploys all functions build as defined in config.

Is this a bug, or is there a way to force single-function deployment to properly execute build instructions defined in serverless.yml and webpack.config.js?

Please see related issue serverless issue #2454

Modifying the output path for serverless is error-prone

Modifying the output path for serverless service is error-prone and it results in exclude/include options being ignored, effectively setting the service package to only be the result of the webpack compilation. This might be by design or a bug, in either case, prevents us from uploading node_modules to Lambda.

Would love to hear your opinion, but having it break default serverless functionality (as in https://github.com/serverless/serverless/blob/f966424a40417960a7ac4a03c0709eb931c0af2c/docs/understanding-serverless/serverless-yml.md) shouldn't be the path.

AWS?

Have you been able to get this to work with AWS successfully?

Unable to deploy functions individually

While service deployment works great, I'm unable to deploy functions individually:

$ serverless deploy function -f getAllUsers -s dev
Serverless: Deploying function: getAllUsers...
Serverless: Packaging function: getAllUsers...
fs.js:987
  return binding.stat(pathModule._makeLong(path));
                 ^

Error: ENOENT: no such file or directory, stat '/projects/service-users/node_modules/.bin/babel'
    at Error (native)
    at Object.fs.statSync (fs.js:987:18)
    at files.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/package/lib/zipService.js:55:26)
    at Array.forEach (native)
    at WriteStream.output.on (/usr/local/lib/node_modules/serverless/lib/plugins/package/lib/zipService.js:49:13)
    at emitOne (events.js:96:13)
    at WriteStream.emit (events.js:188:7)
    at WriteStream.<anonymous> (fs.js:2094:10)
    at FSReqWrap.oncomplete (fs.js:123:15)

Is it even supported?

Cleanup module tests missing

Whoops forgot about those.

What the cleanup method does is to move the package artifact (a zip) where it would normally be if this plugin wasn't present at all. It then removes the webpack out directory basically leaving no trace that webpack was there at all.

This is not entirely useful if at all. Yet it should be unit tested and then changed if it is the case.

Implement custom authorizer support

Not sure if I configured something wrong, but I could not get the custom authorizer function to fire on secure endpoints. Could you add this please?

Multiple Entry?

Hi,

Awesome work.

Currently the webpack.config.js entry only supports a single entry point "handler.js". How would one go about having multiple functions in different files? Perhaps you could update the example to show how you would have multiple functions?

Thanks so much again,
Mike

"Can't set headers after they are sent." Error using "request" package

Hi,

Love your package.
It makes our serverless projects much cleaner and easier to test/deploy.

We've encountered a weird bug where in some cases (couldn't pin which one) using the request package will invoke the error mentioned in the title.

We're using very basic code which breaks, so we assume there is some kind of problem with the bundling...

Code example:

new Promise((resolve, reject) => {
    request.get(endpoint, (err, response, body) => {
      if (err)
        return reject(err)
      const { statusCode } = response
      if (statusCode !== 200)
        return reject(`Response with status code ${statusCode}`)
      return resolve(body)
    })
  })

Help would be much appreciated, thanks!

Doesn't work with Yarn & private NPM packages on CircleCI

I've been using Yarn with serverless-webpack to deploy my functions for a while now without any issues (on OSX)... But I can't seem to get continuous deployment working on CircleCI with the same configuration.

I get the following error on CircleCI:

Serverless: Packing external modules: lodash.defaultsdeep@^4.6.0, [email protected], @my-company/[email protected]
 
  Error --------------------------------------------------
 
     Command failed: npm install lodash.defaultsdeep@^4.6.0
     [email protected] @my-company/[email protected]  --save
npm
     ERR! Linux 3.13.0-105-generic
npm ERR! argv "/opt/circleci/nodejs/v6.9.2/bin/node"
     "/opt/circleci/nodejs/v6.9.2/bin/npm" "install" "lodash.defaultsdeep@^4.6.0"
     "[email protected]" "@my-company/[email protected]" "--save"
npm
     ERR! node v6.9.2
npm ERR! npm  v3.10.9
npm ERR! code
     E404

npm ERR! 404 Not found : @my-company/my-private-package
npm
     ERR! 404 
npm ERR! 404  '@my-company/my-private-package' is
     not in the npm registry.
npm ERR! 404 You should bug
     the author to publish it (or use the name yourself!)
npm
     ERR! 404 
npm ERR! 404 Note that you can also install
     from a
npm ERR! 404 tarball, folder, http url, or git
     url.

npm ERR! Please include the following file with
     any support request:
npm ERR!     /home/ubuntu/my-serverless-service/.webpack/npm-debug.log

 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
 
     Please report this error. We think it might be a bug.
 
  Your Environment Information -----------------------------
     OS:                 linux
     Node Version:       6.9.2
     Serverless Version: 1.4.0

I have no idea why, but it seems like serverless-webpack depends on NPM's cache for some reason...

$ yarn install
$ sls deploy
Error! 😢

$ npm install
$ sls deploy
Success! 😕

$ npm install
$ rm -rf node_modules
$ yarn install
$ sls deploy
Success!? 🤔

$ npm install
$ rm -rf node_modules
$ npm cache clean
$ yarn install
$ sls deploy
Error!? 😵

Does this have something to do with the npm-programmatic module? Why does serverless-webpack need to install packages itself instead of just using what's already installed in node_modules?

Babel example doesn't work

I get npm errors when trying out the example. When I have tried to implement this myself I am getting a func is not a function error when running sls webpack serve and handler is not a function when trying to run sls webpack invoke --function hello. Would definitely appreciate some help! Thanks

New error in SLS 1.0.0-rc.2

I get this error when deploying after updating.

EEXIST: file already exists, link '/my-project/.webpack/.serverless'

Help: examples/babel , Error("Cannot find module \"../package.json\"")

Just clone the project & tried, then npm install request package, and using es6 import syntax

import request from "request";

I got this error
var VERSION = webpack_require(!(function webpackMissingModule() { var e = new Error("Cannot find module "../package.json""); e.code = 'MODULE_NOT_FOUND'; throw e; }())).version;

Error: Cannot find module "../package.json"

Any configs need to be set ? Please advise. thanks

Deploying independent functions doesn't work.

I just attempted deploying a single function instead of all of them:

$ serverless deploy function -f myFunction

It didn't show any build information and broke the endpoint.

I'd hate to have to deploy all my functions each build. Is this a possibility?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.