Pergunta

Como você pode implementar regiões, também conhecidas como colapso do código para JavaScript no Visual Studio?

Se houver centenas de linhas no JavaScript, será mais compreensível usando o dobro de código com regiões como no VB/C#.

#region My Code

#endregion
Foi útil?

Solução

A entrada do blog aqui explica isso e isto Pergunta do MSDN.

Você precisa usar macros do Visual Studio 2003/2005/2008.

Cópia + Colar da entrada do blog por causa da fidelidade:

  1. Open Macro Explorer
  2. Crie uma nova macro
  3. Diga OutlineRegions
  4. Clique em Editar macro e cole o seguinte código 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. Salve a macro e feche o editor
  2. Agora vamos atribuir atalho à macro. Vá para Ferramentas-> Opções-> Ambiente-> Teclado e pesquise sua macro em "Mostrar comandos contendo" TextBox
  3. Agora, na caixa de texto, nas "teclas de atalho da imprensa", você pode inserir o atalho desejado. Eu uso Ctrl+M+E. Não sei por que - acabei de entrar pela primeira vez e usá -lo agora :)

Outras dicas

A Microsoft agora tem uma extensão para Vs 2010 que fornece esta funcionalidade:

Extensões do editor do JScript

Boas notícias para desenvolvedores que estão trabalhando com a versão mais recente do Visual Studio

o Web Essentials estão vindo com esse recurso.

Veja isso

enter image description here

Nota: para uso vs 2017 Regiões JavaScript: https://marketplace.visualstudio.com/items?itemname=madskristensen.javascriptregions

Isso é fácil!

Marque a seção que você deseja entrar em colapso e,

Ctrl+M+H

E para expandir a marca de uso '+' à sua esquerda.

Para quem está prestes a usar o Visual Studio 2012, existe o Web Essentials 2012

Para quem está prestes a usar o Visual Studio 2015, existe o Web Essentials 2015.3

O uso é exatamente como @Prasad perguntou

Ao marcar uma seção de código (independentemente de qualquer bloco lógico) e atingir Ctrl + M + H, você definirá a seleção como uma região que é dobrável e expansível.

o Jsenhances O plug -in para o Visual Studio aborda isso bem.

Graças a 0A0D Para uma ótima resposta. Eu tive boa sorte com isso. Darin Dimitrov Também faz um bom argumento sobre a limitação da complexidade dos seus arquivos JS. Ainda assim, encontro ocasiões em que as funções em colapso para suas definições facilitam muito a navegação por um arquivo.

Em relação a #region em geral, este Então pergunta cobre muito bem.

Fiz algumas modificações na macro para suportar o colapso de código mais avançado. Este método permite que você coloque uma descrição após a //## Palavra -chave ALA C# e a mostre no código como mostrado:

Código de exemplo:

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

Macro atualizado:

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

Isso agora está nativamente no vs2017:

//#region fold this up

//#endregion

O espaço em branco entre o // e # não importa.

Não sei em que versão foi adicionada, pois não consigo encontrar nenhuma menção a ela nos Changelogs. Sou capaz de usá -lo em v15.7.3.

No vs 2012 e no vs 2015 Instale o plug -in do WebEssEnciais e você poderá fazê -lo.

http://vswebessentials.com/features/javascript

Se você está usando Resharper

pousou os degraus nesta foto

enter image description hereEm seguida, escreva isso no editor de modelos

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

e nomeie -o #region Como nesta fotoenter image description here

Espero que isso ajude você

Nenhuma dessas respostas não funcionou para mim com o Visual Studio 2017.

O melhor plugin para o VS 2017: Regiões JavaScript

Exemplo 1:

enter image description here

Exemplo 2:

enter image description here

Testado e aprovado:

enter image description here

Para o Visual Studio 2017.

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

Isso não estava funcionando mais cedo, então eu baixei a extensão de aqui

A região deve funcionar sem alterar as configurações

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

Para ativar a área de comentários em colapso /** /

/* Collapse this

*/

Configurações -> Pesquise "dobrando" -> Editor: Estratégia de dobragem -> De "Auto" para "Indentação".

Tags: node.js nodejs node js javascript es5 Ecmascript comentário dobrável esconderhttps://code.visualstudio.com/updates/v1_17#_folding-regions

Não apenas para VS, mas quase para todos os editores.

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

Aviso: tem desvantagens como o escopo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top