"Cannot find package '#aws-sdk/client-dynamodb' on Appsync Amazon - amazon-web-services

I am deploying on amazon using CI/CD pipeline using Github action.Deployed on Amazon successfully but when I run the graphql query on appsync it show that the #aws-sdk/client-dynamodb not found.
You can see the error on this image
succesfully deployed on github
I add dynamodb package on package.json
`{
"name": "Serverless-apix",
"type": "module",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "sls offline start --stage local",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#aws-sdk/client-dynamodb": "^3.215.0",
"ramda": "^0.28.0",
"serverless": "^3.24.1",
"serverless-appsync-plugin": "^1.14.0",
"serverless-iam-roles-per-function": "^3.2.0"
},
"devDependencies": {}
}`
Controller Where I call the Dynamodb
`import { PutItemCommand } from "#aws-sdk/client-dynamodb";
import { ddbClient } from "../../dynamodb/db.js";`
Db file
`import { DynamoDBClient } from "#aws-sdk/client-dynamodb";
const REGION = "us-east-1"; //e.g. "us-east-1"
// const client = new DynamoDBClient({
// // region: "us-east-1",
// // accessKeyId: "AKIA272VV64HPNKION2R",
// // secretAccessKeyId: "7IARIpa5q8ZEf0NQKKsUPTDP+oszFaw+Dd5v4s7N",
// // endpoint: "http://localhost:8000"
// region: 'localhost',
// endpoint: 'http://localhost:8000'
// });
const ddbClient = new DynamoDBClient({ region: REGION });
export { ddbClient };å`
Serverless file
`service: image-base-serverless-api
provider:
name: aws
runtime: nodejs14.x
stage: ${opt:stage, 'dev'}
region: us-east-1
environment:
# DYNAMODB_TABLE_NAME: ${self:custom.usersTableName}
STAGE: ${self:provider.stage}
REGION: ${self:provider.region}
APPSYNC_NAME: "${self:custom.defaultPrefix}-appsync"
SERVICE_NAME: ${self:service}-${self:provider.stage}
DYNAMODB: ${self:service}-${self:provider.stage}
TABLE_NAME:
Ref: usersTable
iam:
role:
statements: # permissions for all of your functions can be set here
- Effect: Allow
Action: # Gives permission to DynamoDB tables in a specific region
- dynamodb:*
- lambda:*
- s3:*
Resource:
- arn:aws:dynamodb:${self:provider.region}:*:*
- arn:aws:lambda:${self:provider.region}:*:*
- "Fn::GetAtt": [usersTable, Arn]
plugins: ${file(plugins/plugins-${self:provider.stage}.yml)}
package:
exclude:
- node_modules/**
- venv/**
custom:
usersTableName: users-table-${self:provider.stage}
dynamodb:
stages:
- local
start:
port: 8000
inMemory: false
dbPath: "dynamodb_local_data"
migrate: true
appSync:
name: image-base-serverless-backened-api-${self:provider.stage}
schema: schema.graphql
authenticationType: API_KEY
serviceRole: "AppSyncServiceRole"
mappingTemplates: ${file(appsync/mappingtemplate.yml)}
dataSources: ${file(appsync/datasource.yml)}
appsync-offline: # appsync-offline configuration
port: 62222
dynamodb:
client:
endpoint: "http://localhost:8000"
region: localhost
defaultPrefix: ${self:service}-${self:provider.stage}
functions:
- ${file(src/adminusers/admin-user-route.yml)}
resources:
# Roles
- ${file(resources/roles.yml)}
# DynamoDB tables
- ${file(resources/dynamodb-tables.yml)}
# - ${file(resources/dynamodb.yml)}
# - ${file(resources/iam.yml)}
`
I Shall be very thankfull if you help me to solve this error
I downgrade the node version and also try deploy the amazon directly and also deploy the code using CI/CD pipeline but its show the same error on each tried.I have

Related

Serverless Error: TypeError: Cannot read property 'options' of undefined

