NodeJS 减小lambda的googleapis包大小

mspsb9vt  于 2023-02-03  发布在  Node.js
关注(0)|答案(2)|浏览(110)

我正在使用一个无服务器应用程序来处理我的API调用
我正在使用googleapis软件包中的google.auth.GoogleAuthgoogle.androidpublisher
可以上传到lambda的代码大小有限制,googleapis115 MB,这是巨大的!!!
我发现一篇文章说,调用像const {androidpublisher_v3} = require('googleapis/build/src/apis/androidpublisher')这样的包会减小包的大小,但事实并非如此。
运行sls package时,我总是有115 MB的googleapis
有什么办法可以减少这种情况吗?我想自己给电话编码,但这需要几个小时的工作

mwg9r5ms

mwg9r5ms1#

选项1:使用打包工具

看一下https://github.com/floydspace/serverless-esbuild,一旦设置好,它将通过只包含Lambda实际导入的代码来执行树摇动以减少代码大小。
因此,如果您在代码中提到const {androidpublisher_v3} = require('googleapis/build/src/apis/androidpublisher')esbuild将只包含googleapis包中AndroiPublisher模块所需的部分。

    • 优点:**通用方式,自动;
    • 缺点:**一些带有本机代码的包可能会中断,需要排除;慢的

选项2:从node_modules中删除不需要的文件

当您使用yarn package manager而不是npm时,您可以在安装过程中从node_modules中提供您想要自动清理的exclusion list路径。
我写了一篇关于这个主题的深度文章:https://itnext.io/3x-smaller-lambda-artifacts-by-removing-junk-from-node-modules-2b50780ca1f5
实际上,您可以在存储库中创建一个包含以下内容的.yarnclean文件:

**/googleapis/build/src/apis/compute
**/googleapis/build/src/apis/dfareporting
**/googleapis/build/src/apis/displayvideo
**/googleapis/build/src/apis/healthcare
**/googleapis/build/src/apis/dialogflow
**/googleapis/build/src/apis/retail
**/googleapis/build/src/apis/securitycenter
# ... more rules to follow

继续列出Lambda中不需要的文件夹。
特别是对于googleapis Package ,通过从 Package 中删除类型,可以删除约70%的伪影大小。
您只在开发期间需要TypeScript类型,而在Lambda运行时不需要。
因此,您可以在创建工件之前将此代码添加到CI管道中。
仅通过执行以下代码片段,我就能够将代码的大小从111 MB减少到20 MB:

npx del-cli \
  "node_modules/**/@types/**" \
  "node_modules/**/*.d.ts" \
  "node_modules/**/.yarn-integrity" \
  "node_modules/**/.bin"

希望能有所帮助!

yrefmtwq

yrefmtwq2#

现在你可以通过导入树摇动子模块来减少大小。
yarn add @googleapis/androidpublisher
然后像这样导入const androidPublisher = require('@googleapis/androidpublisher');
以下是其他网站的列表https://github.com/googleapis/google-cloud-node#google-cloud-nodejs-client-libraries

相关问题