In serverless, webpack is used to compose the typescript and record the work done.
Basic Environment Configuration
By default, node.js
must be installed.
Install serverless.
npm install -g serverless
Then, create a project.
$ serverless create -t aws-nodejs -p hello-lambda
Serverless: Generating boilerplate...
Serverless: Generating boilerplate in "/home/gyuha/workspace/hello-lambda"
_______ __
| _ .-----.----.--.--.-----.----| .-----.-----.-----.
| |___| -__| _| | | -__| _| | -__|__ --|__ --|
|____ |_____|__| \___/|_____|__| |__|_____|_____|_____|
| | | The Serverless Application Framework
| | serverless.com, v1.32.0
-------'
Serverless: Successfully generated boilerplate for template: "aws-nodejs"
$ cd hello-lambda
Set package.jon
with npm init
and install the necessary packages.
$ npm init
$ npm install --save-dev serverless-webpack serverless-offline ts-loader typescript webpack
Setting up Severless
Edit the serverless.yml
file as shown below.
service: aws-nodejs # NOTE: update this with your service name
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: ap-northeast-2
plugins:
-serverless-webpack
-serverless-offline
functions:
hello:
handler: src/server.hello
events:
-http:
path: hello
method: get
Here, the main contents are the addition of plugins and the addition of events in functions.
Configuring Typescript and Webpack
Create tsconfig.json
file and enter as below.
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
Create webpack.copnfg.js
file and enter as below.
const path = require("path");
module.exports = {
entry: path.join(__dirname, "src/server.ts"),
output: {
libraryTarget: "commonjs",
filename: "src/server.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
}
};
Write Source
Create src/server.ts
file and input as below.
interface SomeResponse {
statusCode: number;
body: string;
}
export async function hello (event: any, context: any) {
const response: SomeResponse = {
statusCode: 200,
body: JSON.stringify({
message: Math.floor(Math.random() * 10)
})
};
return response
};
When you’re done so far… the default run is configured.
Running offline
sls offline
Deploy
sls deploy