I'm trying to upgrade my serverless app from 1.51.0 to 2.7.0
while deploying the app I'm getting the below error:
[08:39:38] 'dev:sls-deploy' errored after 9.85 s
[08:39:38] TypeError: Cannot read property 'options' of undefined
at module.exports (/home/jenkins/workspace/TMC-Broker/DEV/node_modules/serverless/lib/utils/telemetry/generatePayload.js:236:66)
at PluginManager.run (/home/jenkins/workspace/TMC-Broker/DEV/node_modules/serverless/lib/classes/PluginManager.js:685:9)
08:39:38.428520 durable_task_monitor.go:63: exit status 1
First I thought it might be due to plugins I updated the plugins but still not able to resolve.
Here is my serverless.yml:
service: my-service
plugins:
- serverless-webpack
- serverless-step-functions
- serverless-es-logs
- serverless-domain-manager
- serverless-plugin-ifelse
- serverless-prune-plugin
- serverless-offline
provider:
name: aws
runtime: nodejs12.x
timeout: 30
stage: dev
region: us-west-2
lambdaHashingVersion: 20201221
endpointType: PRIVATE
role: lambdaExecutionRole
apiGateway:
resourcePolicy:
- Effect: Allow
Principal: "*"
Action: execute-api:Invoke
Resource: "*"
- Effect: Deny
Principal: "*"
Action: execute-api:Invoke
Resource: "*"
Condition:
StringNotEquals:
aws:SourceVpce:
- "vpce-************"
environment:
APP_SERVICE: ${self:service}
APP_ENV: ${self:custom.stage}
APP_REGION: ${self:custom.region}
BUCKET_NAME: ${self:service}-${self:custom.stage}-#{aws:accountId}-onboard-s3
LOG_REQUEST_ID: "x-request-id"
custom:
prune:
automatic: true
includeLayers: true
number: 5
serverlessIfElse:
- If: '"${self:custom.stage}" == "uat"'
Exclude:
- functions.abc-handler
- If: '"${self:custom.stage}" == "prod"'
Exclude:
- functions.abc-handler
region: ${self:provider.region}
stage: ${opt:stage, self:provider.stage}
prefix: ${self:service}-${self:custom.stage}
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
functions:
ms4-handler:
handler: src/apifunctions/my.handler
events:
- http:
path: /hello
method: ANY
- http:
path: /hello/{proxy+}
method: ANY
resources:
Resources:
onboardingBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: ${self:service}-${self:custom.stage}-#{aws:accountId}-onboard-s3
LifecycleConfiguration:
Rules:
- Id: expirationRule
Status: "Enabled"
ExpirationInDays: 10
Jenkins Deployment Steps:
#!groovy
import groovy.json.JsonSlurperClassic
pipeline {
agent {label 'ecs-tf12'}
stage('Serverless Deploy') {
agent {
docker {
label "ecs"
image "node:10.15"
args "-u 0:0"
}
}
steps {
script {
sh 'node --version'
sh 'npm --version'
sh 'npm config set registry http://registry.npmjs.org'
sh 'npm install -g serverless#2.7.0'
sh 'npm list -g serverless'
sh 'npm install -g typescript#3.9.10'
sh 'npm install'
sh "npx gulp install-terraform-linux"
sh 'cp -v serverless-private.yml serverless.yml'
sh "sls create_domain --stage ${params.env}"
sh "npx gulp ${params.env}:sls-deploy"
sh 'cp -v serverless-public.yml serverless.yml'
sh "sls create_domain --stage ${params.env}"
sh "npx gulp ${params.env}:sls-deploy"
}
}
}
}
My Package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "Serverless Service",
"scripts": {
"build": "tslint --project tsconfig.json **/*.ts && serverless package",
"deploy": "tslint --project tsconfig.json **/*.ts && serverless deploy",
"offline": "tslint --project tsconfig.json **/*.ts && serverless offline"
},
"dependencies": {
"ajv": "^6.10.2",
"axios": "^0.27.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"https-proxy-agent": "^4.0.0",
"joi": "^17.4.0",
"json-stream-stringify": "^2.0.4",
"launchdarkly-node-server-sdk": "^6.4.3",
"lodash": "^4.17.21",
"serverless-domain-manager": "^5.1.1",
"serverless-http": "^2.7.0",
"serverless-step-functions": "^2.23.0",
"source-map-support": "^0.5.16",
"uuid": "^3.3.3",
"xml-js": "^1.6.11"
},
"devDependencies": {
"#hewmen/serverless-plugin-typescript": "^1.1.17",
"#types/aws-lambda": "8.10.39",
"#types/body-parser": "^1.17.1",
"#types/express": "^4.17.2",
"#types/lodash": "^4.14.149",
"#types/node": "^13.1.6",
"#types/uuid": "^3.4.6",
"aws-sdk": "^2.1204.0",
"execa": "^4.0.0",
"gulp": "^4.0.2",
"serverless": "^2.7.0",
"serverless-es-logs": "^3.4.2",
"serverless-offline": "^8.0.0",
"serverless-plugin-ifelse": "^1.0.7",
"serverless-plugin-typescript": "^1.2.0",
"serverless-prune-plugin": "^2.0.1",
"serverless-webpack": "^5.5.0",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.9.10",
"typescript-tslint-plugin": "^0.5.5",
"webpack": "^4.41.5",
"webpack-node-externals": "^1.7.2"
},
"author": "The serverless webpack authors (https://github.com/elastic-coders/serverless-webpack)",
"license": "MIT"
}
I'm not able to figure out the reason and solution for this.
any Ideas?
Found a similar question: but it doesn't resolve as I'm using 2.7.0

