【发布时间】:2016-10-14 00:55:56
【问题描述】:
如何使用调试器(如 Google Chrome 调试器)逐行逐行调试我的 gulpfile.js
中定义的 gulp 任务?
【问题讨论】:
标签: javascript node.js debugging gulp
如何使用调试器(如 Google Chrome 调试器)逐行逐行调试我的 gulpfile.js
中定义的 gulp 任务?
【问题讨论】:
标签: javascript node.js debugging gulp
使用 Node.js 版本 6.3+,您可以在运行任务时使用 --inspect
flag。
调试名为css
的 gulp 任务:
找出 gulp 可执行文件的位置。如果 gulp 安装在本地,它将位于 node_modules/.bin/gulp
。如果 gulp 已全局安装,请在终端中运行 which gulp
(Linux/Mac) 或 where gulp
(Windows) 以找到它。
根据您的 Node.js 版本运行这些命令之一。如果需要,请将./node_modules/.bin/gulp
替换为步骤 1 中的 gulp 安装路径。
node --inspect --debug-brk ./node_modules/.bin/gulp css
node --inspect-brk ./node_modules/.bin/gulp css
使用 Chrome 浏览至chrome://inspect
。
--debug-brk
(Node.js 6.3+) 和 --inspect-brk
(Node.js 7+) 标志用于暂停任务第一行代码的代码执行。这让您有机会在任务完成之前打开 Chrome 调试器并设置断点。
如果您不希望调试器在第一行代码处暂停,只需使用 --inspect
标志。
您还可以为 Chrome 安装 Node.js Inspector Manager (NIM) 扩展程序以帮助完成第 3 步。这将自动打开一个 Chrome 选项卡,其中准备好调试器,作为手动浏览到 URL 的替代方法。
【讨论】:
require(env.configPath);
之后添加一个断点 - 加载您的 gulpfile,以便您可以在 Sources 中找到它并添加断点。
chrome://inspect
,不需要知道devtools地址
--inspect-brk
./node_modules/gulp/bin/gulp.js
而不是./node_modules/.bin/gulp
对于使用 VS Code 1.10+ 的任何人
这就是您的 launch.json 文件的外观。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Gulp task",
"program": "${workspaceFolder}/node_modules/gulp/bin/gulp.js",
"args": [
"yourGulpTaskName"
]
}
]
}
【讨论】:
console.log(...)
语句的方法反而起作用了。
Gulpfile.js
的事实有关,因为我将其重命名为 gulpfile.js
,现在触发了断点(我在 Windows 上使用 VS Code 1.45.1)。
感谢 user2943490,在 Windows 上我发现这个版本对我有用:
node --inspect --debug-brk ./node_modules/gulp/bin/gulp.js --verbose
【讨论】:
如果您使用 gulp-nodemon,您可以在 gulpfile 中执行此操作。 只需将 execMap 选项传递给它:
gulp.task('default', function() {
nodemon({
script: 'server.js',
ext: 'js',
execMap: {
js: "node --inspect"
}
})
}
希望这会有所帮助。
【讨论】:
版本(节点 v8.11.3,npm 6.2.0,gulp 3.9.1)
Windows 10 和 git bash
安装Node.js V8 --inspector Manager (NiM) 并设置为您的preference
试试这个:
node --inspect-brk ./node_modules/gulp/bin/gulp.js --verbose
【讨论】:
我喜欢@Avi Y 的回答。但我想人们会欣赏更完整的脚本:
gulp.task('nodemon', ['sass'], function(cb) {
var started = false;
consoleLog('nodemon started');
return nodemon({
//HERE REMOVE THE COMMENT AT THE BEGINING OF THE LINE YOU NEED
//exec: 'node --inspect --debug-brk node_modules/gulp/bin/gulp.js',
exec: 'node --inspect --debug-brk',
//exec: 'node --inspect',
script: path.server,
ignore: ['*/gulpfile.js', 'node_modules/*'],
verbose: true
}).on('start', function() {
if (!started) {
cb();
started = true;
}
}).on('restart', function() {
consoleLog('nodemon restarted the server');
});});
【讨论】: