如何在 Windows 10 的 VS Code 上调试 Amplify JavaScript 函数?
这个问题在 github 上出现在 How to debug amplify function using visual studio code during invocation?,但它已经关闭并且很旧。例如,
amplify invoke function
已被弃用,取而代之的是 amplify mock function
。
我试过这个
launch.config
:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Create Reort",
"type": "node",
"request": "launch",
"program": "${env:APPDATA}/npm/node_modules/@aws-amplify/cli/bin/amplify",
"args": [
"mock",
"function",
"sayhello",
"--event",
"src/event.json",
"--timeout",
"0"
],
"console": "integratedTerminal"
}
]
}
这将记录输出,但不会在正在执行的函数内命中任何断点:
安装 amplify cli
npm install -g @aws-amplify/cli
初始化放大。选择任何框架的 JavaScript。
amplify init
# Choose your default editor: Visual Studio Code
# Choose the type of app that you're building: javascript
# What javascript framework are you using: none
添加功能
amplify add function SayHello
# Choose the runtime that you want to use: NodeJS
# Choose the function template that you want to use: Hello World
这是一个有点老套的解决方法。
据我所知,对于单次执行,lambda 并没有那么神奇(运行时环境中的特殊调味料、事件处理和自动可伸缩性)。 Amplify CLI 从
event
传入 event.json
对象并调用定义为处理程序的函数。你也可以在 vanilla node js 中做到这一点。
创建一个像
debug.js
这样的文件——你可以把它放在任何你想要的地方,但我的在.vscode
目录
const { handler } = require("../amplify/backend/function/sayHello/src")
const event = require("../amplify/backend/function/sayHello/src/event.json")
(async function(){
// invoke
const response = await handler(event)
console.log(response)
})()
然后你可以像这样使用普通的 node js 调试启动配置:
{
"name": "Debug Function",
"program": "${workspaceFolder}/.vscode/debug.js",
"request": "launch",
"skipFiles": ["<node_internals>/**"],
"type": "pwa-node"
}
一些更友好/开箱即用的东西会很好,但这至少允许在没有太多额外工作的情况下逐步调试。
这曾经在旧版本的 VS Code 中工作。我打开了https://github.com/aws-amplify/amplify-cli/issues/6894希望能解决这个问题。
与此同时,这里建议使用 Node 的注入器的另一个 hacky 解决方法。将此代码添加到处理程序方法的顶部(确保在提交之前将其删除):
require('inspector').open(9229, '127.0.0.1', true);
debugger;
一定要在 launch.json 中的 amplify mock 命令中设置足够长的超时时间。要逐步执行代码,您可以使用 Chrome 的 Node 调试器,方法是导航至 about:inspect 并单击“Open dedicated DevTools for Node”。
在使用了几年不可调试的 amplify cli 之后,我刚刚获得了使用 VS Code 调试内联放大的 100% 工作方式,我在 this git issue 上对此进行了更详细的解释。希望它能帮助其他正在寻找相同的人