我不喜欢 Node 的一件事是,一旦添加一个 require("whatever")
,你最终会得到 1000 个调用 require
的传递依赖项> 如果可能需要该代码。
var whatever = require('whatever');
if (probablyFalse) {
whatever.theOnlyFunctionThatIUse();
// ...but `whatever` et al require other libraries which I won't actually use
}
我想构建一个包来部署在 Google Cloud Functions(以及 Lambda 上的类似应用程序)上。我的代码导入@google-cloud/datastore,它具有许多传递依赖项,其中一些具有二进制文件、计算导入等。我不想遇到包大小限制或增加 Node 解析代码所需的时间。我想使用一种打包工具来进行树摇动并将(大部分)我的代码和依赖项编译到一个文件中。我希望能够指定从 index.js
中排除哪些库,并仅在 node_modules
下提供必要的文件。
因为我正在编译 Typescript 并在构建/测试/打包/部署过程中使用其他库,所以 node_modules 包含 100-1000 个库,其中大部分在生产中不需要。
理想情况下,我希望能够构建如下所示的东西:
- package.json - {“main”:“index.js”,依赖项:{“@google-cloud/datastore”:“1.4.1”}}
- index.js - 从我的项目中的多个 TypeScript 文件以及我从库和传递依赖项导入的大部分代码编译
- node_modules - 所有代码,但仅限于未包含在 index.js 中但运行应用程序所需的代码。
我创建了一个简单的演示应用程序来展示我正在尝试执行的操作(当前我正在使用 FuseBox ):
https://github.com/nalbion/packaged-google-function/blob/master/lib/demo.js
为了从我编译的 demo.js 中排除 @google-cloud/datastore 及其传递依赖项,我添加了一个 filterFile:
filterFile: file => {
return !['@google-cloud/datastore'].includes(file.collection.name);
},
我对输出中的行感到困惑:
FuseBox.pkg("@google-cloud/datastore", {}, function(___scope___){
return ___scope___.entry = "src/index.js";
});
Google Cloud Functions 也很困惑:
TypeError: Cannot read property 'default' of null
at helloWorld (/user_code/demo.js:10:42)
仅供引用,在我尝试添加数据存储代码之前,演示一直在运行:
https://github.com/nalbion/packaged-google-function/blob/no-dependencies/lib/demo.js
我怀疑 filterFile 不适用于此目的,或者可能我使用错误。
FuseBox 中是否有等效的工具来过滤包?
有更好的方法吗?
(编辑) 私有(private) git 存储库存在一个已知问题:
https://github.com/GoogleCloudPlatform/nodejs-docs-samples/issues/300
Auto deploy Google Cloud Functions from Google Cloud Source Control
最佳答案
你会做太多不必要的工作。
Google 云函数 automatically handles dependencies部署后,通过 npm 将它们安装在服务器上(假设依赖项已在 package.json 中列出)。它不上传node_modules的内容。不要费心去尝试创建依赖项的具体化版本,除非您确实不希望 GCF 自动从 npm 安装它们。
关于node.js - 如何打包 Lambda/Google Cloud Functions,而不包含所有不必要的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51182288/