AWS CDK Nodejs功能:导入导出为“export =”的模块

问题描述 投票:0回答:2

有没有办法在使用

export = someModule
中的
NodejsFunction
定义的 Lambda 函数中使用导出为
aws-cdk-lib
的模块(例如 Sharp)?
require 语句(
const xxx = require('module')
) 似乎不适用于 CDK 捆绑的 Lambda TypeScript 代码。

以下两种导入写入方式均导致错误。

import sharp from 'sharp'
import * as sharp from 'sharp'
import sharp = require('sharp')
Something went wrong installing the \"sharp\" module
Cannot find module '../build/Release/sharp-linux-x64.node'
Require stack:
- /var/task/index.js
- /var/runtime/index.mjs

CDK代码定义Lambda函数如下。

import { aws_lambda_nodejs as lambda } from 'aws-cdk-lib'

const fn = new lambda.NodejsFunction(scope, 'fn-id', {
  entry: 'lib/lambda/my-fn.ts',
  functionName: 'fn-name'
})
typescript aws-cdk commonjs esmodules
2个回答
0
投票

如果您为 NodejsFunction 引入

node_modules
external modules
,则需要在 CDK 堆栈中指定它。

查看捆绑选项了解更多信息。

这是一个使用

externalModules
nodeModules
layers
访问资源的示例。

this.lambdaFunctionExample= new NodejsFunction(this, `lambdaFunctionExample`, {
  runtime: Runtime.NODEJS_18_X,
  handler: "handler",
  bundling: { minify: false, nodeModules: ["@aws-sdk/client-sfn", "axios", "axios-retry"], externalModules: ["aws-sdk", "crypto-js"] },
  layers: [lambdaLayerStack.getSecrets, lambdaLayerStack.generateMagentoAuthorisationHeader]
});

0
投票

如果您在 M1 上构建,则必须安装 Sharp via

npm install --platform=linux --arch=x64 sharp

否则您将在 lambda 执行时收到以下错误:

Could not load the \"sharp\" module using the linux-x64 runtime\

安装 Sharp 后,您可以像这样导入它:

import sharp from 'sharp' // typescript

const sharp = require("sharp") // javascript

如果您在

cdk deploy

上遇到此错误
[ERROR] No loader is configured for ".node" files: asset-input/node_modules/sharp/build/Release/sharp-linux-x64.node

将以下选项添加到您的

NodejsFunction
以将
sharp
定义为应该安装而不是捆绑的模块

const fn = new lambda.NodejsFunction(scope, 'fn-id', {
  entry: 'lib/lambda/my-fn.ts',
  functionName: 'fn-name',
  bundling: {
    nodeModules: ['sharp'],
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.