Serverless-stack-com: Comments: Add Support for ES6/ES7 JavaScript

Created on 10 Apr 2017  路  43Comments  路  Source: AnomalyInnovations/serverless-stack-com

All 43 comments

Any chance that you could show the same setup but using TypeScript instead?

@EisenbergEffect We could, but we might have to create a completely separate TypeScript version of the tutorial. And that makes it a little lower on the priorities.

But we could look into creating a one off chapter just for the TypeScript setup.

I'd love to see one-off chapter, particularly on setting up TypeScript with the Serverless Stack. I've got setups for my front-ends framework but I'm new to the Serverless Stack so I wasn't sure how to handle that part of it.

On a side note, I really love what you all have done here. Once I see how to get this setup with TS for Serverless, I'll be using this as a foundation for a new side-project of mine. One difference will be that I'm using Aurelia instead of React, but all the front-end work should translate very easily.

@jayair I found this: https://github.com/y13i/serverless-ts-example

Does that look like a "correct" configuration that would serve as a substitute for the equivalent Babel implementation?

@EisenbergEffect I haven't seen that before but I'll need to play around with it. I hope there are some other TS folks that are willing to help out.

what about the idea to implement a language switch where the user can switch the language flavor for the code samples - then it is easy to add step by step the TypeScript examples inline in the tutorial.

also this can be interesting to have an "easy javascript" vs "functional javascript" version - this addresses the #109 recommendations to use advanced functions for the examples.

or maybe some other languages can be implemented on demand

@muescha I like the idea of having the sample project repos in multiple languages/setups. It would need some community contributions to get it up and running since I'm not much of a TypeScript user.

There have been a lot of updates to serverless-webpack recently and v3 is just around the corner now 馃槃 - a prerelease is already available as [email protected]. The chapter should be updated (especially the webpack.conf.js part) to use the new automatic entry resolution which makes any manual entry file search obsolete (here: globEntries()).

This is already supported in the current version 2.2.0 of the plugin. See the V3 readme/branch for details, what will change and is improved (includes the v2.2.0 changelog at the bottom too).

@HyperBrain Thanks for letting us know. v3 looks really good! Congrats!

I'll push out an update to the tutorial once it's out because it changes a few things (including webpack invoke).

Fantastic resource. Please consider mentioning facebook's create-react-app.

create-react-app notes-app-api

and for typescript:

create-react-app notes-app-api --scripts-version=react-scripts-ts

@kenbankspeng Thanks!

Are you referring to these commands while we create the API? I think you mean the frontend React app?

I was initially thinking regarding both the API and the front end, but looks like create-react-app has other files added which are really only for a front end app, so may not be appropriate for the API. I just liked how create-react-app hid babel and webpack from me. Maybe a configuration option for typescript then. But beggars can't be choosers...

I need help on: I am using ubuntu 16.04

$ serverless invoke local --function create --path mocks/create-event.json
Serverless: Bundling with Webpack...
Time: 587ms
    Asset  Size  Chunks             Chunk Names
create.js  5 kB       0  [emitted]  create
   [0] ./create.js 2.16 kB {0} [built]
   [1] external "babel-runtime/core-js/json/stringify" 42 bytes {0} [not cacheable]
   [2] external "uuid" 42 bytes {0} [not cacheable]
   [3] external "aws-sdk" 42 bytes {0} [not cacheable]

@lbybill What's the issue?

@jayair The process stops here. I thought this, "[not cacheable]", is a error.

@lbybill Oh no those messages are fine. But it looks like your create function did not print anything out. Have you completed this chapter - https://serverless-stack.com/chapters/add-a-create-note-api.html?

@jayair Yes. I followed and finished this chapter.

@lbybill You can follow the console.log to debug what is going on. We talk about it briefly at the bottom the chapter - https://serverless-stack.com/chapters/add-a-create-note-api.html#common-issues.

@jayair I got this error. I am behind a firewall. I setup proxy already.

aws dynamodb scan --table-name notes --region us-east-2 in command line works for me.
I am wondering if sls need proxy too?

{ [TimeoutError: Connection timed out after 120000ms]
  message: 'Connection timed out after 120000ms',
  code: 'TimeoutError',
  time: Fri Oct 13 2017 15:01:17 GMT-0700 (PDT),
  region: 'us-east-2',
  hostname: 'dynamodb.us-east-2.amazonaws.com',
  retryable: true }

@lbybill I haven't come across this error before but on local the AWS SDK is being used to make calls to DynamoDB. So technically if the AWS CLI works then this sls invoke local should work as well. At least I think it should.

webpack is only needed locally isn't it ? The babel runtime transpiles normal js into es6/7 syntax in lambda right ? I have babel-preset-2015 and it seems that I can use import working locally. However, app breaks in lambda when deployed. So I was wondering if adding babel-runtime in the dependency will solve issues for me ?

@kaiyes Aside from transpiling, Babel also has a a runtime portion that is needed. It's in our package.json here - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json#L32

@jayair thanks. I was trying to get some answers in the forum about how webpack and bable runtime works in lambda. And I got this answer which clears it up for me.

Serverless uses the serverless-webpack plugin to run Webpack which builds the files that are uploaded to Lambda. Webpack uses TypeScript (or Babel) to compile ES7/8 code back to ES6 that鈥檚 supported by Node 6. It鈥檚 the compiled ES6 version that is being sent to Lambda and not your ES 7/8 source versions.

