简体   繁体   English

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

[英]how to implement regions/code collapse in javascript

How can you implement regions aka code collapse for JavaScript in Visual Studio?如何在 Visual Studio 中为 JavaScript 实现区域又名代码折叠?

If there are hundreds of lines in javascript, it'll be more understandable using code folding with regions as in vb/C#.如果 javascript 中有数百行,那么在 vb/C# 中使用带有区域的代码折叠会更容易理解。

#region My Code

#endregion

Good news for developers who is working with latest version of visual studio对于正在使用最新版本的 Visual Studio 的开发人员来说是个好消息

The Web Essentials are coming with this feature . Web Essentials将提供此功能。

Check this out看看这个

在此处输入图片说明

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

Microsoft now has an extension for VS 2010 that provides this functionality: Microsoft 现在为VS 2010提供了一个扩展,可以提供以下功能:

JScript Editor Extensions JScript 编辑器扩展

Thats easy!这很容易!

Mark the section you want to collapse and,标记要折叠的部分,然后,

Ctrl+M+H Ctrl+M+H

And to expand use '+' mark on its left.并扩展使用其左侧的“+”标记。

For those about to use the visual studio 2012, exists the Web Essentials 2012对于那些即将使用 Visual Studio 2012 的人,存在Web Essentials 2012

For those about to use the visual studio 2015, exists the Web Essentials 2015.3对于那些即将使用 Visual Studio 2015 的人,存在Web Essentials 2015.3

The usage is exactly like @prasad asked用法与@prasad 所问的完全一样

Blog entry here explains it and this MSDN question . 此处的博客条目解释了它和这个MSDN 问题

You have to use Visual Studio 2003/2005/2008 Macros.您必须使用 Visual Studio 2003/2005/2008 宏。

Copy + Paste from Blog entry for fidelity sake:为了保真,从博客条目中复制 + 粘贴:

  1. Open Macro Explorer打开宏资源管理器
  2. Create a New Macro创建新宏
  3. Name it OutlineRegions将其命名为OutlineRegions
  4. Click Edit macro and paste the following VB code:单击编辑宏并粘贴以下 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. 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.我使用 Ctrl+M+E。 I don't know why - I just entered it first time and use it now :)我不知道为什么 - 我第一次输入它并现在使用它:)

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

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

Thanks to 0A0D for a great answer.感谢0A0D提供了一个很好的答案。 I've had good luck with it.我很幸运。 Darin Dimitrov also makes a good argument about limiting the complexity of your JS files. Darin Dimitrov还就限制 JS 文件的复杂性提出了很好的论据。 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.关于#region 一般而言,这个SO 问题很好地涵盖了它。

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:此方法允许您在 //#region 关键字 ala C# 之后放置描述,并在代码中显示,如下所示:

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

This is now natively in VS2017:这现在在 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.我可以在 v15.7.3 中使用它。

For VS 2019, this should work without installing anything:对于 VS 2019,这应该可以在不安装任何东西的情况下工作:

在此处输入图片说明

    //#region MyRegion1

    foo() {

    }

    //#endregion

    //#region MyRegion2

    bar() {

    }

    //#endregion

For those who have come here for Visual Studio Code , the same syntax works对于那些来这里学习 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

When collapsed, it looks like below折叠后如下图

在此处输入图片说明

On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.在 VS 2012 和 VS 2015 上安装 WebEssentials 插件,您将能够这样做。

http://vswebessentials.com/features/javascript http://vswebessentials.com/features/javascript

For visual studio 2017.对于 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扩展名(JavaScript 区域) 作者:Mads Kristensen

It works like a charm in PhpStorm它在 PhpStorm 中就像一个魅力

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

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

我的地区

if you are using Resharper如果您使用的是Resharper

fallow the steps in this pic休耕这张照片中的步骤

在此处输入图片说明 then write this in template editor然后在模板编辑器中写这个

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

and name it #region as in this picture并将其命名为#region如这张图片所示在此处输入图片说明

hope this help you希望这对你有帮助

None of these answers did not work for me with visual studio 2017.这些答案都不适用于 Visual Studio 2017。

The best plugin for VS 2017: JavaScript Regions VS 2017 的最佳插件: JavaScript Regions

Example 1:示例 1:

在此处输入图片说明

Example 2:示例 2:

在此处输入图片说明

Tested and approved:测试和批准:

在此处输入图片说明

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标签:Node.js Nodejs Node js Javascript ES5 ECMAScript 注释折叠隐藏区域 Visual Studio 代码 vscode 2018 版本 1.2+ https://code.visualstudio.com/updates/v1_17#_folding-regions

Not only for VS but nearly for all editors.不仅适用于 VS,而且几乎适用于所有编辑器。

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

Warning: has disadvantages such as scope.警告:具有范围等缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM