如何在javascript中实现区域/代码折叠

发布于 2024-08-15 15:12:36 字数 164 浏览 5 评论 0原文

如何在 Visual Studio 中实现 JavaScript 的区域(又名代码折叠)?

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

#region My Code

#endregion

How can you implement regions a.k.a. code collapse for JavaScript in Visual Studio?

If there are hundreds of lines in javascript, it'll be more understandable using code folding with regions as in vb/C#.

#region My Code

#endregion

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

魔法唧唧 2024-08-22 15:12:36

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

Web Essentials 即将附带此功能。

看看这个

在此处输入图像描述

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

Good news for developers who is working with latest version of visual studio

The Web Essentials are coming with this feature .

Check this out

enter image description here

Note: For VS 2017 use JavaScript Regions : https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions

栖竹 2024-08-22 15:12:36

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

JScript 编辑器扩展

Microsoft now has an extension for VS 2010 that provides this functionality:

JScript Editor Extensions

柳絮泡泡 2024-08-22 15:12:36

那很容易!

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

Ctrl+M+H

并使用左侧的“+”标记展开。

Thats easy!

Mark the section you want to collapse and,

Ctrl+M+H

And to expand use '+' mark on its left.

黑白记忆 2024-08-22 15:12:36

对于那些即将使用 Visual Studio 2012 的用户,可以使用 Web Essentials 2012

对于那些即将使用 Visual Studio 2015 的用户,存在 Web Essentials 2015.3

用法与@prasad询问的完全一样

For those about to use the visual studio 2012, exists the Web Essentials 2012

For those about to use the visual studio 2015, exists the Web Essentials 2015.3

The usage is exactly like @prasad asked

小…红帽 2024-08-22 15:12:36

此处的博客条目对此进行了解释 以及此 MSDN 问题

您必须使用 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。我不知道为什么 - 我刚刚第一次输入并现在使用它:)

Blog entry here explains it and this MSDN question.

You have to use Visual Studio 2003/2005/2008 Macros.

Copy + Paste from Blog entry for fidelity sake:

  1. Open Macro Explorer
  2. Create a New Macro
  3. Name it OutlineRegions
  4. Click Edit macro and paste the following VB code:
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. Save the Macro and Close the Editor
  2. Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox
  3. now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+E. I don't know why - I just entered it first time and use it now :)
神经暖 2024-08-22 15:12:36

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

By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.

十二 2024-08-22 15:12:36

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

The JSEnhancements plugin for Visual Studio addresses this nicely.

木落 2024-08-22 15:12:36

对于那些来到这里使用 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

在折叠时有效,如下所示

在此处输入图像描述

For those who have come here for Visual Studio Code, the same syntax works

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

When collapsed, it looks like below

enter image description here

违心° 2024-08-22 15:12:36

感谢 0A0D 提供了很好的答案。我很幸运。 Darin Dimitrov 还就限制 JS 文件的复杂性提出了很好的论点。尽管如此,我确实发现有时将函数折叠到其定义可以使浏览文件变得更加容易。

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

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

示例代码:

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

Thanks to 0A0D for a great answer. I've had good luck with it. Darin Dimitrov also makes a good argument about limiting the complexity of your JS files. Still, I do find occasions where collapsing functions to their definitions makes browsing through a file much easier.

Regarding #region in general, this SO Question covers it quite well.

I have made a few modifications to the Macro to support more advanced code collapse. This method allows you to put a description after the //#region keyword ala C# and shows it in the code as shown:

Example code:

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

Updated Macro:

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
饮惑 2024-08-22 15:12:36

现在,这在 VS2017 中是原生的:

//#region fold this up

//#endregion

// 和 # 之间的空格并不重要。

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

This is now natively in VS2017:

//#region fold this up

//#endregion

Whitespace between the // and # does not matter.

I do not know what version this was added in, as I cannot find any mention of it in the changelogs. I am able to use it in v15.7.3.

黯淡〆 2024-08-22 15:12:36

对于 VS 2019,这应该无需安装任何东西即可工作:

在此处输入图像描述

    //#region MyRegion1

    foo() {

    }

    //#endregion

    //#region MyRegion2

    bar() {

    }

    //#endregion

For VS 2019, this should work without installing anything:

enter image description here

    //#region MyRegion1

    foo() {

    }

    //#endregion

    //#region MyRegion2

    bar() {

    }

    //#endregion
花辞树 2024-08-22 15:12:36

它就像 PhpStorm

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

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

我的地区

It works like a charm in PhpStorm

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

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

my regions

沫尐诺 2024-08-22 15:12:36

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

http://vswebessentials.com/features/javascript

On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.

http://vswebessentials.com/features/javascript

人│生佛魔见 2024-08-22 15:12:36

对于 Visual Studio 2017。

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

这之前不起作用,所以我从此处下载了扩展

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

For visual studio 2017.

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

This was not working earlier so I downloaded extension from here

Extension Name(JavaScript Regions) By Mads Kristensen

篱下浅笙歌 2024-08-22 15:12:36

如果您使用 Resharper

请按照此图片中的步骤

在此处输入图像描述
然后在模板编辑器中编写此内容

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

并将其命名为 #region ,如下图所示
输入图像描述这里

希望这对您有帮助

if you are using Resharper

fallow the steps in this pic

enter image description here
then write this in template editor

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

and name it #region as in this picture
enter image description here

hope this help you

掩饰不了的爱 2024-08-22 15:12:36

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

的最佳插件: JavaScript 区域

示例 1:

在此处输入图像描述

示例 2:

在此处输入图像描述

已测试并批准:

在此处输入图像描述

None of these answers did not work for me with visual studio 2017.

The best plugin for VS 2017: JavaScript Regions

Example 1:

enter image description here

Example 2:

enter image description here

Tested and approved:

enter image description here

胡大本事 2024-08-22 15:12:36

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

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

要启用折叠评论区域 /**/

/* Collapse this

*/

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

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

Region should work without changing settings

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

To enable collapsing comment area /**/

/* Collapse this

*/

Settings -> Search "folding" -> Editor: Folding Strategy -> From "auto" to "indentation".

TAGS: Node.js Nodejs Node js
Javascript ES5 ECMAScript comment folding hiding region
Visual studio code vscode 2018 version 1.2+
https://code.visualstudio.com/updates/v1_17#_folding-regions

你爱我像她 2024-08-22 15:12:36

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

(function /* 区域名称 */ () { ... })();

警告:有范围等缺点。

Not only for VS but nearly for all editors.

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

Warning: has disadvantages such as scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文