简体   繁体   English

如何在 Twilio Functions 中使用自定义模块?

[英]How to use custom modules in Twilio Functions?

I was looking for a way to simplify and extract some of the code into a custom common.js module to make my Twilio function more readable.我一直在寻找一种方法来简化并将一些代码提取到自定义 common.js 模块中,以使我的 Twilio 函数更具可读性。

I was expecting the serverless api to take the custom js file automatically and let me require it where I wanted it, but after deploying, it cant be found.我期待无服务器 api 自动获取自定义 js 文件,并让我在我想要的地方需要它,但是在部署之后,它就找不到了。

Is there a proper way if any, to do something like:如果有的话,是否有适当的方法来执行以下操作:

const utils = require('./libs/utils.js');
exports.handler = async function(context, event, callback) {
    ...
    utils.do_this();

Trying this brings me to:尝试这个让我:

{"Message":"Cannot find module './libs/utils.js'\nRequire stack:\n- /var/task/handlers/ZN5be18c53f5acf0299a224607fdeccedb.js\n- /var/task/node_modules/runtime-handler/index.js\n- /var/task/runtime-handler.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","name":"Error","stack":"Error: Cannot find module './libs/utils.js'\nRequire stack:\n- /var/task/handlers/ZN5be18c53f5acf0299a224607fdeccedb.js\n- /var/task/node_modules/runtime-handler/index.js\n- /var/task/runtime-handler.js\n- /...

Swimming deep in Twilio's doc swamp, I noticed there is a hint on how to do this .在 Twilio 的文档沼泽深处游泳,我注意到有一个关于如何做到这一点的提示

Basically you MUST基本上你必须

  1. Add the .js file as an PRIVATE ASSET <- IMPORTANT!将 .js 文件添加为私有资产 <- 重要! *unprotected wont work! *不受保护的不起作用! ie if your file name is utils.js , rename it to utils.private.js即,如果您的文件名为utils.js ,请将其重命名为utils.private.js
  2. Get the path of that asset in the following way:通过以下方式获取该资产的路径:
// notice you don't need to write .private.
const path = Runtime.getAssets()['/utils.js'].path; 
  1. Require the path inside the handler:需要处理程序内部的路径:
exports.handler = async function(context, event, callback) {
     const path = Runtime.getAssets()['/utils.js'].path; 
     const utils = require(path);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM