如何通過vscode運行調試javascript代碼
初次正式要寫 javascript 相關的代碼,想要用 vscode 直接編譯 js 代碼,但是發現沒有那么簡單,需要配置好 launch.json 文件,現已經在vscode上編譯過去并且可以調試 javascript 代碼,總結了兩種方法,分享給大家.
方法一: 在 js 后綴文件中寫 javascript 代碼.
1. 環境配置:
(1). 需要安裝 nodejs (在Bing搜索中輸入 nodejs, 找到nodejs官網,然后找到適合你電腦配置的安裝包進行下載安裝,最后要輸入 node -v 和 npm -v 檢驗是否安裝成功)
(2). 可以安裝 vscode 擴展包: Code Runner
2. 新建一個 js 后綴的文件,如 hello_world.js ,輸入以下內容:
var a = 1;var b = 2;console.log('hello world');console.log('a = ', a);console.log('b = ', b);
3. 運行程序
(1) 如果你安裝了 Code Runer,那么就可以直接點擊右鍵選擇 Run Code 運行代碼,就可以在 OUTPUT 窗口上看到運行結果
(2) 在 vscode 的 TERMINAL 終端輸入: node hello_world.js 也可以看到 運行結果
(3) 想要按下 F5 進行運行并且調試,那么就要配置好 launch.json 文件. 先點擊 Run -> Open Configurations, 輸入以下內容
{ // 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': [{ 'name': 'Launch', 'type': 'node', 'request': 'launch', 'program': '${workspaceRoot}/hello_world.js', }, ]}
注意這里的第 11 行的文件名稱要改成你自己定義的文件名稱,其中的workspaceRoot 表示當前文件路徑.
再按下 F5 的時候,記得配置文件一定要選擇名為 Launch (和上面的name同名) 的那個配置文件運行,配置了 launch.json 文件,你還可以在 js 文件中打上斷點進行調試.如下圖所示
方法二: 在 html 后綴文件中寫 javascript 代碼.
1. 環境配置:
(1) 安裝 chrome 瀏覽器(做前端開發這是通用瀏覽器)
(2) 安裝 vscode 擴展包: Debugger for chrome 和 open in browser
(3) File -> Preferences -> Settings, 輸入 breakpoints,找到 Debug: Allow Breakpoints Everywhere,勾上允許在任何文件設置斷點(這樣才可以在html文件中設置斷點)
2. 新建一個 html 后綴的文件,如 a.html ,輸入以下內容:
<!DOCTYPE html><html><head><script>function myFunction(){ console.log('hello world'); document.getElementById('demo').innerHTML='My First JavaScript Function'; alert('this is a place where can write code.');}</script></head><body><h1>My Web Page</h1><p id='demo'>A Paragraph</p><button type='button' onclick='myFunction()'>Try it</button></body></html>
3. 運行程序
(1) 按下 F5 運行并且調試代碼,這里主要涉及到 launch.json 文件的配置,先點擊 Run -> Open Configurations, 輸入以下內容
{ // 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': 'chrome', 'request': 'launch', 'name': 'Launch Chrome against localhost', 'url': 'http://localhost:8080', 'webRoot': '${workspaceFolder}' }, { 'type': 'chrome', 'request': 'launch', 'name': '使用本地chrome調試', 'file': '${file}', 'port':8000, } ]}
然后在 script 的代碼部分打上斷點,按下 F5 , 點擊 Try it 按鈕,你可以看到中間結果了,如下圖所示
(2) 鼠標右鍵點擊 Open in Other Browsers, 選擇其中 一個瀏覽器就可以看到結果,再點擊按鈕出現的網頁中的 Try it 按鍵,就可以調用 script 中 js 的代碼的結果. 這里,你也可以在vscode中設置你的默認瀏覽器,那么你就可以選擇Open in Default Browers, 在默認的瀏覽器中打開, 或者按下快捷鍵 Alt + B 查看結果. (這種方法不能調試,并且這種方法只能在配置好launch.json后再按下F5之后才可以使用)
(備注: vscode 默認瀏覽器的設置, File -> Preferences -> Settings, 輸入 default browser , 找到 Open-in-browser : Default , 我這里是輸入了 : Google Chrome )
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: