【问题标题】:how to implement regions/code collapse in javascript如何在javascript中实现区域/代码折叠
【发布时间】:2010-12-27 15:45:11
【问题描述】:

如何在 Visual Studio 中为 JavaScript 实现区域(也称为代码折叠)?

如果 javascript 中有数百行,那么在 vb/C# 中使用带有区域的代码折叠会更容易理解。

#region My Code

#endregion

【问题讨论】:

标签: javascript visual-studio folding code-regions


【解决方案1】:

Blog entry here explains it 和这个MSDN question

您必须使用 Visual Studio 2003/2005/2008 宏。

为了保真,从博客条目中复制 + 粘贴:

  1. 打开宏浏览器
  2. 创建新宏
  3. 将其命名为OutlineRegions
  4. 单击编辑宏并粘贴以下 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
  1. 保存宏并关闭编辑器
  2. 现在让我们为宏分配快捷方式。转到工具->选项->环境->键盘并在“显示包含的命令”文本框中搜索您的宏
  3. 现在在“按下快捷键”下的文本框中,您可以输入所需的快捷键。我使用 Ctrl+M+E。我不知道为什么 - 我只是第一次输入它现在使用它:)

【讨论】:

  • 这个很有用,从网站的 cmets 中要注意的重要一点是“您必须检查上面代码中的模块名称与新宏的名称。两个名称必须匹配!”
  • 这适用于 VS2010 吗?我无法到达。搜索时未显示宏。
  • @Mr. Flibble:不确定.. 我只有 VS2005。
  • 好的。我在这里提出了一个新问题:stackoverflow.com/questions/2923177/…
  • 微软现在有一个 VS2010 的扩展来提供这个功能(见我的回答下面的链接)。
【解决方案2】:

感谢0A0D 的精彩回答。我很幸运。 Darin Dimitrov 也为限制 JS 文件的复杂性提出了很好的论据。不过,我确实发现在某些情况下,将函数折叠到它们的定义中会使浏览文件变得更加容易。

关于#region 一般而言,这个SO Question 很好地涵盖了它。

我对宏进行了一些修改以支持更高级的代码折叠。此方法允许您在 //#region 关键字 ala C# 之后放置描述,并在代码中显示如下:

示例代码:

//#region InputHandler
var InputHandler = {
    inputMode: 'simple', //simple or advanced

    //#region filterKeys
    filterKeys: function(e) {
        var doSomething = true;
        if (doSomething) {
            alert('something');
        }
    },
    //#endregion filterKeys

    //#region handleInput
    handleInput: function(input, specialKeys) {
        //blah blah blah
    }
    //#endregion handleInput

};
//#endregion InputHandler

更新宏:

Option Explicit On
Option Strict On

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module JsMacros


    Sub OutlineRegions()
        Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection, EnvDTE.TextSelection)

        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 New Stack(Of Integer)

        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 ...
                Dim tempStartIndex As Integer = CInt(startRegions.Pop())
                selection.MoveToLineAndOffset(CalcLineNumber(text, tempStartIndex), CalcLineOffset(text, tempStartIndex))
                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) As Integer
        Dim lineNumber As Integer = 1
        Dim i As Integer = 0

        While i < index
            If text.Chars(i) = vbLf Then
                lineNumber += 1
                i += 1
            End If

            If text.Chars(i) = vbCr Then
                lineNumber += 1
                i += 1
                If text.Chars(i) = vbLf Then
                    i += 1 'Swallow the next vbLf
                End If
            End If

            i += 1
        End While

        Return lineNumber
    End Function

    Private Function CalcLineOffset(ByVal text As String, ByVal index As Integer) As Integer
        Dim offset As Integer = 1
        Dim i As Integer = index - 1

        'Count backwards from //#region to the previous line counting the white spaces
        Dim whiteSpaces = 1
        While i >= 0
            Dim chr As Char = text.Chars(i)
            If chr = vbCr Or chr = vbLf Then
                whiteSpaces = offset
                Exit While
            End If
            i -= 1
            offset += 1
        End While

        'Count forwards from //#region to the end of the region line
        i = index
        offset = 0
        Do
            Dim chr As Char = text.Chars(i)
            If chr = vbCr Or chr = vbLf Then
                Return whiteSpaces + offset
            End If
            offset += 1
            i += 1
        Loop

        Return whiteSpaces
    End Function

End Module

【讨论】:

  • VS 2010 有一个更新的扩展框架,有人很好地在这里创建了一个名为“Visual Studio 2010 JavaScript Outlining”的代码折叠插件:jsoutlining.codeplex.com
  • 我们可以用 C# 代替 VB 编写宏吗?
【解决方案3】:

Visual Studio 的JSEnhancements 插件很好地解决了这个问题。

【讨论】:

  • 这正是我想要的。谢谢。
【解决方案4】:

Microsoft 现在有一个提供此功能的 VS 2010 扩展:

JScript Editor Extensions

