IT

자바 스크립트에서 지역 / 코드 축소를 구현하는 방법

lottoking 2020. 7. 5. 07:46
반응형

자바 스크립트에서 지역 / 코드 축소를 구현하는 방법


Visual Studio에서 JavaScript에 대한 코드 축소 (일명 코드 축소) 영역을 어떻게 구현할 수 있습니까?

자바 스크립트에 수백 줄이있는 경우 vb / C #에서와 같이 영역으로 코드 접기를 사용하면 더 이해할 수 있습니다.

#region My Code

#endregion

블로그 항목은 여기 와이 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를 사용합니다. 왜 그런지 모르겠습니다-방금 처음 입력하여 지금 사용하십시오 :)

Microsoft는 이제이 기능을 제공 하는 VS 2010 의 확장 기능을 갖습니다 .

JScript 에디터 익스텐션


최신 버전의 Visual Studio를 사용하는 개발자에게 희소식

웹 요점은 이 기능을오고있다.

이것 좀 봐

여기에 이미지 설명을 입력하십시오

참고 : VS 2017의 경우 JavaScript 리전 사용 : https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions


간단합니다!

접고 싶은 부분을 표시하고

Ctrl + M + H

확장하려면 왼쪽에 '+'표시를 사용하십시오.


Visual Studio 2012를 사용하려는 사람들을 위해 Web Essentials 2012가 있습니다.

Visual Studio 2015를 사용하려는 사람들을 위해 Web Essentials 2015가 있습니다 .3

사용법은 @prasad와 정확히 같습니다.


논리 블록에 관계없이 코드 섹션을 표시하고 CTRL + M + H를 누르면 선택 영역이 축소 가능하고 확장 가능한 영역으로 정의됩니다.


JSEnhancements는 비주얼 스튜디오 주소이 잘 플러그인.


좋은 답변 주신 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

이것은 기본적으로 VS2017에 있습니다.

//#region fold this up

//#endregion

//와 # 사이의 공백은 중요하지 않습니다.

변경 로그에서 언급 할 수 없으므로 어떤 버전이 추가되었는지 알 수 없습니다. v15.7.3에서 사용할 수 있습니다.


VS 2012 및 VS 2015에서 WebEssentials 플러그인을 설치하면 그렇게 할 수 있습니다.

http://vswebessentials.com/features/javascript


Resharper를 사용하는 경우

이 사진의 단계를 포기

여기에 이미지 설명을 입력하십시오 그런 다음 템플릿 편집기에서 작성하십시오.

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

#region이 그림 과 같이 이름을여기에 이미지 설명을 입력하십시오

이것이 당신을 도울 수 있기를 바랍니다


이 답변 중 어느 것도 Visual Studio 2017에서 작동하지 않았습니다.

The best plugin for VS 2017: JavaScript Regions

Example 1:

여기에 이미지 설명을 입력하십시오

Example 2:

여기에 이미지 설명을 입력하십시오

Tested and approved:

여기에 이미지 설명을 입력하십시오


For visual studio 2017.

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

This was not working earlier so I downloaded extension from here


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


Not only for VS but nearly for all editors.

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

Warning: has disadvantages such as scope.

참고 URL : https://stackoverflow.com/questions/1921628/how-to-implement-regions-code-collapse-in-javascript

반응형

'IT' 카테고리의 다른 글

Gemfile을 찾을 수 없습니다  (0) 2020.07.05
matplotlib에서 컬러 바 범위 설정  (0) 2020.07.05
OS X의 LLVM 대 클랑  (0) 2020.07.05
양식 제출 jQuery에서 기본값 방지  (0) 2020.07.05
기본 디렉토리가 아닌 설치합니까?  (0) 2020.07.05