serverless-heaven / serverless-webpack Goto Github PK
View Code? Open in Web Editor NEWServerless plugin to bundle your lambdas with Webpack
License: MIT License
Serverless plugin to bundle your lambdas with Webpack
License: MIT License
node-debug/node-inspector or webstorm/vscode can be used in order to debug functions locally.
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?
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
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!
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)
})
}
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!
When running sls webpack serve
the command deletes the whole containing folder.
You may guess how fun that is...
Have you seen: https://github.com/ericclemmons/npm-install-webpack-plugin ?
It automatically with add deps to package.json and npm i
them for you.
Just an idea. Might be out of scope or something the custom webpack config would do.
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.
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):
โ 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
โ 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
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}`;
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.
Inspired by elastic-coders/serverless-runtime-webpack#8 it could be useful to have a command to run a local server simulating the API Gateway. It could be something like:
$ serverless webpack serve --port 8000
Serving endpoints:
GET - http://localhost:8000/dev/hello
POST - http://localhost:8000/dev/user/{userId}
What do you think? how would you go in implementing this?
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.
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
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! :)
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,
}
I get this error when deploying after updating.
EEXIST: file already exists, link '/my-project/.webpack/.serverless'
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.
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?
Hello all!
I have been away for a while. I'll be checking out Serverless rc.1 and start working on the update of this plugin asap.
Any help is appreciated!
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
I see Error Serverless: Uploading function .zip files to S3...
Error --------------------------------------------------
ENOENT: no such file or directory .webpack.serverless\servicename-funtionName.zip'
In zip archive I see all entry points but want only required by function handler in serverless.yml
From what I can see the current working dir isn't updated before calling a function which stops some relative path locations locally
I believe process.chdir(path.dirname(handlerFilePath))
should be inserted before https://github.com/elastic-coders/serverless-webpack/blob/master/lib/run.js#L16
This will help with serverless/serverless#2009
Have you been able to get this to work with AWS successfully?
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:
json
in the content-type as JSON.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
.
As a peer dep, we can use whatever webpack version we want as long as it's above the minimum required version
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.
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?
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
It looks like serverless webpack serve
doesn't add environment vars (serverless 1.2.0) defined in serverless.yml
to the local environment.
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);
};
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.
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.
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?
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
.
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.
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.
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.
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
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 });
}
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?
Hi,
It would be nice if you changed serverless.yml or serverless.env.yml then webpack serve would restart.
Not sure how hard that might be to do?
Mike
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 ...
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.
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.
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.
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
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?
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
/tmp/.webpack/node_modules
not just contain request and
rxjs(as you can see I'm using
nodeExternals()`?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 webpackI'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
?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.