TypeScript, AWS SAM and Rollup.js

Henrik Hauge Bjørnskov
1 min readJul 16, 2019

--

This time we are using Rollup instead of Webpack and it is super easy. Also it requires less configuration.

Before going further I suggest you read the other blog post which will explain the conventions behind the Rollup configuration.

Rollup Configuration

// rollup.config.js
import fs from 'fs'
import CloudFormation from 'yaml-cfn'
import typescript from 'rollup-plugin-typescript'
import nodeResolve from 'rollup-plugin-node-resolve'
const defaultConfig = {
plugins: [
nodeResolve(),
typescript(),
],
output: {
format: 'commonjs',
},
external: [
'aws-sdk',
],
}
const { Resources } = CloudFormation.yamlParse(fs.readFileSync('template.yml'))const entries = Object.values(Resources)
.filter(resource => resource.Type == 'AWS::Serverless::Function')
.filter(resource => resource.Properties.Runtime.startsWith('nodejs'))
.map(resource => {
const file = resource.Properties.Handler.split('.')[0]
const prefix = resource.Properties.CodeUri.substr(8)
return Object.assign({}, defaultConfig, {
input: `${prefix}/${file}.ts`,
output: {
format: 'cjs',
dir: `.rollup/${prefix}`,
}
})
})
export default entries

AWS SAM Template

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Resources:
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: index.handler
Runtime: nodejs10.x
CodeUri: .rollup/packages/my-function

Result

$ yarn rollup -c rollup.config.jspackages/my-function/index.ts → .rollup/packages/my-function...
created .rollup/packages/my-function in 283ms

When developing you would want to start it in watch mode with --watch. Then you can always use sam local invoke as normal.

--

--

Henrik Hauge Bjørnskov

I build stuff at Relatel A/S, vivid traveller and gear junkie.