Git Product home page Git Product logo

serverless-optimizer-plugin's Introduction

Serverless Optimizer Plugin

serverless

Browserifies, minifies your Serverless Node.js Functions on deployment, and more!

Reducing the file size of your AWS Lambda Functions allows AWS to provision them more quickly, speeding up the response time of your Lambdas. Smaller Lambda sizes also helps you develop faster because you can upload them faster. This Severless Plugin is absolutely recommended for every project including Lambdas with Node.js.

Note: Requires Serverless v0.5.0 or higher.

###Setup

  • Install via npm in the root of your Serverless Project:
npm install serverless-optimizer-plugin --save
  • Add the plugin to the plugins array in your Serverless Project's s-project.json, like this:
plugins: [
    "serverless-optimizer-plugin"
]
  • In the custom property of your s-function.json add an optimize property.
"custom": {
    "optimize": true
}
  • If you rely on the aws-sdk, be sure to read the Common Pitfalls section.

  • All done!

Configuration Options

Configuration options can be used by setting the optimize property to an object instead of a boolean value. The following options are available:

  • disable - When set to true, this will disable optimizer. This is effectively the same as setting the optimize property to false, but it does not require the deletion of any other configuration values within the optimize object. This is a good option for temporarily disabling while debugging.
"custom": {
    "optimize": {
        "disable": true
    }
}
  • excludeStage - When set to a string or [string], optimizer will be disabled for the specified stage(s). This is beneficial if you do not want optimizer to run on a specific stage to aid in debugging.
"custom": {
    "optimize": {
        "excludeStage": ["dev", "test"]
    }
}
  • excludeRegion - When set to a string or [string], optimizer will be disabled for the specified region(s).
"custom": {
    "optimize": {
        "excludeRegion": ["us-east-1"]
    }
}

Browserify Options

Browserify options can be included as normal configuration options to the optimize object. The following options are supported:

  • handlerExt
  • includePaths
  • requires
  • plugins
  • transforms
  • exclude
  • ignore
  • extensions

For more information on these options, please visit the Browserify Documentaton.

Common Pitfalls

  • aws-sdk does not play well with Browserify. If the aws-sdk is used anywhere in your code, even if it is not within node_modules or package.json, you may receive an error similar to:

Uncaught {"errorMessage":"Cannot find module '/usr/lib/node_modules/aws-sdk/apis/metadata.json'"...

To fix this, the aws-sdk should be excluded by using the exclude Browserify option. Since the aws-sdk is always available to an AWS Lambda, it should never need to be included.

"custom": {
    "optimize": {
        "exclude": ["aws-sdk"]
    }
}

ES6 with Babel and Babelify

Bundles are packaged with Browserify, and can be transformed to support ES6 features with Babelify.

Install babelify within the root context of your project:

npm install babelify --save

npm install babel-preset-es2015 --save

Add the babelify transform to s-function.json:

{
    "name": "myfunc",
    "runtime": "nodejs",
    "custom": {
        "optimize": {
            "exclude": [ "aws-sdk" ],
            "transforms": [
                {
                    "name": "babelify",
                    "opts": {
                        "presets": [
                            "es2015"
                        ]
                    }
                }
            ]
        }
    }
}

We're currently working on adding support for Typescript. Check back for updates!

serverless-optimizer-plugin's People

Contributors

ac360 avatar ajagnanan avatar alua-kinzhebayeva avatar arabold avatar bugeats avatar eahefnawy avatar joostfarla avatar jordanmack avatar kpotehin avatar martinmicunda avatar minibikini avatar rajington avatar staceymoore 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  avatar  avatar  avatar  avatar

serverless-optimizer-plugin's Issues

can not add directory using includePaths

s-function.json

"handler": "handler.handler",
"custom": {
    "optimize": {
        "exclude": [
        "aws-sdk"
      ],
      "includePaths": [
        "api/lib"
      ]

    }
  },

folder structure

projectname
  - _meta
  - node_modules
  - api(parent folder of all lambda functions)
      -- lib
      -- functioname(sharing s-function.json of this function)

  - package.json
  - s-project.json
  - s-resources-cf.json

got following error

Serverless:   functioname: ENOENT: no such file or directory, lstat 'E:\wamp\www\projectname\_meta\_tmp\functioname@1461748890741\api\lib

install not effective unless in package.json

I had some issues while installing this plugin.

Tried to install running npm install serverless-optimizer-plugin --save
and added "plugins": ["serverless-optimizer-plugin"] on s-project.json file.

But after that running any sls command gave me an error:

sls                                                            ⏎
/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:61
        fn = function () { throw arg; };
                           ^

ServerlessError: This plugin could not be found: serverless-optimizer-plugin
    at new ServerlessError (/usr/local/lib/node_modules/serverless/lib/Error.js:17:11)
    at Serverless._loadPlugins (/usr/local/lib/node_modules/serverless/lib/Serverless.js:298:17)
    at Serverless.loadProjectPlugins (/usr/local/lib/node_modules/serverless/lib/Serverless.js:245:10)
    at /usr/local/lib/node_modules/serverless/lib/Serverless.js:76:41
From previous event:
    at Serverless.init (/usr/local/lib/node_modules/serverless/lib/Serverless.js:72:25)
    at Object.<anonymous> (/usr/local/lib/node_modules/serverless/bin/serverless:17:12)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:139:18)
    at node.js:999:3

