UFO ET IT

Visual Studio 2015 JSX / ES2015 구문 강조

ufoet 2020. 11. 20. 17:25
반응형

Visual Studio 2015 JSX / ES2015 구문 강조


ES2015 코드를 사용하여 Visual Studio 2015 for JSX에서 적절한 구문 강조 표시를 얻으려면 어떻게해야합니까?

ES2015 코드

importexport키워드를 제거하면 정상적으로 작동합니다 .가져 오기 / 내보내기없이

방금 Visual Studio 2015 Enterprise Update 1로 업데이트했지만 여전히 동일합니다.


업데이트 (2017-02)

Node Tools for Visual Studio (NTVS)는 v1.2부터 Salsa 분석 엔진을 사용하고 있으며 NTVS를 사용하는 것이 JSX 지원에 대한 저항이 가장 적은 경로 일 가능성이 높습니다.

https://github.com/Microsoft/nodejstools

자세한 내용은이 답변을 읽고 찬성 투표하십시오 : https://stackoverflow.com/a/41996170/9324


원래 답변

동일한 문제가 발생하여 ReSharper를 사용하는 솔루션과 Visual Studio 외부 웹 도구를 수정하는 두 가지 솔루션을 찾았습니다.

해결책 1

ReSharper 10에서 :

  • 옵션 대화 상자 열기
  • 아래 코드 편집> 자바 스크립트> 검사는 선택 인 ECMAScript 6 에서 자바 스크립트 언어 수준 드롭 다운
  • .JS 파일에서 JSX 구문 사용 옵션도 선택되어 있는지 확인 하십시오 (JSX 구문 을 사용한다고 가정).
  • 또한 다음과 같이 Visual Studio에서 javascript 구문 오류를 비활성화해야합니다.
    • 이동 도구> 옵션> 텍스트 편집기> 자바 스크립트> 인텔리
    • 구문 오류 표시 상자를 선택 취소 하고 확인하십시오.
  • VS 솔루션 다시로드

솔루션을 다시로드 한 후 빨간 물결 모양이 사라졌습니다. 그러나 JSX에 대한 구문 강조는 작동하지 않습니다. render함수 에서 선언 한 요소의 시작 부분 에는 적절한 색상이 지정되어 있지 않지만 무시하기 쉽습니다.