Nuxt 3 in AWS Lambda with Serverless Framework

I try to deploy simple Nuxt 3 application to AWS Lambda for SSR. So far I have:
in nitro.config.ts
import { defineNitroConfig } from 'nitropack';
export default defineNitroConfig({
preset: 'aws-lambda',
serveStatic: true
});
in Lambda handler
import { handler } from './output/server/index.mjs';
export const runner = (event, context) => {
const { statusCode, headers, body } = handler({ rawPath: '/' });
return {
statusCode,
body,
headers
}
}
in serverless.yaml
functions:
ssr:
handler: handler.runner
timeout: 15
package:
individually: true
include:
- output/**
events:
- httpApi:
path: '*'
method: '*'
I run yarn build, change .output folder name to output to be able to include it with package, but I still have errors like "errorMessage": "SyntaxError: Cannot use import statement outside a module".
Is someone has idea how it could be done?
Its easier than that bro, nuxt already exports the handler nothing for us to do:
serverles.yml:
service: nuxt-app-lamba
provider:
name: aws
runtime: nodejs14.x
stage: dev
region: us-east-1
functions:
nuxt:
handler: .output/server/index.handler
events:
- httpApi: '*'
nuxt.config.ts:
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
nitro: {
preset: 'aws-lambda',
serveStatic: true
}
})
package.json:
{
"private": true,
"scripts": {
"build": "nuxt build",
"build:lamba": "NITRO_PRESET=aws-lambda nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"deploy": "sls deploy"
},
"devDependencies": {
"nuxt": "3.0.0-rc.11"
}
}
This example is not working anymore (2022.12.09):
Working example: https://8cyysz2g5f.execute-api.us-east-1.amazonaws.com/

Serverless: Configuration error at root: unrecognized property 'stepFunctions'

I have some strange errors and I can not find out the reason, can you help me?
...
Serverless: Warning: Unable to find plugin named: TypeScriptPlugin
Serverless: Configuration error at root: unrecognized property 'stepFunctions'
...
serverless.yml
service:
name: service-name
plugins:
- serverless-localstack
- serverless-step-functions
- serverless-pseudo-parameters
- serverless-webpack
custom:
webpackIncludeModules: true
localstack:
stages:
- local
host: http://localhost
edgePort: 4566
autostart: true
lambda:
mountCode: false
debug: true
docker:
sudo: true
provider:
configValidationMode: off
deploymentBucket:
name: local
name: aws
runtime: nodejs12.x
stage: ${opt:stage, "dev"}
region: ${env:AWS_REGION, "us-east-1"}
logRetentionInDays: 30
functions:
...
stepFunctions:
...
package.json
{
"name": "service-name",
"version": "0.119.0",
"description": "Service decription.",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.2.0",
"babel-core": "^6.26.0",
"babel-loader": "^8.0.5",
"babel-plugin-source-map-support": "^2.0.1",
"babel-preset-env": "^1.6.1",
"serverless": "^1.40.0",
"serverless-localstack": "^0.4.27",
"serverless-pseudo-parameters": "^1.4.2",
"serverless-step-functions": "^1.11.0",
"serverless-webpack": "^4.4.0",
"webpack": "^3.11.0",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"babel-runtime": "^6.26.0",
"source-map-support": "^0.5.9"
}
}
This is just a bug with the package serverless-step-functions
This can be resolved by updating the library :)
"serverless-step-functions": "^2.23.x",

AWS Cloudformation template for a codepipeline with jenkins build stage

I need to write a CFT for pipeline with Jenkins integration for build/test. I found this documentation to setup ActionTypeId for the jenkins stage. But this doc does not specify how to set the server url of the jenkins server. And also it is not clear to me where to give the Jenkins Provider name. Is it in the ActionTypeId or in configuration properties?
I could not find any example for this use case in the internet as well.
Please provide a proper example for setup Jenkins Action Provider for AWS Codepipeline using AWS Cloudformation template.
Following is a section from the sample cft I wrote from what I learnt from above doc.
"stages": [
{
"name": "Jenkins",
"actions": [
...
{
"name": "Jenkins Build",
"actionTypeId": {
"category": "Build",
"owner": "Custom",
"provider": "Jenkins",
"version": "1"
},
"runOrder": 2,
"configuration": {
???
},
...
}
]
},
...
]
The piece of information which was missing for me was that I need to create a Custom Action to use Jenkins as the Action provider for my codepipeline.
First I added the custom action as below:
JenkinsCustomActionType:
Type: AWS::CodePipeline::CustomActionType
Properties:
Category: Build
Provider: !Ref JenkinsProviderName
Version: 1
ConfigurationProperties:
-
Description: "The name of the build project must be provided when this action is added to the pipeline."
Key: true
Name: ProjectName
Queryable: false
Required: true
Secret: false
Type: String
InputArtifactDetails:
MaximumCount: 5
MinimumCount: 0
OutputArtifactDetails:
MaximumCount: 5
MinimumCount: 0
Settings:
EntityUrlTemplate: !Join ['', [!Ref JenkinsServerURL, "/job/{Config:ProjectName}/"]]
ExecutionUrlTemplate: !Join ['', [!Ref JenkinsServerURL, "/job/{Config:ProjectName}/{ExternalExecutionId}/"]]
Tags:
- Key: Name
Value: custom-jenkins-action-type
The jenkins server URL is given in the settings for Custom Action
and the Jenkins provider name is given for Provider. Which were the
issues I had initially.
Then configure the pipeline stage as following:
DevPipeline:
Type: AWS::CodePipeline::Pipeline
DependsOn: JenkinsCustomActionType
Properties:
Name: Dev-CodePipeline
RoleArn:
Fn::GetAtt: [ CodePipelineRole, Arn ]
Stages:
...
- Name: DevBuildVerificationTest
Actions:
- Name: JenkinsDevBVT
ActionTypeId:
Category: Build
Owner: Custom
Version: 1
Provider: !Ref JenkinsProviderName
Configuration:
# JenkinsDevBVTProjectName - Jenkins Job name defined as a parameter in the CFT
ProjectName: !Ref JenkinsDevBVTProjectName
RunOrder: 4
The Custom Action has to be created before the Pipeline. Hence DependsOn: JenkinsCustomActionType

Getting Sequelize.js library to work on Amazon Lambda

So I'm trying to run a lambda on amazon and narrowed down the error finally by testing the lambda in amazons testing console.
The error I got is this.
{
"errorMessage": "Please install mysql2 package manually",
"errorType": "Error",
"stackTrace": [
"new MysqlDialect (/var/task/node_modules/sequelize/lib/dialects/mysql/index.js:14:30)",
"new Sequelize (/var/task/node_modules/sequelize/lib/sequelize.js:234:20)",
"Object.exports.getSequelizeConnection (/var/task/src/twilio/twilio.js:858:20)",
"Object.<anonymous> (/var/task/src/twilio/twilio.js:679:25)",
"__webpack_require__ (/var/task/src/twilio/twilio.js:20:30)",
"/var/task/src/twilio/twilio.js:63:18",
"Object.<anonymous> (/var/task/src/twilio/twilio.js:66:10)",
"Module._compile (module.js:570:32)",
"Object.Module._extensions..js (module.js:579:10)",
"Module.load (module.js:487:32)",
"tryModuleLoad (module.js:446:12)",
"Function.Module._load (module.js:438:3)",
"Module.require (module.js:497:17)",
"require (internal/module.js:20:19)"
]
}
Easy enough, so I have to install mysql2. So I added it to my package.json file.
{
"name": "test-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 0"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"aws-sdk": "^2.153.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
"serverless-domain-manager": "^1.1.20",
"serverless-dynamodb-autoscaling": "^0.6.2",
"serverless-webpack": "^4.0.0",
"webpack": "^3.8.1",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"babel-runtime": "^6.26.0",
"mailgun-js": "^0.13.1",
"minimist": "^1.2.0",
"mysql": "^2.15.0",
"mysql2": "^1.5.1",
"qs": "^6.5.1",
"sequelize": "^4.31.2",
"serverless": "^1.26.0",
"serverless-plugin-scripts": "^1.0.2",
"twilio": "^3.10.0",
"uuid": "^3.1.0"
}
}
I noticed when I do sls deploy however, it seems to only be packaging some of the modules?
Serverless: Package lock found - Using locked versions
Serverless: Packing external modules: babel-runtime#^6.26.0, twilio#^3.10.0, qs#^6.5.1, mailgun-js#^0.13.1, sequelize#^4.31.2, minimi
st#^1.2.0, uuid#^3.1.0
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
................................
Serverless: Stack update finished...
I think this is why it's not working. In short, how do I get mysql2 library to be packaged correctly with serverless so my lambda function will work with the sequelize library?
Please note that when I test locally my code works fine.
My serverless file is below
service: testapi
# Use serverless-webpack plugin to transpile ES6/ES7
plugins:
- serverless-webpack
- serverless-plugin-scripts
# - serverless-domain-manager
custom:
#Define the Stage or default to Staging.
stage: ${opt:stage, self:provider.stage}
webpackIncludeModules: true
#Define Databases Here
databaseName: "${self:service}-${self:custom.stage}"
#Define Bucket Names Here
uploadBucket: "${self:service}-uploads-${self:custom.stage}"
#Custom Script setup
scripts:
hooks:
#Script below will run schema changes to the database as neccesary and update according to stage.
'deploy:finalize': node database-schema-update.js --stage ${self:custom.stage}
#Domain Setup
# customDomain:
# basePath: "/"
# domainName: "api-${self:custom.stage}.test.com"
# stage: "${self:custom.stage}"
# certificateName: "*.test.com"
# createRoute53Record: true
provider:
name: aws
runtime: nodejs6.10
stage: staging
region: us-east-1
environment:
DOMAIN_NAME: "api-${self:custom.stage}.test.com"
DATABASE_NAME: ${self:custom.databaseName}
DATABASE_USERNAME: ${env:RDS_USERNAME}
DATABASE_PASSWORD: ${env:RDS_PASSWORD}
UPLOAD_BUCKET: ${self:custom.uploadBucket}
TWILIO_ACCOUNT_SID: ""
TWILIO_AUTH_TOKEN: ""
USER_POOL_ID: ""
APP_CLIENT_ID: ""
REGION: "us-east-1"
IDENTITY_POOL_ID: ""
RACKSPACE_API_KEY: ""
#Below controls permissions for lambda functions.
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:UpdateTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-1:*:*"
functions:
create_visit:
handler: src/visits/create.main
events:
- http:
path: visits
method: post
cors: true
authorizer: aws_iam
get_visit:
handler: src/visits/get.main
events:
- http:
path: visits/{id}
method: get
cors: true
authorizer: aws_iam
list_visit:
handler: src/visits/list.main
events:
- http:
path: visits
method: get
cors: true
authorizer: aws_iam
update_visit:
handler: src/visits/update.main
events:
- http:
path: visits/{id}
method: put
cors: true
authorizer: aws_iam
delete_visit:
handler: src/visits/delete.main
events:
- http:
path: visits/{id}
method: delete
cors: true
authorizer: aws_iam
twilio_send_text_message:
handler: src/twilio/twilio.send_text_message
events:
- http:
path: twilio/sendtextmessage
method: post
cors: true
authorizer: aws_iam
#This function handles incoming calls and where to route it to.
twilio_incoming_call:
handler: src/twilio/twilio.incoming_calls
events:
- http:
path: twilio/calls
method: post
twilio_failure:
handler: src/twilio/twilio.twilio_failure
events:
- http:
path: twilio/failure
method: post
twilio_statuschange:
handler: src/twilio/twilio.statuschange
events:
- http:
path: twilio/statuschange
method: post
twilio_incoming_message:
handler: src/twilio/twilio.incoming_message
events:
- http:
path: twilio/messages
method: post
twilio_whisper:
handler: src/twilio/twilio.whisper
events:
- http:
path: twilio/whisper
method: post
- http:
path: twilio/whisper
method: get
twilio_start_call:
handler: src/twilio/twilio.start_call
events:
- http:
path: twilio/startcall
method: post
- http:
path: twilio/startcall
method: get
resources:
Resources:
uploadBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: ${self:custom.uploadBucket}
RDSDatabase:
Type: AWS::RDS::DBInstance
Properties:
Engine : mysql
MasterUsername: ${env:RDS_USERNAME}
MasterUserPassword: ${env:RDS_PASSWORD}
DBInstanceClass : db.t2.micro
AllocatedStorage: '5'
PubliclyAccessible: true
#TODO: The Value of Stage is also available as a TAG automatically which I may use to replace this manually being put here..
Tags:
-
Key: "Name"
Value: ${self:custom.databaseName}
DeletionPolicy: Snapshot
DNSRecordSet:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneName: test.com.
Name: database-${self:custom.stage}.test.com
Type: CNAME
TTL: '300'
ResourceRecords:
- {"Fn::GetAtt": ["RDSDatabase","Endpoint.Address"]}
DependsOn: RDSDatabase
UPDATE:: So I confirmed that running sls package --stage dev seems to create this in the zip folder that would eventually upload to AWS. This confirms that serverless is not creating the package correctly with the mysql2 reference for some reason? Why is this?
webpack config file as requested
const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: slsw.lib.entries,
target: "node",
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: __dirname,
exclude: /node_modules/
}
]
}
};
Thanks to dashmugs comment after some investigation on this page (https://github.com/serverless-heaven/serverless-webpack), there is a section on Forced Inclusion. I'll paraphrase it here.
Forced inclusion Sometimes it might happen that you use dynamic
requires in your code, i.e. you require modules that are only known at
runtime. Webpack is not able to detect such externals and the compiled
package will miss the needed dependencies. In such cases you can force
the plugin to include certain modules by setting them in the
forceInclude array property. However the module must appear in your
service's production dependencies in package.json.
# serverless.yml
custom:
webpackIncludeModules:
forceInclude:
- module1
- module2
So I simply did this...
webpackIncludeModules:
forceInclude:
- mysql
- mysql2
Now it works! Hope this helps someone else with the same issue.
None of the previous helped me, I used this solution: https://github.com/sequelize/sequelize/issues/9489#issuecomment-493304014
The trick is to use dialectModule property and override sequelize.
import Sequelize from 'sequelize';
import mysql2 from 'mysql2'; // Needed to fix sequelize issues with WebPack
const sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect: 'mysql',
dialectModule: mysql2, // Needed to fix sequelize issues with WebPack
host: process.env.DB_HOST,
port: process.env.DB_PORT
}
)
export async function connectToDatabase() {
console.log('Trying to connect via sequelize')
await sequelize.sync()
await sequelize.authenticate()
console.log('=> Created a new connection.')
// Do something
}
The previous so far works on MySql but is not working with Postgres