The only to make it work for me was to create an package.json file at project root and add this line in dependencies

"serverless-optimizer-plugin": "https://github.com/serverless/serverless-optimizer-plugin.git"

Unfortunately I have no idea what went wrong before ... so I can't really help solving this issue

Optimizer crashes on ES2015-compliant code.

So, getting this error:

JS_Parse_Error {
  message: 'Unexpected token: name (tempPass)',
  filename: 'C:\\Users\\...\\_meta\\_tmp\\clientApi@1461203961098\\optimized\\clientApi\\_serverless_handler.js',

The code is:

  let tempPass = request.password;

A similar issue with:

  var cognitoParams = {
    IdentityPoolId: process.env.cognitoIdentityPool,
    Logins: {
      [process.env.cognitoDeveloperName]: cognitoKey
    }
  };

Result is:

Serverless: ------------------------
Serverless: Failed to deploy the following functions in "carmine" to the following regions:
Serverless: us-east-1 ------------------------
Serverless:   clientApi: Unexpected token: name (process)
C:\Users\...\npm\node_modules\serverless\node_modules\bluebird\js\release\async.js:61
        fn = function () { throw arg; };

This is serverless-optimizer-plugin v2.5.1. Code is running fine on Lambda when I remove the optimizer plugin.

Getting an error when running a lambda function with asyncawait, issue with fibers bin path

So because it's using browserify to create a single js file when it uploads, is there any way to tell optimise to not touch asyncawait, but to then copy it into the output zip file in place?

Here's the error:

{
    "errorMessage": "`/vagrant/_meta/_tmp/function1@1463372948220/node_modules/asyncawait/node_modules/fibers/bin/linux-x64-v8-4.5/fibers.node` is missing. Try reinstalling `node-fibers`?",
    "errorType": "Error",
    "stackTrace": [
        "Object.u.6.fs (/var/task/function1/_serverless_handler.js:1:3168)",
        "i (/var/task/function1/_serverless_handler.js:1:621)",
        "/var/task/function1/_serverless_handler.js:1:672",
        "Object.<anonymous> (/var/task/function1/_serverless_handler.js:3:1135)",
        "Object.u.18.fibers (/var/task/function1/_serverless_handler.js:3:1261)",
        "i (/var/task/function1/_serverless_handler.js:1:621)",
        "/var/task/function1/_serverless_handler.js:1:672",
        "Object.u.13.../await/index (/var/task/function1/_serverless_handler.js:2:30438)",
        "i (/var/task/function1/_serverless_handler.js:1:621)"
    ]
}

Optimize options in s-function.json

{
  "disable": false,
  "exclude": ["aws-sdk"],
  "transforms": [
    {
      "name": "babelify",
      "opts": {
        "presets": [
          "es2015"
        ]
      }
    }
  ]
}

Error trying to deploy single function

Hi there.

Using version 4.2.1-rc.1 of serverless-optimizer-plugin and serverless versions:

Framework Core: 2.55.0 (local)
Plugin: 5.5.1
SDK: 4.3.0
Components: 3.18.1

Other plugins:

  - serverless-domain-manager
  - serverless-offline
  - serverless-plugin-optimize
  - serverless-iam-roles-per-function

Using:

sls deploy function -f <name> --stage=<stage>

Results in:

SyntaxError: Assigning to rvalue (1:62403) while parsing ***/serverless_sdk/index.js while parsing file: ***/serverless_sdk/index.js
      at DestroyableTransform.end [as _flush] (***:21)
      at DestroyableTransform.prefinish (***/_stream_transform.js:138:10)
      at DestroyableTransform.emit (events.js:400:28)
      at DestroyableTransform.emit (domain.js:470:12)
      at prefinish (***/node_modules/readable-stream/lib/_stream_writable.js:619:14)
      at finishMaybe (***/monorepo/node_modules/readable-stream/lib/_stream_writable.js:627:5)
      at endWritable (***/monorepo/node_modules/readable-stream/lib/_stream_writable.js:638:3)
      at DestroyableTransform.Writable.end (***/node_modules/readable-stream/lib/_stream_writable.js:594:41)
      at BabelifyStream.onend (internal/streams/readable.js:665:10)
      at Object.onceWrapper (events.js:519:28)
      at BabelifyStream.emit (events.js:400:28)
      at BabelifyStream.emit (domain.js:470:12)
      at endReadableNT (internal/streams/readable.js:1317:12)
      at processTicksAndRejections (internal/process/task_queues.js:82:21)

However it works if we set optimise:false on the function (which is not ideal).

Any idea how to make it work without yml changes?

Disabling Optimizer Explodes Package.zip File Size and Hangs Deployment

Removing "optimize" element from the s-component and trying to redeploy results in an explosive package.zip file size (far beyond before optimizing) and the Sls deployment logic hangs. You cannot CTRL+C and must terminate the IDE or terminal session. (NOTE: I did not uninstall the es2015 npm package, but it should not be used as it's not being used in transforms).

feature suggestion: elm support

I'm not sure if optimizer is meant to be the thing that transpiles, compiles etc, but I saw that you are trying to support typescript and thought to suggest elm-lang.

How to avoid duplicate optimizer config for each function?

The serverless v0.0.5 has removed the concept of components so I tried to move the optimizer config from s-component.json to s-project.json however this doesn't work and as it mentions in the doc optimizer config needs to be add to each s-function.json so my question is, is there a way how we could avoid duplicate this config for each function either by placing this config to s-project.json or add it to s-templates.json (template options doesn't work as it doesn't seem to compile optimize template).

s-templates.json

    "optimize": {
      "exclude": [
        "aws-sdk"
      ],
      "transforms": [
        {
          "name": "babelify",
          "opts": {
            "presets": [
              "es2015",
              "stage-2"
            ]
          }
        }
      ],
      "minify": false
    }

s-function.json

  "custom": {
    "excludePatterns": [ "aws-sdk"],
    "optimize": "$${optimize}"
  }

ES2015 Deployed Code Crashes -- Optimizer not observing strict mode

The serverless-optimizer-plugin does not appear to be observing 'use strict’; Thus, not defining a variable with var is ignored and when the code is deployed, it crashes in the Lambda environment.

To reproduce this issue:

1). Setup fresh project with a single component and function.

  1. Add the optimizer for es6 as outlined in readme.
    "custom": {
        "optimize": {
            "exclude": [
                "aws-sdk"
            ],
            "includePaths": [
            ],
            "transforms": [
                {
                    "name": "babelify",
                    "opts": {
                        "presets": [
                            "es2015"
                        ]
                    }
                }
            ]
        }
    }
  1. Make sure 'use strict;' is at the top of the function file.

  2. Add the following line to the function handler

foo = 1;
  1. Deploy and run function in AWS Lambda environment.

sls function run component/function -s dev

Check CloudWatch for Crash ReferenceError: foo is not defined.*

  1. Add var ahead of the variable:
var foo = 1;
  1. Deploy and run function again.

sls function run [path]

Works fine now.

Serverless deployment process should catch this error (due to strict mode) and fail. Not catching these errors results in unstable code being deployed that is out of spec.

If possible, adding babel-plugin-transform-strict-mode might help. How can this plugin be added to the optimizer json? It really shouldn't be required when strict is declared at the top of the file, but it would be nice to know how to include plugins for babel.

Python Support

Are there plans to extend the support runtime to python?

Improve `includePaths` property

@ac360 @minibikini please improve includePaths path because so many person have issue and that issues are still open.

look like includePaths is not taking path properly,it should start from project root directory.

my case

s-functions.js

"handler": "functionone/handler.handler",
"custom": {
    "optimize": {
      "exclude": [
        "aws-sdk",
        "mysql"
      ],

      "includePaths": [
        "lib",
        "node_modules/mysql"


      ]

    }
  },

project structure

project root
 - functions //parent folder of all function
      -- functionone
      -- functiontwo
      -- lib //common functionalities
      -- node_modules
           --- mysql
- package.json
- node_modules
     -- serverless-optimizer-plugin
- s-project.json
- s-resources-cf.json

when i try to deploy function from root project dir using dash deploy its fails with following error

ENOENT: no such file or directory

thanks for your great work 👍

Serverless 1.0

What are the plans to upgrade this plugin to 1.0 .. or maintain it in general. I think it would be great to have on "standard" plugin that takes care es6 and bundling (if it really helps).

Currently it seems that there are several packages for this.

The only one with support for serverless 1.0 being that latter.

I think it would be great to have some kind of best practices for what should and should not be done. What are the pros and cons etc of each of these packages and so on.

Since Lambda only supports the outdated node 4.3 this seems to be a vital part of any serious serverless application.

What's the plan with Babelify support?

I see that the call to babelify was removed in the 0.1.0 release, and I see that the config signature was simplified, but it's not clear to me where babelify is meant to fit in now.

I'd like to work on this. Is there a plan?

Another includePaths bug

Hi - Isn't this a bug in the includePaths?
https://github.com/serverless/serverless-optimizer-plugin/blob/master/index.js#L288

Shouldn't it be something like:

let destDir  = (fs.lstatSync(path.join(_this.evt.options.pathDist,p)).isDirectory()) ? destPath : path.dirname(destPath);

That way optimizer will actually find the intended include? If you just use the includePath as written in the s-function then lstat won't find it because its looking for a full path right? (http://linux.die.net/man/2/lstat)

Changing to the above allows a successful deploy for me

Function Deployment Failed

I am running sls v 0.5 and serverless-optimizer-plugin, both latest versions are installed from Github.
When I add babelify config to s-function, sls dash deploy and sls function deploy fail.
Optimizer plugin fails on 185th line which is const handlerName = this.function.getHandler();
It seems that Function stored in this.function does not have access to getHandler from Function class.

[ '_class',
  '_config',
  '_filePath',
  'name',
  'runtime',
  'customName',
  'customRole',
  'handler',
  'timeout',
  'memorySize',
  'authorizer',
  'custom',
  'endpoints',
  'events',
  'environment',
  'vpc',
  'templates' ]

Suggested: Have includePaths override excludePatterns

With the goal in mind to reduce deployed package size, it would be a nice feature to be able to exclude all paths using excludePattern, then surgically select files/paths to include using includePaths.

Given the following directory structure...

/api
  /fn1
    handler.py
    s-function.json
  /fn2
    handler.py
    s-function.json
  /lib
    Notifier.py
    StackEvent.py

If /api/fn1/s-function.json has...

 "custom": {
    "optimize": true,
    "includePaths": []
 }

I still find /fn2/* and /lib/* in the deployment package (.zip).

As I understand the intent of this plugin is to remove those two additional directories. It's possible/likely I am missing something. I have reviewed other issues, like #48, etc.

Thanks all! This is good work.

Cannot find module 'mysql'

part of my serverless_project_folder/parent_folder_of_all_lambda_functions/lambda_function_name(folder)/s-function.js

 "handler": "functioname/handler.handler",
  "timeout": 4,
  "memorySize": 128,
  "authorizer": {},
  "custom": {
    "excludePatterns": [],
    "envVars": [],
    "optimize": {
      "exclude": [
        "aws-sdk",
        "mysql"
      ]
    },
    "includePaths": [
      "config",
      "node_modules/mysql"
    ]
  }

location of mysql module serverless_project/parent_folder_of_all_lambda_functions/node_modules

after deploy i got following error

Cannot find module 'mysql'

using latest code of this plugin

error with optimized lambda

I get this error on a lambda function when it has been optimized by this plugin. Without the plugin, the function works. I'm using the 'test' button from within the AWS console to produce this error:

{
  "errorMessage": "Cannot find module './aes'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._resolveFilename (module.js:338:15)",
    "Function.Module._load (module.js:280:25)",
    "Module.require (module.js:364:17)",
    "require (module.js:380:17)",
    "i (/var/task/ivr/selection/handler.js:1:497)",
    "/var/task/ivr/selection/handler.js:1:688",
    "/var/task/ivr/selection/handler.js:12:25267",
    "Array.map (native)",
    "Object.a.exports (/var/task/ivr/selection/handler.js:12:25244)",
    "o (/var/task/ivr/selection/handler.js:12:25428)"
  ]
}

I'm not sure how to debug this. But I can gather more info if you ask for something in particular.

includePaths and folder structure issue

I'm running serverless version 0.5.5 on Windows 10 1511 with node.js version 5.6.0 and serverless-optimizer version 2.5.1.

First, given a folder structure like:

MyProject
|--lib
    |--common.js
|--functions
   |--myFunction1
       |--handler.js 
       |--s-function.json

and my optimize section looks like:

"custom": {
    "optimize": {
      "exclude": [ "aws-sdk" ],
      "require": [ "q", "jsonwebtoken", "rsa-pem-from-mod-exp", "node-uuid" ],
      "excludeStage": [ "dev", "test" ],
      "includePaths": [ "./lib" ]
    }
  }

and my handler is defined as

"handler" : "myFunction1/handler.handler"

When I run sls function deploy myFunction1 it always fails with an error: myFunction1: ENOENT: no such file or directory, lstat 'C:\Workspaces\AWS\LambdaFunctions\MyProject\_meta\_tmp\myFunction1@1464958827455\lib'. So, when I create an empty lib folder in the functions folder, it succeeds. However, the contents of MyProject/functions/lib are not included in the resulting zip file. I'm expecting there to be a folder called lib with the contents of the lib folder in the project, namely common.js. Now, if I put the common.js file in that new empty lib folder, then it does end up in the zip. But, if I delete the lib folder in the project root, because it appears to not actually get utilized, then I get an error: myFunction1: ENOENT: no such file or directory, lstat 'C:\Workspaces\AWS\LambdaFunctions\MyProject\lib'. So it appears that the optimizer is checking for the folder to actually exist in both places, but only taking the content from the one in the functions folder. This is not what I would expect or desire, I want the includePaths to be relative to the project root and actually take the files/folders defined there and not need to maintain a shadow copy somewhere in subfolders.

Error: 'import' and 'export' may appear only with 'sourceType: module', When running sls deploy

Description

sls deploy only works when I remove serverless-plugin-optimize from serverless.yaml

Service configuration (serverless.yml) content

service: nest-serverless-lambda

plugins:
 - 'serverless-plugin-typescript'
 - serverless-plugin-optimize
 - serverless-offline

provider:
 name: aws
 runtime: nodejs14.x

functions:
 oa-staging-backend:
   handler: packages/backend/src/app/lambda.handler
   events:
     - http:
         method: any
         path: /{any+}

Command name and used flags

sls deploy --verbose --debug "*"

Command output

lifecycle:command:invoke:hook: [17]   > before:package:createDeploymentArtifacts
lifecycle:command:invoke:hook: [17]   < before:package:createDeploymentArtifacts
Optimize: starting engines
Optimize: nest-serverless-lambda-dev-oa-staging-backend
aws: [1] { Error: connect EHOSTDOWN 169.254.169.254:80 - Local (172.20.10.8:65007)
    at internalConnect (net.js:934:16)
    at defaultTriggerAsyncIdScope (internal/async_hooks.js:452:18)
    at net.js:1022:9
    at processTicksAndRejections (internal/process/task_queues.js:77:11)
  message: 'Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1',
  errno: -64,
  code: 'CredentialsError',
  syscall: 'connect',
  address: '169.254.169.254',
  port: 80,
  time: 2022-11-25T16:30:10.671Z,
  originalError:
   { message: 'Could not load credentials from any providers',
     errno: -64,
     code: 'CredentialsError',
     syscall: 'connect',
     address: '169.254.169.254',
     port: 80,
     time: 2022-11-25T16:30:10.671Z,
     originalError:
      { message: 'EC2 Metadata roleName request returned error',
        errno: -64,
        code: 'EHOSTDOWN',
        syscall: 'connect',
        address: '169.254.169.254',
        port: 80,
        time: 2022-11-25T16:30:10.671Z,
        originalError:
         { errno: -64,
           code: 'EHOSTDOWN',
           syscall: 'connect',
           address: '169.254.169.254',
           port: 80,
           message: 'connect EHOSTDOWN 169.254.169.254:80 - Local (172.20.10.8:65007)' } } } }
lifecycle:command:invoke:hook: [17]   > before:package:createDeploymentArtifacts
lifecycle:command:invoke:hook: [1] > before:deploy:deploy

✖ Stack nest-serverless-lambda-dev failed to deploy (89s)
process: handle error
process: finalize { error:
   { [SyntaxError: 'import' and 'export' may appear only with 'sourceType: module']
     message: "'import' and 'export' may appear only with 'sourceType: module'",
     line: 1,
     column: 1,
     annotated:
      "\n/Users/bassel/oa-monorep/.build/node_modules/@nestjs/axios/node_modules/axios/index.js:1\nimport axios from './lib/axios.js';\n^\nParseError: 'import' and 'export' may appear only with 'sourceType: module'",
     stream:
      Labeled {
        _readableState:
         ReadableState {
           objectMode: true,
           highWaterMark: 16,
           buffer: BufferList { length: 0 },
           length: 0,
           pipes:
            Labeled {
              _readableState: [ReadableState],
              readable: true,
              [domain]: null,
              _events: [Object: null prototype],
              _eventsCount: 8,
              _maxListeners: undefined,
              _writableState: [WritableState],
              writable: true,
              allowHalfOpen: true,
              _options: [Object],
              _wrapOptions: [Object],
              _streams: [Array],
              length: 1,
              label: 'sort',
              [Symbol(kCapture)]: false,
              _writev: null,
              [writableHighWaterMark]: [Getter],
              [destroyed]: [Getter/Setter] },
           pipesCount: 1,
           flowing: true,
           ended: false,
           endEmitted: false,
           reading: true,
           sync: false,
           needReadable: true,
           emittedReadable: false,
           readableListening: false,
           resumeScheduled: false,
           destroyed: false,
           defaultEncoding: 'utf8',
           awaitDrain: 0,
           readingMore: false,
           decoder: null,
           encoding: null },
        readable: true,
        [domain]: null,
        _events:
         [Object: null prototype] {
           end: [ [Function], [Function], [Function], [length]: 3 ],
           finish: { [Function: bound onceWrapper] [length]: 0, [name]: 'bound onceWrapper', listener: [Function] },
           error: { [Function (anonymous)] [length]: 1, [name]: '', [arguments]: null, [caller]: null, [prototype]: [Object] },
           data: { [Function: ondata] [length]: 1, [name]: 'ondata', [prototype]: [Object] },
           _mutate: { [Function: bound onceWrapper] [length]: 0, [name]: 'bound onceWrapper', listener: [Function] } },
        _eventsCount: 5,
        _maxListeners: undefined,
        _writableState:
         WritableState {
           objectMode: true,
           highWaterMark: 16,
           finalCalled: false,
           needDrain: false,
           ending: false,
           ended: false,
           finished: false,
           destroyed: false,
           decodeStrings: true,
           defaultEncoding: 'utf8',
           length: 1,
           writing: true,
           corked: 0,
           sync: false,
           bufferProcessing: false,
           onwrite: { [Function (anonymous)] [length]: 1, [name]: '', [prototype]: [Object] },
           writecb: { [Function: nop] [length]: 0, [name]: 'nop', [prototype]: [Object] },
           writelen: 1,
           bufferedRequest: null,
           lastBufferedRequest: null,
           pendingcb: 1,
           prefinished: false,
           errorEmitted: false,
           bufferedRequestCount: 0,
           corkedRequestsFree: CorkedRequest { next: null, entry: null, finish: [Function] },
           [buffer]: [Getter] },
        writable: true,
        allowHalfOpen: true,
        _options: { objectMode: true },
        _wrapOptions: { objectMode: true },
        _streams:
         [ DestroyableTransform {
             _readableState: [ReadableState],
             readable: true,
             [domain]: null,
             _events: [Object: null prototype],
             _eventsCount: 4,
             _maxListeners: undefined,
             _writableState: [WritableState],
             writable: true,
             allowHalfOpen: true,
             _transformState: [Object],
             _destroyed: false,
             _transform: [Function],
             [Symbol(kCapture)]: false,
             _writev: null,
             [writableHighWaterMark]: [Getter],
             [destroyed]: [Getter/Setter] },
           [length]: 1 ],
        length: 1,
        label: 'syntax',
        [Symbol(kCapture)]: false,
        _writev: null,
        [writableHighWaterMark]: [Getter],
        [destroyed]: [Getter/Setter] } },
  shouldBeSync: undefined,
  telemetryData: undefined,
  shouldSendTelemetry: undefined }
Environment: darwin, node 14.19.0, framework 3.25.0, plugin 6.2.2, SDK 4.3.2
Docs:        docs.serverless.com
Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error:
'import' and 'export' may appear only with 'sourceType: module'
auth: start with cached data: {}, expires NaN
auth: resolved data from config: {}
auth: mode: null
telemetry: payload { ciName: null,
  isTtyTerminal: true,
  cliName: 'serverless',
  command: 'deploy',
  commandOptionNames: [ 'verbose', 'debug', 'stage', 'region', [length]: 4 ],
  console: { isAuthenticated: false },
  dashboard: { userId: null, orgUid: undefined },
  firstLocalInstallationTimestamp: 1669305495,
  frameworkLocalUserId: 'cde0c610-6c10-11ed-8287-49d5a986a63d',
  installationType: 'global:npm',
  isAutoUpdateEnabled: false,
  isUsingCompose: false,
  notificationsMode: 'on',
  timestamp: 1669393812432,
  timezone: 'Asia/Beirut',
  triggeredDeprecations: [ [length]: 0 ],
  versions: { serverless: '3.25.0', '@serverless/dashboard-plugin': '6.2.2' },
  commandDurationMs: 93817,
  hasLocalCredentials: false,
  npmDependencies:
   [ '@emotion/react',
     '@emotion/server',
     '@fortawesome/fontawesome-svg-core',
     '@fortawesome/free-regular-svg-icons',
     '@fortawesome/free-solid-svg-icons',
     '@fortawesome/react-fontawesome',
     '@mantine/core',
     '@mantine/form',
     '@mantine/hooks',
     '@mantine/next',
     '@mantine/notifications',
     '@nestjs/axios',
     '@nestjs/common',
     '@nestjs/config',
     '@nestjs/core',
     '@nestjs/passport',
     '@nestjs/platform-express',
     '@prisma/client',
     'amazon-cognito-identity-js',
     'aws-amplify',
     'aws-lambda',
     'aws-serverless-express',
     'core-js',
     'jwks-rsa',
     'next',
     'passport',
     'passport-jwt',
     'react',
     'react-dom',
     'reflect-metadata',
     'regenerator-runtime',
     'rxjs',
     'tslib',
     'zod',
     '@nestjs/schematics',
     '@nestjs/swagger',
     '@nestjs/testing',
     '@nrwl/cli',
     '@nrwl/cypress',
     '@nrwl/eslint-plugin-nx',
     '@nrwl/jest',
     '@nrwl/js',
     '@nrwl/linter',
     '@nrwl/nest',
     '@nrwl/next',
     '@nrwl/node',
     '@nrwl/react',
     '@nrwl/web',
     '@nrwl/workspace',
     '@testing-library/react',
     '@types/aws-serverless-express',
     '@types/jest',
     '@types/node',
     '@types/passport-jwt',
     '@types/react',
     '@types/react-dom',
     '@typescript-eslint/eslint-plugin',
     '@typescript-eslint/parser',
     'babel-jest',
     'babel-preset-es2015',
     'class-validator',
     'cypress',
     'eslint',
     'eslint-config-next',
     'eslint-config-prettier',
     'eslint-plugin-cypress',
     'eslint-plugin-import',
     'eslint-plugin-jsx-a11y',
     'eslint-plugin-react',
     'eslint-plugin-react-hooks',
     'jest',
     'jest-environment-jsdom',
     'nx',
     'plugin',
     'prettier',
     'prisma',
     'react-test-renderer',
     'sass',
     'serverless-offline',
     'serverless-plugin-optimize',
     'serverless-plugin-typescript',
     'serverless-webpack',
     'ts-jest',
     'ts-node',
     'typescript',
     [length]: 85 ],
  config:
   { configValidationMode: 'warn',
     provider: { name: 'aws', runtime: 'nodejs14.x', stage: 'dev', region: 'us-east-1' },
     variableSources: [ [length]: 0 ],
     plugins:
      [ 'serverless-plugin-typescript', 'serverless-plugin-optimize', 'serverless-offline', 'serverless-webpack', [length]: 4 ],
     functions: [ { url: false, runtime: 'nodejs14.x', events: [ [Object], [length]: 1 ] }, [length]: 1 ],
     resources: { general: [ [length]: 0 ] },
     paramsCount: 0 },
  isConfigValid: true,
  didCreateService: false,
  commandUsage: {} }

Environment information

Framework Core: 3.25.0
Plugin: 6.2.2
SDK: 4.3.2

serverless v0.5 and optimizer

I'm testing the v0.5 branch for the serverless guys and looks like there is a problem with the optimizer plugin and the new code. I'm able to deploy without issue if serverless-optimizer-plugin is not included in the s-project.json plugins, however once included I get the following:

Serverless: Deploying functions in "development" to the following regions: us-east-1  
Serverless: ------------------------  
Serverless: Failed to deploy the following functions in "development" to the following regions:  
Serverless: us-east-1 ------------------------  
Serverless:   listaccounts: Cannot read property 'getFunctions' of undefined  
/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:49
        fn = function () { throw arg; };
                           ^

ServerlessError: Lambda Deployment Failed.
    at new ServerlessError (/usr/local/lib/node_modules/serverless/lib/Error.js:17:11)
    at FunctionDeploy.<anonymous> (/usr/local/lib/node_modules/serverless/lib/actions/FunctionDeploy.js:137:19)
    at next (/usr/local/lib/node_modules/serverless/node_modules/rimraf/rimraf.js:74:7)
    at FSReqWrap.CB [as oncomplete] (/usr/local/lib/node_modules/serverless/node_modules/rimraf/rimraf.js:110:9)
From previous event:
    at FunctionDeploy.functionDeploy (/usr/local/lib/node_modules/serverless/lib/actions/FunctionDeploy.js:116:10)
From previous event:
    at /usr/local/lib/node_modules/serverless/lib/Serverless.js:188:29
    at Array.reduce (native)
    at /usr/local/lib/node_modules/serverless/lib/Serverless.js:187:30
From previous event:
    at Serverless._execute (/usr/local/lib/node_modules/serverless/lib/Serverless.js:185:10)
    at Serverless.actions.(anonymous function) (/usr/local/lib/node_modules/serverless/lib/Serverless.js:407:20)
    at Serverless.command (/usr/local/lib/node_modules/serverless/lib/Serverless.js:376:38)
    at /usr/local/lib/node_modules/serverless/bin/serverless:19:16
    at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
    at Object.<anonymous> (/usr/local/lib/node_modules/serverless/bin/serverless:18:4)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

Optimizer fails when deploy is started from project root

The optimizer will fail if you run a sls function deploy -a from the project root and have multiple function roots in a deeper level. It does not find the inclusion paths.

It seems the plugin does not use the magic handler strategy to find the function root from the function definitions.

If you start the deploy from the function root, it works as expected.

@doapp-ryanp I suggest that the plugin uses SLS Project to get the function root and sets its CWD to there and then executes all the stuff. Then it should work.

Optimize lib on local run

When I try sls function run ... I get the error Serverless: SyntaxError: Unexpected token import whenever I reference my files in my components lib folder which are ES6. Deploying to AWS works fine but I am unable to test locally. Unfortunately running with --debug does not give any more info about the error.

Support for source map output

It would be great is source maps were supported in the use of UglifyJS2 so it's possible to find the root cause of any issues with minified code a little easier.

It looks like it's a case of adding a merge of additional config into 'uglyOptions' which is defined here.

Configuration in s-templates.json caused `Function Deployment Failed`

Hi,

I'm trying to DRYer my s-function.json by grouping the same configuration into s-templates.json.

// s-templates.json
  ...
  "babelifyOptions": {
    "exclude": ["aws-sdk"],
    "transforms": [{
      "name": "babelify",
      "opts": {
        "presets": ["es2015"],
        "plugins": ["syntax-async-functions", "transform-regenerator"]
      }
    }],
    "minify": false
  },
  "customTemplateForBabelify": {
    "excludePatterns": [
      "node_modules"
    ],
    "optimize": "$${babelifyOptions}"
  },
  ...

When comes to s-function.json,

// Working fine
"custom": "$${customTemplateForBabelify}",

is working fine for me.

However, if I specifically inject the template to optimize field like below:

// Not working
"custom": {
  "excludePatterns": [
    "node_modules"
  ],
  "optimize": "$${babelifyOptions}"
}

Then I will get below errors:

/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:61
        fn = function () { throw arg; };
                           ^

ServerlessError: Function Deployment Failed
    at new ServerlessError (/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/lib/Error.js:17:11)
    at FunctionDeploy.<anonymous> (/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/lib/actions/FunctionDeploy.js:126:19)
    at next (/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/node_modules/rimraf/rimraf.js:74:7)
    at FSReqWrap.CB [as oncomplete] (/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/node_modules/rimraf/rimraf.js:110:9)
From previous event:
    at FunctionDeploy.functionDeploy (/home/cheehau/opt/node/node-v6.3.0-linux-x64/lib/node_modules/serverless/lib/actions/FunctionDeploy.js:105:10)
...

I'm assuming both configurations should be the exactly the same, but one succeed and one failed.
Not sure if this should be fixed.

Bump version and publish to npm

It looks like the v0.0.1 published on npm is out of date, even though the version numbers are the same.

My guess is you forgot to bump the version number and re-publish when you updated to run with Serverless v0.0.13.

How to use?

Does this need to be npm installed inside each function of the project?
Do we need to add the custom object to s-function.json shown in the readme for each function in the project?
Does this work when deploying using sls dash deploy or does it require a particular command?
Are there any global dependencies that need to be installed?

Thanks,

Joel.

Optimiser doesn't seems to work

It seems that optimizer plugin doesn't work as I am not able to get ES6 working, minification etc. In below case I try to use ES6 import but I am getting follow error SyntaxError: Unexpected reserved word which means ES6 is not compiled to ES5. Am I missing anything? Has anyone working ES6 example with latest serverless v0.4.2?

project/package.json

  "devDependencies": {
    "babelify": "7.2.0",
    "serverless-serve": "1.4.0",
    "serverless-optimizer-plugin": "1.1.0"
  }

project/s-project.json

  "plugins": [
    "serverless-serve",
    "serverless-optimizer-plugin"
  ]

project/component/package.json

  "devDependencies": {
    "babel-preset-es2015": "6.5.0"
  },

project/component/s-component.json

{
  "name": "nodejs",
  "runtime": "nodejs",
  "custom": {
    "optimize": {
      "exclude": [ "aws-sdk" ],
      "transforms": [
        {
          "name": "babelify",
          "opts": {
            "presets": [
              "es2015"
            ]
          }
        }
      ],
      "minify": true
    }
  }
}

project/component/locations/handler.js

import lib from '../lib';

Error: SyntaxError: Unexpected reserved word

IncludePaths doesn't support parent directory

Some nodejs modules doesn't compatible with optimizer, so I need to exclude the module in the exclude prop and take some includePaths directly.

The problem is that, the node_modules folder is in the root of project, my function is in the path of functions_group/functions/myfunction and handler config like functions/myfunction/handler.handler. Now I want to include specific module in node_modules, but includePaths did not support parent directory like "../parentDir".

I made a dirty hack with adding a new prop 'includeModules' to copy the specific module to the optimizer path, but I think it is not perfect.

Any ideas of this?

plugin not found

I have followed instructions from the README file except installing it from npm registry.
I installed it directly from Github in the project root

npm install serverless/serverless-optimizer-plugin

But when I run sls dash deploy, I get this warning message.

WARNING: This plugin was requested by this project but could not be found: serverless-plugin-optimizer

I have also checked node_modules, plugin is there.
What could be the problem?

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.