From what I鈥檝e read the bable-runtime package add polyfills for missing objects and functions but it won鈥檛 help with missing syntax. That鈥檚 what the babel compiler run by Webpack handles.

Basically I am trying to get async-await and imports working in my current app and failing.

Can this step now be simplified with the ability to create a service from a ecma template via:

serverless create --template aws-nodejs-ecma-script --path myService

@rogerschlachter Yeah we have a similar service that we show later in the tutorial - https://serverless-stack.com/chapters/serverless-es7-service.html. The services themselves don't do a whole lot and for now it makes sense to show folks what they are doing. But at some point we'll switch over to this.

Since 'aws-sdk' is not compatible with webpack, we exclude all node dependencies

This justification does not follow the description of webpack-node-externals library, which is:

When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.

Meaning, we don't have to bundle the dependencies because they will be available in node_modules.

npm install --save-dev babel-preset-es2015 

now yields the following:

npm WARN deprecated [email protected]: 
  馃檶  Thanks for using Babel: we recommend using babel-preset-env now: 
  please read babeljs.io/env to update! 

@SpencerGreene Thanks for letting us know I'll switch over to it.

Why not use SimpleDB instead of DynamoDB? Then you have two services that only run when you have a request.

How complicated would it be to use SimpleDB for this tutorial instead?

@appernetic We had looked into SimpleDB but it has some big limitations when you grow. Support for SimpleDB has also fallen behind for the SDK. So it isn't a very good option to invest in, if you are just starting off.

@jayair Ok, thanks for the heads up. What are the big limitations when you grow?

I intend to use it for user data and each user has only 347 B of data. It will be read each time user signs in and written one time each month when subscription date is updated. Sounds like a perfect use case for SimpleDB.

I have researched both SimpleDB, DynamoDB and Aurora Serverless and DynamoDB seems to be the best option.

@jayair hey man..if i want to add 'src' directory to store all my codes, what do i need to add or change in the webpack.config.js file ..? thanks.

@takeuchie You just need to change the line in serverless.yml where the handler is referenced with the new path. So handler: create.main changes to handler: src/create.main.

https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/serverless.yml#L39

@jayair thanks mate..

Error running "serverless invoke local --function create --path mocks/create-event.json"
i get the following error

ERROR in Entry module not found: Error: Can't resolve './src' in '/var/www/html/learning/notes-app-api'
here is my webpack.config.js

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


module.export={
    entry:slsw.lib.entries,
    target:'node',
    externals:[nodeExternals()],
    mode:slsw.lib.webpack.islocal?"development":"production",
    optimization:{
        minimize:false
    },
    performance:{
        hints:false
    },
    module:{
        rules:[
            {
                test:/\.js$/,
                loaders:['babel-loader'],
                include:__dirname,
                exclude:/node_modules/
            }
        ]
    }
};

Here is my serverless.yml

service: notes-app-api

# Use serverless-webpack plugin to transpile ES6/ES7
plugins:
  - serverless-webpack

# serverless-webpack configuration
# Enable auto-packing of external modules
custom:
  webpack:
    webpackConfig: ./webpack.config.js
    includeModules: true

provider:
  name: aws
  runtime: nodejs6.10
  stage: prod
  region: us-east-1

  # 'iamRoleStatement' defines the permission policy for the Lambda function.
  # In this case Lambda functions are granted with permissions to access DynamoDB.
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-1:*:*"

functions:
  # Defines an HTTP API endpoint that calls the main function in create.js
  # - path: url path is /notes
  # - method: POST request
  # - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross
  #     domain api call
  # - authorizer: authenticate using the AWS IAM role
  create:
    handler: create.main
    events:
      - http:
          path: notes
          method: post
          cors: true
          authorizer: aws_iam

here is mys package.json

{
  "name": "notes-app-api",
  "version": "1.0.0",
  "description": "",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "aws-sdk": "^2.218.1",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-3": "^6.24.1",
    "serverless-webpack": "^5.1.1",
    "webpack": "^4.4.1",
    "webpack-cli": "^2.0.13",
    "webpack-node-externals": "^1.6.0"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "uuid": "^3.2.1"
  }
}

here is my create.js

import uuid from "uuid";
import AWS from "aws-sdk";


AWS.config.update({region:"us-east-1"});
const dynamoDB=new AWS.DynamoDB.DocumentClient();


export function main(event,contenxt,callback){

    const data=JSON.parse(event.body);


    const params={
        TableName:"noted",
        Item:{
            userId:event.requestContext.identity.cognitoIdentityId,
            noteId:uuid.content,
            attachment:data.attachment,
            createdAt:new Date().getTime()
        }
    };


dynamoDB.put(params,(error,data)=>{
    const headers={
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": true
    };

    if(error){
        const response={
            statusCode:500,
            headers:headers,
            body:JSON.stringify({status:false})
        };

        callback(null,response);

        return;
    }

    const response={
        statusCode:200,
        headers:headers,
        body:JSON.stringify(params.Item)
    };
    callback(null,response);
});

}


@Malouda Where is the ./src coming from?

aws announced support for node 8.10 : https://aws.amazon.com/about-aws/whats-new/2018/04/aws-lambda-supports-nodejs/?nc1=h_ls

is it as simple to replace 6 by 8 in .babelrc and in serverless.yml files

@lepirlouit Yes it is. We'll update the tutorial soon.

Was this page helpful?
0 / 5 - 0 ratings