Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
swyxio authored Oct 11, 2018
2 parents 654973b + d739bb3 commit ce3b8c8
Show file tree
Hide file tree
Showing 6 changed files with 2,001 additions and 1,573 deletions.
35 changes: 25 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ This is a small CLI tool that helps with building or serving lambdas built with

The goal is to make it easy to work with Lambda's with modern ES6 without being dependent on having the most state of the art node runtime available in the final deployment environment and with a build that can compile all modules into a single lambda file.

## Installation
Since v1.0.0 the dependencies were upgraded to Webpack 4 and Babel 7.

We recommend installing locally rather than globally: `yarn add -D netlify-lambda`
## Installation

At the present moment you may have to also install peer dependencies [as documented here](https://github.com/netlify/netlify-lambda/issues/35) - we will correct this for the next release when we update our [webpack and babel versions](https://github.com/netlify/netlify-lambda/pull/15).
**We recommend installing locally** rather than globally: `yarn add -D netlify-lambda`. This will ensure your build scripts don't assume a global install which is better for your CI/CD (for example with Netlify's buildbot).

## Usage

Expand All @@ -19,7 +19,7 @@ netlify-lambda serve <folder>
netlify-lambda build <folder>
```

Both depends on a `netlify.toml` file being present in your project and configuring functions for deployment.
**IMPORTANT**: Both commands depend on a `netlify.toml` file being present in your project and configuring functions for deployment.

The `serve` function will start a dev server and a file watcher for the specified folder and route requests to the relevant function at:

Expand All @@ -29,38 +29,53 @@ http://localhost:9000/hello -> folder/hello.js (must export a handler(event, con

The `build` function will run a single build of the functions in the folder.

There are additional options, introduced later:
```bash
-h --help
-c --config
-p --port
```

### Proxying for local development

When your function is deployed on Netlify, it will be available at `/.netlify/functions/function-name` for any given deploy context. It is advantageous to proxy the `netlify-lambda serve` development server to the same path on your primary development server.
When your function is deployed on Netlify, it will be available at `/.netlify/functions/function-name` for any given deploy context. It is advantageous to proxy the `netlify-lambda serve` development server to the same path on your primary development server.

Say you are running `webpack-serve` on port 8080 and `netlify-lambda serve` on port 9000. Mounting `localhost:9000` to `/.netlify/functions/` on your `webpack-serve` server (`localhost:8080/.netlify/functions/`) will closely replicate what the final production environment will look like during development, and will allow you to assume the same function url path in development and in production.
Say you are running `webpack-serve` on port 8080 and `netlify-lambda serve` on port 9000. Mounting `localhost:9000` to `/.netlify/functions/` on your `webpack-serve` server (`localhost:8080/.netlify/functions/`) will closely replicate what the final production environment will look like during development, and will allow you to assume the same function url path in development and in production.

See [netlify/create-react-app-lambda](https://github.com/netlify/create-react-app-lambda/blob/3b5fac5fcbcba0e775b755311d29242f0fc1d68e/package.json#L19) for an example of how to do this.

[Example webpack config](https://github.com/imorente/netlify-functions-example/blob/master/webpack.development.config):

```js
module.exports = {
mode: 'development',
mode: "development",
devServer: {
proxy: {
"/.netlify": {
target: "http://localhost:9000",
pathRewrite: {"^/.netlify/functions" : ""}
pathRewrite: { "^/.netlify/functions": "" }
}
}
}
}
};
```

The serving port can be changed with the `-p`/`--port` option.

## Webpack Configuration

By default the webpack configuration uses `babel-loader` to load all js files. Any `.babelrc` in the directory `netlify-lambda` is run from will be respected. If no `.babelrc` is found, a [few basic settings are used](https://github.com/netlify/netlify-lambda/blob/master/lib/build.js#L11-L15a).

If you need to use additional webpack modules or loaders, you can specify an additional webpack config with the `-c` option when running either `serve` or `build`.
If you need to use additional webpack modules or loaders, you can specify an additional webpack config with the `-c`/`--config` option when running either `serve` or `build`.

The additional webpack config will be merged into the default config via [webpack-merge's](https://www.npmjs.com/package/webpack-merge) `merge.smart` method.

### babel configuration

The default webpack configuration uses `babel-loader` with a [few basic settings](https://github.com/netlify/netlify-lambda/blob/master/lib/build.js#L19-L33).

However, if any `.babelrc` is found in the directory `netlify-lambda` is run from, it will be used instead of the default one.

## License

[MIT](LICENSE)
8 changes: 3 additions & 5 deletions bin/cmd.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,10 @@ program
.command("serve <dir>")
.description("serve and watch functions")
.action(function(cmd, options) {
console.log("Starting server");
console.log("netlify-lambda: Starting server");
var static = Boolean(program.static);
var server = serve.listen(program.port || 9000, static);
if(static) {
return
}
if (static) return // early terminate, don't build
build.watch(cmd, program.config, function(err, stats) {
if (err) {
console.error(err);
Expand All @@ -48,7 +46,7 @@ program
.command("build <dir>")
.description("build functions")
.action(function(cmd, options) {
console.log("Building functions");
console.log("netlify-lambda: Building functions");
build
.run(cmd, program.config)
.then(function(stats) {
Expand Down
34 changes: 17 additions & 17 deletions lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,27 @@ var webpack = require("webpack");
var merge = require("webpack-merge");

// custom babel target for each node version
function getBabelTarget(envConfig){
function getBabelTarget(envConfig) {
var key = "AWS_LAMBDA_JS_RUNTIME";
var runtimes = ["nodejs8.10", "nodejs4.3.2", "nodejs6.10.3"];
var current = envConfig[key] || process.env[key] || "nodejs6.10.3";
var unknown = runtimes.indexOf(current) === -1;
return unknown ? "6.10" : current.replace(/^nodejs/, '');
return unknown ? "6.10" : current.replace(/^nodejs/, "");
}

function webpackConfig(dir, additionalConfig) {
var config = conf.load();
var envConfig = config.build.environment || config.build.Environment || {};
var babelOpts = {cacheDirectory: true};
if (!fs.existsSync(path.join(process.cwd(), '.babelrc'))) {
var babelOpts = { cacheDirectory: true };
if (!fs.existsSync(path.join(process.cwd(), ".babelrc"))) {
babelOpts.presets = [
["env", {
targets: {
node: getBabelTarget(envConfig)
}
}]
["@babel/preset-env", { targets: { node: getBabelTarget(envConfig) } }]
];

babelOpts.plugins = [
"transform-class-properties",
"transform-object-assign",
"transform-object-rest-spread"
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-object-assign",
"@babel/plugin-proposal-object-rest-spread"
];
}

Expand All @@ -37,16 +34,19 @@ function webpackConfig(dir, additionalConfig) {
var dirPath = path.join(process.cwd(), dir);

if (dirPath === functionsPath) {
throw new Error("Function source and publish folder should be in different locations");
throw new Error(
"Function source and publish folder should be in different locations"
);
}

// Include environment variables from config if available
var defineEnv = {};
Object.keys(envConfig).forEach((key) => {
Object.keys(envConfig).forEach(key => {
defineEnv["process.env." + key] = JSON.stringify(envConfig[key]);
});

var webpackConfig = {
mode: "production",
module: {
rules: [
{
Expand All @@ -64,7 +64,7 @@ function webpackConfig(dir, additionalConfig) {
target: "node",
plugins: [
new webpack.IgnorePlugin(/vertx/),
new webpack.DefinePlugin(defineEnv),
new webpack.DefinePlugin(defineEnv)
],
output: {
path: functionsPath,
Expand Down
11 changes: 7 additions & 4 deletions lib/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ function promiseCallback(promise, callback) {

function createHandler(dir, static) {
return function(request, response) {
var func = request.path.split("/").filter(function(e) {
// handle proxies without path re-writes (http-servr)
var cleanPath = request.path.replace(/^\/.netlify\/functions/, '')

var func = cleanPath.split("/").filter(function(e) {
return e;
})[0];
var module = path.join(process.cwd(), dir, func);
Expand All @@ -62,7 +65,7 @@ function createHandler(dir, static) {

var isBase64 =
request.body &&
!(request.headers["content-type"] || "").match(/text|application/);
!(request.headers["content-type"] || "").match(/text|application|multipart\/form-data/);
var lambdaRequest = {
path: request.path,
httpMethod: request.method,
Expand All @@ -82,8 +85,8 @@ exports.listen = function(port, static) {
var config = conf.load();
var app = express();
var dir = config.build.functions || config.build.Functions;
app.use(bodyParser.raw());
app.use(bodyParser.text({type: "*/*"}));
app.use(bodyParser.raw({limit: "6mb"}));
app.use(bodyParser.text({limit: "6mb", type: "*/*"}));
app.use(expressLogging(console, {
blacklist: ['/favicon.ico'],
}));
Expand Down
24 changes: 12 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "netlify-lambda",
"version": "0.5.0",
"version": "1.0.1",
"description": "Build and serve lambda function with webpack compilation",
"homepage": "https://github.com/netlify/netlify-lambda#readme",
"main": "bin/cmd.js",
Expand All @@ -20,19 +20,19 @@
"url": "https://github.com/netlify/netlify-lambda/issues"
},
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-assign": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0",
"@babel/plugin-transform-object-assign": "^7.0.0",
"babel-loader": "^8.0.0",
"base-64": "^0.1.0",
"body-parser": "^1.18.2",
"commander": "^2.11.0",
"express": "^4.16.2",
"body-parser": "^1.18.3",
"commander": "^2.17.1",
"express": "^4.16.3",
"express-logging": "^1.1.1",
"toml": "^2.3.3",
"webpack": "^3.8.1",
"webpack-merge": "^4.1.1"
"webpack": "^4.17.1",
"webpack-merge": "^4.1.4"
}
}
Loading

0 comments on commit ce3b8c8

Please sign in to comment.