在我的团队中,我们决定不使用无服务器框架。相反,我们使用 cdk 和 lambda 层以及用于 nodejs 的 aws-sdk v3 (typescript)。对于 lambda 层,我提供 node_modules 文件夹并在我自己的 lambda 中引用该层。但我之前也玩过 webpack,请参阅下面的配置文件。 dist 文件夹中的结构需要在 cdk 中易于引用。我认为在您的情况下,您只需更改 webpack.config.js 文件中的库目标,它也应该在浏览器中工作。
webpack.config.js
// webpack.config.js -> we´ve only one config for production/dev -> context: lambda (no minifiying etc. needed)
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
module.exports = {
target: "node14", // needed to build proper nodejs14 code (without browser stuff)
mode: 'development',
context: __dirname, // to automatically find tsconfig.json
entry: {
callCreateLogs: './src/functions/callCreateLogs/index.ts',
// TODO: add new functions here, maybe later here an additional script will do this for us (the key must match to the folder for right cdk reference)
},
devtool: 'inline-source-map', // to find errors (we use that also in productions for backend lambdas)
output: {
filename: '[name]/index.js', // generated file based on the entry key
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs', // important for aws lambda context
},
plugins: [
new CleanWebpackPlugin(), // clean up dist folder before build
],
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
// disable type checker - we will use it in fork plugin
transpileOnly: true
}
}
]
},
plugins: [new ForkTsCheckerWebpackPlugin()]
};
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["es2020"],
"esModuleInterop": true,
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": false,
"sourceMap": true,
"strictPropertyInitialization": false,
"typeRoots": ["./node_modules/@types"],
"outDir": "dist"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "**/*.spec.ts", "test"]
}
这里有一个 cdk sn-p:
this.CreateLogLambda = new lambda.Function(this, 'createLogLambda', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset(path.resolve(__dirname, '../../../../backend/dist/createLogs')), // hint: only directory which include the file (no filename here)
handler: 'index.handler', // filename.methodname (without file extension),
//role: createLogsLambdaExecutionRole
});