또한 javascript 파일의 확장자 .js 여야 합니다. 당신이 그들에게주는 경우에 .jsx 확장을, 당신은 첫 번째 import 문에 빨간색 squigglies를 얻을 수 있습니다. 오류 메시지는입니다 JSX Parser: illegal import declaration. (아래의 솔루션 # 2를 사용하여 수정할 수 있습니다.)

업데이트 :이 해결 방법에 대한 @SntsDev 덕분에 .jsx 파일 이름 .js지정하지 않는 방법 이 있습니다 .

  • Visual Studio에서 옵션> 텍스트 편집기> 파일 확장명으로 이동합니다.
  • jsx를 추가 하고 Javascript 편집기에 할당하십시오.

해결 방법 2

Curiosity가 나아졌고 ReSharper가 아닌 솔루션이 있는지 여부를 알아보고 싶었습니다. Visual Studio는 로컬에서 실행되는 노드 서버 모듈을 사용하여 react-serverJSX를 즉시 구문 분석합니다. 이 모듈은 여기에서 찾을 수 있습니다.

C:\Program Files (x86)\Microsoft Visual Studio
14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\react-server

Visual Studio 2015 업데이트 3 업데이트 주석 / 업데이트에 대해 @TheQuickBrownFox 에게 감사드립니다 . 업데이트 3의 경우 react-server명령 의 위치 는 이제 다음 파일에 있습니다.

C:\Program Files (x86)\Microsoft Visual Studio 
14.0\Web\External\vs-task-server\react-commands.js

또한, 검사 server.js또는 react-commands.js상기 폴더 (들)로부터 파일을라는 함수가 transformJsxFromPosttransformJsx. 이 메서드에는 다음 줄이 포함 var transformed = reactTools.transformWithDetails(code, { elementMap: true });됩니다.. 이것은 ES6 구문 분석에 더 많은 옵션을 사용할 수 있는 react-tools모듈 ( https://www.npmjs.com/package/react-tools )에 대한 참조 입니다.

따라서:

  • 다음 줄을 바꿉니다.

    var transformed = reactTools.transformWithDetails(code, { elementMap: true });

  • 다음과 함께 :

    var transformed = reactTools.transformWithDetails(code, { elementMap: true, es6module: "--es6module", harmony: "--harmony" });

    들어오는 코드를 ES6로 처리하도록 지시 하는 --es6module--harmony플래그 가 추가 react-tools되었습니다.

  • 다음과 같이 Visual Studio에서 javascript 구문 오류를 비활성화합니다.

    • Visual Studio에서 도구> 옵션> 텍스트 편집기> JavaScript> IntelliSense로 이동합니다.
    • 구문 오류 표시 상자를 선택 취소 하고 확인
  • 중요 : Visual Studio를 다시 시작하십시오. 귀하의 .jsxES6 코드 파일은 더 이상 ES6 코드에 빨간색 구불 거리는 곡선이 없어야합니다.


메모:

  • server.js파일 에 대한 솔루션 2에 설명 된 변경 사항 이 비 ES6 코드에 영향을 미칠지 모르겠습니다 . 따라서 자신의 책임하에 구현하십시오.
  • 또한 Visual Studio에 대한 이후 업데이트로 변경 사항을 덮어 쓸 수 있습니다.
  • react-toolswithin react-server사용을 Babel CLI 로 대체하는 것이 멋지고 / 재미있을 것 입니다. 업데이트 : @NickDewitt 덕분에 그가이 일을 할 수 있었던 것 같습니다 : https://stackoverflow.com/a/36321109/9324

VS2015 업데이트 -3 및 NTVS 1.2가 설치된 경우 TypeScript 편집기를 파일 확장자 jsx 의 기본 편집기로 설정하기 만하면 저에게 트릭이 생겼 습니다.

1) 도구> 옵션> 텍스트 편집기> 파일 확장자를 엽니 다 .

2) Extension에 jsx입력하고 TypeScript Editor 를 Editor로 선택한 다음 Apply를 클릭합니다.

여기에 이미지 설명 입력


편집 : Visuals studio 15가 Visual Studio 2017로 이름이 변경되었습니다 : 여기에서 RC를 얻을 수 있습니다 : https://www.visualstudio.com/vs/visual-studio-2017-rc/

미래 솔루션 :

Visual Studio "15"Preview 2는 JSX와 React를 즉시 지원합니다. VS Code와 같은 동일한 (Salsa) Javascript 서비스 라이브러리를 활성화 할 수 있습니다.

릴리스 정보 : https://www.visualstudio.com/en-us/news/releasenotes/vs15/vs15-relnotes

살사 : https://github.com/Microsoft/TypeScript/wiki/Using-the-Salsa-Preview-in-Visual-Studio-15-Preview


솔루션 '3':

Thanks to the insights from Adam in his answer, I have got this working with babel and it's plugins/presets. It's worth reading his answer first if you are trying this.

You need nodeJs and npm installed before you go any further, and maybe back up any files before you modify them.

I am using react, es2015 plugins with stage1 presets here, but you can use whatever plugins you like

  1. Powershell to C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\react-server

  2. Install the following packages:

    npm install babel-core --save-dev
    npm install babel-preset-es2015 --save-dev
    npm install babel-preset-react --save-dev
    npm install babel-preset-stage-1 --save-dev
    
  3. Add the dependencies to server.js below childProcess

    var childProcess = require('child_process'); //already there
    var babel = require('babel-core');
    var es2015 = require('babel-preset-es2015');
    var react = require('babel-preset-react');
    var stage1 = require('babel-preset-stage-1');
    
  4. Replace the try{}catch{} section of the req.on('end' assignment in the transformJsxFromPost function:

    try {
    
        var transformed = 
            babel.transform(
                code, 
                {
                    sourceMaps: true, 
                    presets: [
                        es2015, 
                        react, 
                        stage1
                    ]
                }
            );
    
        result = { 
            elementMappings: []
        }
        //I found it least buggy when returning an empty list of elementMappings
        //but i will leave the code i was using to try and dupe it, or 
        //recreate the elementMappings from react-tools
        //
        // result = { 
            // elementMappings: [{
                // 'start': 1,
                // 'end': transformed.code.length,
                // 'generatedCode': transformed.code
            // }], 
            // map: transformed.map, 
            // code: transformed.code
        // }
    }
    catch (e) {
        //the error that react-tools was returning was slightly different, so
        //map the babel error back to the react-tools error that VS 2015 expects
         result = {
             column: e.loc.column,
             description: e.errorMessage,
             errorMessage: e.message + ".. :-(",
             index: e.pos,
             lineNumber: e.loc.line
         };
    }
    
  5. Restart visual studio, close and re-open any .jsx files and enjoy babel syntax highlighting :-)

Notes
Give the parser a chance to kick in after you start, visual studio will do the following when you load into a .jsx file the first time:

  1. Create a folder in %localappdata%\Temp\ with stderr.txt where you can find a log of any errors and stdout.txt which will tell you what {port} the server is running on and also logs other info.
  2. Start a nodeJs server, running on localhost:{port} which accepts JSX as a POST on /transformJsxFromPost and returns the line number and column number of the first error it encounters as a json object to visual studio

I had to turn off javascript intellisense for jsx files as Adam shows in solution 1 in his answer:

In Visual Studio, go to Tools > Options > Text Editor > JavaScript > IntelliSense, then uncheck the Show syntax errors box and OK out.

With javascript intellisense off, both react-server as packaged with vs and babel as i am replacing it here both only return the first error they encounter, so you shouldn't expect to see highlighting on all errors throughout your file, but they do show up as you type if you keep your code error free.

I guess now all is left to do is get the elementMappings over properly - solution 4 maybe? :-)


Whilst trying to research this I realised a simple way to work with jsx files in all versions of Visual Studio. It's not perfect but works for me.

Download the latest Visual Studio Code [ https://code.visualstudio.com/updates ] then right click a jsx file within whatever version of Visual Studio you have and select 'Open With...'. Select 'Add' and browse to your recently downloaded Visual Studio Code and make this your default.

Hope that helps people worrying about having to upgrade.


It is mentioned in the comments above by @TheQuickBrownFox, but hidden by default (needed to expand all to see it), so summarizing what I did to fix the issue in the latest Visual Studio 2015 Community Update 3:

에서 100 % 아담 웨버에 의해 해결 방법 1 : https://stackoverflow.com/a/34110461/1633913 (설정 자바 스크립트 언어 수준 에 ReSharper에서에 ECMAScript를 2016 , 체크 ... JSX를 사용 하지 않도록 설정 같은 창 +로 표시 구문 오류 에 VS JavaScript IntelliSense 옵션)

Adam Weber의 솔루션 2 : https://stackoverflow.com/a/34110461/1633913 , 약간 수정 됨; 교체해야하는 대상 파일 :

이: var transformed = reactTools.transformWithDetails(code, { elementMap: true });

이것으로 : var transformed = reactTools.transformWithDetails(code, { elementMap: true, es6module: "--es6module", harmony: "--harmony" });

실제로 여기에 있습니다. C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\vs-task-server\react-commands.js

VS를 다시 시작하면 완료됩니다.

참고 URL : https://stackoverflow.com/questions/34097915/visual-studio-2015-jsx-es2015-syntax-highlighting

반응형