【讨论】:

  • 这太棒了!我希望他们将其包含在下一个 VS 更新中。感谢分享!
  • 非常棒的扩展,比第三方大纲扩展还要好。
  • 在 VS 2012 和 2013 中发生了什么?
  • 这太棒了!有 VS 2012 或 2013 的版本吗?
【解决方案5】:

对于那些即将使用 Visual Studio 2012 的人,存在 Web Essentials 2012

对于即将使用 Visual Studio 2015 的用户,Web Essentials 2015.3

用法和@prasad问的一模一样

【讨论】:

  • +1 - 这应该是答案,因为大多数人现在将使用 2012/2013! (它也适用于 2013 年)
【解决方案6】:

通过标记一段代码(不考虑任何逻辑块)并按 CTRL + M + H,您可以将所选内容定义为可折叠和可展开的区域。

【讨论】:

【解决方案7】:

不仅适用于 VS,而且几乎适用于所有编辑器。

(function /* RegionName */ () { ... })();

警告:有范围等缺点。

【讨论】:

    【解决方案8】:

    很简单!

    标记您要折叠的部分,然后,

    Ctrl+M+H

    并在其左侧使用“+”标记进行扩展。

    【讨论】:

    • 成功了!救了我,因为它使我的代码看起来更苗条,因为我在单个 ajax 调用下有很多 ajax 调用。
    • 这是一个临时解决方案。如果您关闭并重新打开文件,则所选区域会消失。
    【解决方案9】:

    在 VS 2012 和 VS 2015 上安装 WebEssentials 插件即可。

    http://vswebessentials.com/features/javascript

    【讨论】:

      【解决方案10】:

      对于正在使用最新版本 Visual Studio 的开发人员来说是个好消息

      Web Essentials 带有此功能。

      Check this out

      注意:对于 VS 2017,请使用 JavaScript 区域: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions

      【讨论】:

      • @William 总有一天人们肯定会需要这个 ;)
      • 随着时间的推移,这将是事实上接受的答案。
      • 与 2019 年 6 月 10 日的最新版本的 VSCode - Typescript 完美搭配。
      • 这也适用于 VS2019,我没有安装 Web Essentials。
      • @LukeVo 然后似乎 vs2019 内置支持这个,
      【解决方案11】:

      如果您使用的是Resharper

      放松这张照片中的步骤

      然后在模板编辑器中写这个

        //#region $name$
      $END$$SELECTION$
        //#endregion $name$
      

      并将其命名为#region,如图所示

      希望对你有帮助

      【讨论】:

        【解决方案12】:

        这些答案都不适用于 Visual Studio 2017。

        VS 2017 最佳插件:JavaScript Regions

        示例 1:

        示例 2:

        测试和批准:

        【讨论】:

        • 你的答案只是重复this one
        • 正如我在编辑历史中看到的,在 2016 年首次提交后,图片 URL 没有任何变化
        【解决方案13】:

        现在在 VS2017 中原生:

        //#region fold this up
        
        //#endregion
        

        // 和 # 之间的空格无关紧要。

        我不知道这是在哪个版本中添加的,因为我在更改日志中找不到任何提及。我可以在 v15.7.3 中使用它。

        【讨论】:

          【解决方案14】:

          适用于 Visual Studio 2017。

              //#region Get Deactivation JS
              .
              .
              //#endregion Get Deactivation JS
          

          这之前不工作,所以我从here下载了扩展

          扩展名(JavaScript 区域)作者:Mads Kristensen

          【讨论】:

            【解决方案15】:

            区域应该在不更改设置的情况下工作

            //#region Optional Naming
                var x = 5 -0; // Code runs inside #REGION
                /* Unnecessary code must be commented out */
            //#endregion
            

            启用折叠评论区/**/

            /* Collapse this
            
            */
            

            设置 -> 搜索“折叠” -> 编辑器:折叠策略 -> 从“自动”到“缩进”。

            标签:Node.js Nodejs 节点 js Javascript ES5 ECMAScript 注释折叠隐藏区域 Visual Studio Code vscode 2018 1.2+版本 https://code.visualstudio.com/updates/v1_17#_folding-regions

            【讨论】:

              【解决方案16】:

              它在 PhpStorm 中就像一个魅力

              //#region My Region 1
                  ...
              //#endregion
              
              //#region My Region 2
                  ...
              //#endregion
              
              

              【讨论】:

                【解决方案17】:

                对于 VS 2019,这应该可以在不安装任何东西的情况下工作:

                    //#region MyRegion1
                
                    foo() {
                
                    }
                
                    //#endregion
                
                    //#region MyRegion2
                
                    bar() {
                
                    }
                
                    //#endregion
                

                【讨论】:

                  【解决方案18】:

                  对于那些来这里使用 Visual Studio 代码的人来说,同样的语法也适用

                  // #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
                  

                  折叠后如下图所示

                  【讨论】:

                    猜你喜欢
                    • 2014-07-23
                    • 2011-01-24
                    • 2010-11-08
                    • 1970-01-01
                    • 2014-06-02
                    • 1970-01-01
                    • 2022-11-30
                    • 2012-08-25
                    • 1970-01-01
                    相关资源
                    最近更新 更多