Visual Studio - 如何在 JavaScript 中實現區域/代碼折疊
如何在 Visual Studio 中為 JavaScript 實現區域(即代碼折疊)?
如果在 JavaScript 中有數百行程式碼,使用像 VB/C# 中的區域折疊功能會更容易理解。
#region My Code
#endregion
答案#1
對於使用最新版本 Visual Studio 的開發者來說,是個好消息
網頁精華將隨這個功能一起推出。
看看這個
注意:對於 VS 2017 使用 JavaScript 區域 : https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions
答案#2
微軟現在為 VS 2010 提供了一個擴充功能,提供此功能:
JScript 編輯器擴充功能
答案#3
那很容易!
標記你想要折疊的部分,並且,
Ctrl+M+H
並在其左側使用「+」號來展開。
答案#4
對於那些即將使用 Visual Studio 2012 的人,有 Web Essentials 2012
對於那些準備使用 Visual Studio 2015 的人,存在 Web Essentials 2015.3
使用方法正如 @prasad 所問的一樣
答案#5
這裡的部落格文章解釋了它,還有這個 MSDN 問題。
你必須使用 Visual Studio 2003/2005/2008 巨集。
為了忠實起見,從部落格文章複製並貼上:
- 打開巨集瀏覽器
- 建立新巨集
- 將其命名為
OutlineRegions - 點擊編輯巨集並貼上以下的 VB 代碼:
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections
Public Module JsMacros
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As Stack = New Stack()
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
End If
i += 1
End While
Return lineNumber
End Function
End Module
- 儲存巨集並關閉編輯器
- 現在讓我們為巨集指派快捷鍵。前往 工具->選項->環境->鍵盤,並在「顯示包含的命令」文本框中搜尋你的巨集
- 現在在「按快捷鍵」下方的文字框中,你可以輸入想要的快捷鍵。我使用 Ctrl+M+E。我也不知道為什麼——我第一次輸入它,現在就一直用它 :)
答案#6
透過標記一段程式碼(不論任何邏輯區塊)並按下 CTRL + M + H,你將把所選的部分定義為可摺疊和展開的區域。
答案#7
Visual Studio 的 JSEnhancements 外掛程式很好地解決了這個問題。
答案#8
對於那些來這裡尋找 Visual Studio Code 的人,相同的語法也適用
// #region MongoDB Client
const MongoClient = require('mongodb').MongoClient;
const url = constants.credentials["uat"].mongo.url
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, client) {
if (err) {
console.log(err);
}
else {
docDB = client.db("middlewareDB");
}
});
// #endregion
縮起來時,看起來如下

