cómo implementar regiones/contraer código en javascript
-
20-09-2019 - |
Pregunta
¿Cómo se puede implementar una de las regiones.k.una.código colapso de JavaScript en Visual Studio?
Si hay cientos de líneas de javascript, que va a ser más comprensible el uso de plegado de código con regiones como en vb/C#.
#region My Code
#endregion
Solución
entrada de blog aquí lo explica y este pregunta MSDN .
Hay que utilizar Visual Studio 2003/2005/2008 macros.
Copiar + Pegar en la entrada del blog por causa fidelidad:
- Abra el Explorador de macros
- Crear una nueva macro
- Nombre que
OutlineRegions
- Haga clic en Editar macro y pegar el siguiente 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
- Guardar la macro y cierre el editor
- Ahora vamos a asignar acceso directo a la macro. Ir a Herramientas-> Opciones-> Medio Ambiente-> Teclado y la búsqueda de la macro en "comandos show que contienen" cuadro de texto
- Ahora en el cuadro de texto debajo de las teclas de acceso directo "Press" puede introducir el acceso directo deseado. Yo uso Ctrl + M + E. No sé por qué - me acaba de entrar por primera vez y cómo utilizar ahora:)
Otros consejos
Microsoft ahora tiene una extensión de VS 2010 que proporciona esta funcionalidad:
Buena noticia para los desarrolladores que está trabajando con la última versión de Visual Studio
Los Fundamentos Web vienen con esta característica.
Nota: Para VS 2017 uso JavaScript Regiones: https: //marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions
Eso es fácil!
Marcar la sección que desea al colapso y,
Ctrl + M + H
Y para ampliar el uso de la marca '+' a su izquierda.
Para los que van a utilizar el Visual Studio 2012, existe en el web Essentials 2012
Para los que van a utilizar el Visual Studio 2015, existe el Web Essentials 2015.3
El uso es exactamente igual @prasad preguntó
Al marcar una sección de código (independientemente de cualquier bloques lógicos) y golpear CTRL + M + H que definiremos la selección como una región que es plegable y expansible.
href="http://visualstudiogallery.msdn.microsoft.com/0696ad60-1c68-4b2a-9646-4b5f4f8f2e06" plug-in para Visual Studio direcciones esta muy bien.
Gracias a 0A0D para una gran respuesta.He tenido buena suerte con él. Darin Dimitrov también hace un buen argumento acerca de la limitación de la complejidad de la JS.Aún así, creo que en ocasiones el colapso de las funciones de estas definiciones hace que la navegación a través de un archivo mucho más fácil.
Respecto a la #región en general, este ASÍ, Pregunta cubre bastante bien.
He hecho un par de modificaciones a la Macro para apoyar más avanzados código de colapso.Este método permite que usted ponga una descripción después de los //#región palabra clave ala C# y lo muestra en el código como se muestra:
Ejemplo de código:
//#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
Actualizado 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
Esto es ahora de forma nativa en VS2017:
//#region fold this up
//#endregion
El espacio en blanco entre la // y # no importa.
No sé qué versión esto se añadió en el, ya que no puedo encontrar ninguna mención de la misma en los registros de cambios. Soy capaz de utilizarlo en v15.7.3.
En VS 2012 y VS 2015 WebEssentials instalar plugin y usted será capaz de hacerlo.
si está utilizando ReSharper
barbecho los pasos en esta foto
a continuación, escribir esto en editor de plantillas
//#region $name$
$END$$SELECTION$
//#endregion $name$
y el nombre de #region
como en esta foto
esperanza que esto ayudará a
Ninguna de estas respuestas no funcionaba para mí con Visual Studio 2017.
El mejor complemento para VS 2017: de JavaScript Regiones
Ejemplo 1:
Ejemplo 2:
Probado y aprobado:
Para Visual Studio 2017.
//#region Get Deactivation JS
.
.
//#endregion Get Deactivation JS
Esto no estaba funcionando anteriormente lo que he descargado la extensión del aquí
Región debe trabajar sin cambiar la configuración
//#region Optional Naming
var x = 5 -0; // Code runs inside #REGION
/* Unnecessary code must be commented out */
//#endregion
Para habilitar el colapso área de comentarios / ** /
/* Collapse this
*/
Configuración -> Buscar "plegable" -> Editor: plegable Estrategia -> A partir de "auto" a "sangría"
.TAGS: Node.js nodejs Nodo js Javascript ES5 ECMAScript región escondite comentario plegamiento código de Visual Studio 2018 vscode versión 1.2+ https://code.visualstudio.com/updates/v1_17#_folding-regions
No sólo para VS pero casi en todos los editores.
(function /* RegionName */ () { ... })();
Advertencia:. tiene desventajas tales como el alcance