Serverless webpack (Babel)

KyungUp·2022년 10월 10일
0

AWS

목록 보기
2/3
post-custom-banner

요구 사항

Serverless offline 프로젝트가 필요.

webpack 및 babel 관련된 패키지 설치

$ npm install --save-dev webpack serverless-webpack webpack-node-externals @babel/cli @babel/core @babel/preset-env babel-loader

added 169 packages, and audited 815 packages in 6s

130 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

webpack.config.js 파일 생성

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

module.exports = {
    entry: serverlessWebpack.lib.entries,
    target: "node",
    externals: [nodeExternals()],
    mode: serverlessWebpack.lib.webpack.isLocal ? "development" : "production",
    module: {
        rules: [
            {
                loader: "babel-loader",
                include: __dirname,
                exclude: /node_modules/
            }
        ]
    }
}

webpack custom 및 plugins 추가

// serverless.yml

...

custom:
  webpack: 
    webpackConfig: ./webpack.config.js
    includeModules: true

...

plugins:
  - serverless-webpack
  - serverless-offline

commonjs > ES 변경

// handler.js

module.exports.hello = async (event) => { // commonjs
  return {
    statusCode: 200,
    body: JSON.stringify('Hello')
  }
}

export const hello = async () => { // ES Module
    return {
        statusCode: 200,
        body: JSON.stringify('Hello')
    }
}

sls offline start

$ sls offline start


> aws-node-project@1.0.0 start
> sls offline start


Starting Offline at stage dev (us-east-1)

Offline [http for lambda] listening on http://localhost:3002
Function names exposed for local invocation by aws-sdk:
           * hello: aws-node-project-dev-hello

   ┌─────────────────────────────────────────────────────────────────────────┐
   │                                                                         │
   │   GET | http://localhost:3000/dev/api/v1/hello                          │
   │   POST | http://localhost:3000/2015-03-31/functions/hello/invocations   │
   │                                                                         │
   └─────────────────────────────────────────────────────────────────────────┘

Server ready: http://localhost:3000 🚀

└ [Webpack] Watch service...

메소드 확인

샘플 코드

https://github.com/wonkyungup/serverless-template/tree/serverless-webpack

profile
Last Epoch하고싶다
post-custom-banner

0개의 댓글