Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serverless webpack doesn't bundle handlers.js

I am new to webpack and serverless, so please forgive me if this seems trivial. I copied these codes from npm serverless-webpack.

I tried to use serverless webpack --out dist, but my command line didn't recognise webpack. If I tried to serverless deploy <opts> <opt>, then it compiled and bundled into a .serverless but missing the essential JS files.

webpack.config.js

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

module.exports = {
  context: path.resolve(__dirname, './src'),
  entry: slsw.lib.entries,
  target: 'node',
  externals: [nodeExternals()],
  output: {
    libraryTarget: 'commonjs',
    path: path.resolve(__dirname, '.webpack'),
    filename: '[name].js',
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        loader: ["babel-loader"],
        include: __dirname,
        exclude: /node_modules/
      }
    ]
  }
};

Serverless.yml

service: hello-world
frameworkVersion: '>=1.2.0 <2.0.0'
provider:
  name: aws
  runtime: nodejs8.10
  deploymentBucket:
     name: test-bucket
plugin:
  - serverless-webpack
  - serverless-prune-plugin
custom:
  prune:
    automatic: true
    number: 3
  webpack: webpack.config.js
  webpackIncludeModules:
    packagePath: ./src/package.json
    forceInclude:
       - express
       - body-parser
functions:
  getHelloWorld:
    handler: functions/test.hello
    events:
      - http:
          path: test/hello
          method: get  

webpack: 4.22.0 (global)

serverless-webpack: 5.3.0 (global)

like image 216
roger Avatar asked Oct 23 '18 13:10

roger


1 Answers

  1. First, install webpack.

    npm install --save-dev webpack
    
  2. Install plugin serverless webpack

    npm install serverless-webpack --save-dev
    
  3. Add plugin to serverless.yml

    service: hello-world
    plugins:
        - serverless-webpack
    custom:
        webpackIncludeModules: true
    
  4. Your package.json will be something that:

    "scripts": {
        "test-process": "mocha --require babel-core/register ./tests/unit.test.js",
        "deploy": "./node_modules/.bin/serverless remove --stage dev --region us-east-1 && ./node_modules/.bin/serverless deploy -v --stage dev --region us-east-1"
    }
    
  5. Then, you can deploy with this command: npm run deploy

  6. Also, with mocha you can test your code before doing the deploy. For that, you will have that configure babel

I prepare you a basic example hello-world with webpack4 and serverless:

https://github.com/ns4lin4s/stackoverflow

Don't forget, add response application/json in apigateway:

enter image description here

let me know how did work..

like image 178
ene_salinas Avatar answered Oct 17 '22 00:10

ene_salinas