반응형

Vue.js의 라이프 사이클은 크게 Creation, Mounting, Updating, Destruction 으로 나눌 수 있다.

1. Creation : 컴포넌트 초기화 단계

Creation 단계에서 실행되는 훅(hook)들이 라이프사이클 중에서 가장 처음 실행된다. 이 단계는 컴포넌트가 돔에 추가되기 전이다. 서버 렌더링에서도 지원되는 훅이다.

따라서 클라이언트 단과 서버단 렌더링 모두에서 처리해야할일이 있다면 이단계에서 하면된다. 아직 컴포넌트가 돔에 추가되기 전이기 때문에 돔에 접근하거나 this.$el를 사용할 수 없다.

이 단계에서는 beforeCreate 훅과 Created 훅이 있다.

beforeCreate

모든 훅 중에 가장 먼저 실행되는 훅이다. 아직 data와 events(vm.$on, vm.$once, vm.$off, vm.$emit)가 세팅되지 않은 시점이므로 접근하려고 하면 에러를 뿜어낼 것이다.

<script>
  export default {
    data () {
      return {
        title: ''
      }
    },

    beforeCreate () {
      //can't use Data(this.title ...), events(vm.$on, vm.$once, vm.$off, vm.$emit)
    }
  }
</script>

 

created

created 훅에서는 이제 data와 events가 활성화되어 접근할 수 있다. 여전히 템플릿과 가상돔은 마운트 및 렌더링되지 않은 상태이다.

<script>
  export default {
    data () {
      return {
        title: ''
      }
    },
    computed: {
      titleComputed() {
        console.log('I change when this.property changes.')
        return this.property
      }
    },
    created () {
      //can use Data(this.title, this.titleComputed ...), events(vm.$on, vm.$once, vm.$off, vm.$emit)
      //don't use $el
    }
  }
</script>

2. Mounting : 돔(DOM) 삽입 단계

Mounting 단계는 초기 렌더링 직전에 컴포넌트에 직접 접근할 수 있다. 서버렌더링에서는 지원하지 않는다.

초기 랜더링 직전에 돔을 변경하고자 한다면 이 단계를 활용할 수 있다. 그러나 컴포넌트 초기에 세팅되어야할 데이터 페치는 created 단계를 사용하는것이 낫다.

beforeMount

beforeMount 훅은 템플릿과 렌더 함수들이 컴파일된 후에 첫 렌더링이 일어나기 직전에 실행된다. 대부분의 경우에 사용하지 않는 것이 좋다. 그리고 서버사이드 렌더링시에는 호출되지 않는다.

<script>
export default {
  beforeMount() {
    console.log(`this.$el doesn't exist yet, but it will soon!`)
  }
}
</script>

mounted

mounted 훅에서는 컴포넌트, 템플릿, 렌더링된 돔에 접근할 수 있다. 모든 하위 컴포넌트가 마운트된 상태를 보장하지는 않는다. 서버렌더링에서는 호출되지 않는다.

<script>
export default {
  mounted() {
    console.log(this.$el.textContent) // can use $el
    this.$nextTick(function () {
      // 모든 화면이 렌더링된 후 실행합니다.
    })
  }
}
</script>

mounted 훅에서 유의할 점은, 부모와 자식 관계의 컴포넌트에서 우리가 생각한 순서로 mounted가 발생하지 않는다는 점이다. 즉 부모의 mounted훅이 자식의 mounted훅보다 먼저 실행되지 않는다. 오히려 그 반대이다.

Parent/child initialisation workflow

위 그림처럼 Created훅은 부모->자식의 순서로 실행되지만 mounted는 그렇지 않다는 것을 알 수 있다. 다른 식으로 말하면 부모는 mounted훅을 실행하기 전에 자식의 mounted훅이 끝나기를 기다린다. (참고 Vue Parent and Child lifecycle hooks)

3. Updating : Diff 및 재 렌더링 단계

컴포넌트에서 사용되는 반응형 속성들이 변경되거나 어떤 이유로 재 렌더링이 발생되면 실행된다. 디버깅이나 프로파일링 등을 위해 컴포넌트 재 렌더링 시점을 알고 싶을때 사용하면 된다. 조심스럽지만, 꽤 유용하게 활용될 수 있는 단계이다. 서버렌더링에서는 호출되지 않는다.

beforeUpdate

이 훅은 컴포넌트의 데이터가 변하여 업데이트 사이클이 시작될때 실행된다. 정확히는 돔이 재 렌더링되고 패치되기 직전에 실행된다. 재 렌더링 전의 새 상태의 데이터를 얻을 수 있고 더 많은 변경이 가능하다. 이 변경으로 이한 재 렌더링은 트리거되지 않는다.

updated

이 훅은 컴포넌트의 데이터가 변하여 재 렌더링이 일어나 후에 실행된다. 돔이 업데이트 완료된 상태이므로 돔 종속적인 연산을 할 수 있다. 그러나 여기서 상태를 변경하면 무한루프에 빠질 수 있다. 모든 자식 컴포넌트의 재 렌더링 상태를 보장하지는 않는다.

<script>
export default {
  updated() {
    this.$nextTick(function () {
      // 모든 화면이 렌더링된 후 실행합니다.
    })
  }
}
</script>

4. Destruction : 해체 단계

beforeDestroy

이 훅은 해체(뷰 인스턴스 제거)되기 직전에 호출된다. 컴포넌트는 원래 모습과 모든 기능들을 그대로 가지고 있다. 이벤트 리스너를 제거하거나 reactive subscription을 제거하고자 한다면 이 훅이 제격이다. 서버 렌더링시 호출되지 않는다.

destroyed

이 훅은 해체(뷰 인스턴스 제거)된 후에 호출된다. Vue 인스턴스의 모든 디렉티브가 바인딩 해제 되고 모든 이벤트 리스너가 제거되며 모든 하위 Vue 인스턴스도 삭제된다. 서버 렌더링시 호출되지 않는다.

그 밖에

activated와 deactivated가 있다. 각각 keep-alive 컴포넌트가 활성화 될 때와 비활성화 될 때 호출된다.

 

출처: https://medium.com/witinweb/vue-js-%EB%9D%BC%EC%9D%B4%ED%94%84%EC%82%AC%EC%9D%B4%ED%81%B4-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-7780cdd97dd4

반응형
반응형

https://www.youtube.com/watch?v=vqwe1H1cYrY

이 유튜브가 여러곳중에 제일 친절하고 이해하기 쉬웠다.

반응형
반응형

JavaScript가 될 언어의 첫 번째 데모는 거의 정확히 25 년 전에 진행되었습니다 .

이 언어는 1995 년 가을 Netscape Navigator 베타에서 LiveScirpt로 출시되었으며 그해 말에 JavaScript로 이름이 변경되었습니다. 그해 말에 저는 JavaScript : The Definitive Guide 의 첫 번째 판 (O'Reilly에서이를 "베타 판" 으로 출판)을 시작했으며 1996 년 8 월에 출판되었습니다. .

 일곱 번째 에디션이 몇 주에 나오고, 나는 자바 스크립트의 우리가 지금, 자비, 잊을 수있는 초기 웹 플랫폼의 오래된 이상한 기능에 대한 기억을 더듬어 및 블로그 다운 여행을하고 싶다. 새 7 번째 에디션이 6 번째 에디션보다 얇은 이유 중 하나는 참조 섹션을 제거 했기 때문 입니다. 그러나 2020 년에는 더 이상 웹 개발자와 관련이없는 것들이 많았습니다. 웹 호환성은 영원히 (또는 25 년 이상) 지속되므로 브라우저 공급 업체는 오래되고 모호한 지원을 계속해야 할 수 있습니다 언어 및 플랫폼 기능이 오랫동안 사용되었습니다. 그러나 우리 나머지는 더 이상 우리의 마음을 어지럽 힐 필요가 없습니다.

여기에 더 이상 JavaScript : Definitive Guide 의 페이지 수를 늘리지 않는 JavaScript 및 웹 플랫폼 기능이 있습니다. 그들에게 작별 인사를하게되어 기쁩니다. (나는 여기에 약간의 맹렬한 소리가 나고 있다고 느낀다. 따라서 이것이 신중하게 연구되지는 않았고, 나쁜 옛날 시절의 일에 대한 내 기억 만 경고된다.)

  • arguments개체가 완전히의 도입에 의해 없어진다 된 ...argsES6있다. 명명 된 인수와 상호 작용하는 이상한 방식을 설명하고 성능 관련 사항에 대해 항상주의를 기울이는 것은 항상 어려운 일이었습니다. 레거시 코드에서 여전히 볼 수 있으며 arguments엄격 모드에서 로컬 변수 또는 함수 매개 변수의 이름을 지정하려고하면 존재 여부를 상기시킬 수 있지만 이제 나머지 인수가 있으므로 망각에 빠질 수 있어야합니다.

  • 우리는 반복 된 문자열 연결의 성능에 대해 걱정해야했습니다. 우리 모두는 문자열을 배열로 푸시 join()하고 마지막에 모든 것을 연결 하는  사용하는 기간이있었습니다 . 그런 다음 JavaScript가 빨라지고 우리는 모두“실제로”그 패턴을 배우지 못했습니다. 그리고 이제 더 이상 문자열 연결을 사용하는 템플릿 리터럴이 있습니다!

  • document.write()DOM 이전에 JavaScript의 주요 기능이었습니다. (20 세기에 JavaScript를 사용하지 않았다면 DOM 이전에 시간이 있었음을 알 수는 있지만 사실입니다. 웹 페이지의 배경색을 변경하도록 설정할 수있는 속성이 있었지만 그 방법은 없습니다 IIRC를 사용하여을 사용하여 문서에 스크립트를 삽입 할 수도 document.write()있지만 </script>HTML 파서가이를 해석하지 않도록 닫는 태그를 두 개의 문자열로 분리해야합니다. 현재 실행중인 스크립트의 끝

  • HTML은하지 않았다 <iframe>초기에,하지만 거기 <frameset>와 <frame>.  window.frames속성은 문서의 프레임을 나타내는 중첩 창 객체의 배열이었습니다. 실제로 open()프레임에서 문서  메서드를 호출 한 다음 document.write()해당 프레임 내에서 전체 문서를 동적으로 생성하는 데 사용할 수있었습니다. 실제로는 시원했습니다. 프레임은 다른 프레임 안에 중첩 될 수 있으므로 모든 Window 객체에는 frames자식 프레임을 포함 하는 배열과 parent포함 창 top을 참조 하는 속성  최상위 창을 참조 하는 속성이 있습니다. 필자의 저서 초판은 긴 부분과이 모든 것을 설명하는 복잡한 그림을 다뤘습니다.

  • 문서 내의 특정 요소를 참조하기위한 모든 종류의 사용되지 않는 기술이 있습니다. frames배열이 또한 있었다, IIRC 일 이었지만, links그리고 images말 그대로 문서에있는 모든 링크와 이미지의 단지 목록이었다 아니라 배열. IE (버전 4, 나는 생각한다)는 document.all문서에 모든 요소의 배열을 올인 하고 소개했다 . (이것은 DOM과 "DHTML"의 시작이었습니다. 마른 땅으로 기어가는 최초의 물고기와 같은 종류였습니다.) document.all온갖 이상한 기능이있었습니다. 이름이나 다른 요소로 요소를 찾는 방법도있는 배열이었습니다. 그렇게 document.all표준화 없지만, 심지어 표준 방법 좋아 않았다 document.getElementById(), document.getElementsByName(), document.getElementsByTagName()와 document.getElementsByClassName()jQuery의에 의해 부적절로 분쇄되지 않는 오늘을 보인다$()기능과 그것이 영감을 얻은 표준 document.querySelector()및 document.querySelectorAll()방법. CSS 선택기의 강력한 기능을 통해이 두 기능은 이전의 모든 기능을 폐기합니다.

  • Internet Explorer에서 가장 싫어했던 것은 attachEvent()이벤트 핸들러 등록 방법을 사용했다는 것 입니다. 내 기억에, 그들은 표준이지만이 작업을 수행addEventListener()이미 정의되었고, 정말 저를 괴롭 혔습니다. 이벤트와 이벤트 처리는 웹에서 가장 큰 비 호환성 소스 중 하나였으며, 수 년 동안 JavaScript 프로그래머 (및 JavaScript 서적 저자)는 IE 이벤트 모델과 표준 이벤트 모델 간의 긴 차이 목록을 처리해야했습니다. 이벤트 처리 코드는 IE와 Firefox에 대해 두 번 작성해야했습니다. 사건에 관한 서적 장은 사건을 다루는 두 가지 유사하지만 완전히 양립 할 수없는 방법이 있었기 때문에 필요한 것보다 두 배나 길었습니다. jQuery의 주요 기능 중 하나는 자체 이벤트 호환성 계층을 구현하여 jQuery 이벤트에 대해서만 알아야한다는 것이 었습니다. 이것이 인기의 중요한 이유라고 생각합니다.

  • 원래 DOM API는 XML에 대한 마 법적 사고 시대에 정의되었습니다. (사람들은 XML이 모든 데이터 문제를 해결할 것이라고 몇 년 동안 믿었던 것 같았습니다. 이상한 시간이었습니다.) 어떻게 든 W3C는 DOM API를 정의했다고 Java 사람들이 침투했다고 약속했습니다. HTML 문서로 작업하는 JavaScript 프로그래머 및 XML 데이터로 작업하는 Java 프로그래머가 사용하는 단일 API. 그렇기 때문에 Attr 노드와 같은 이상한 것들이 가장 좋은 이유입니다. DOM Level 3 API에 대해 항상 나를 괴롭혔던 것 중 하나는 e문서에서 요소를 제거하면 e.remove()오늘날처럼 쓸 수 없다는 것입니다. 당신은 실제로 썼다 e.parentNode.removeChild(e).

 

원문 : https://davidflanagan.com/2020/05/12/javascript-to-forget.html

반응형
반응형

동적 언어는 유용한 도구이다. 스크립팅을 통해 사용자는 메모리 관리나 빌드 시스템과 같은 세부 정보에 대해 걱정하지 않고 복잡한 시스템을 빠르고 간결하게 연결하고 아이디어를 표현할 수 있습니다. 최근 몇년간 러스트 앤 고와 같은 프로그래밍 언어들은 정교한 네이티브 머신 코드를 제작하는 것을 훨씬 쉽게 만들었다. 이러한 프로젝트들은 컴퓨터 인프라에서 믿을 수 없을 만큼 중요한 발전이다. 그러나 광범위한 문제 도메인을 해결할 수 있는 강력한 스크립팅 환경을 구축하는 것이 여전히 중요하다고 주장합니다.

JavaScript는 웹 브라우저가 있는 모든 장치에서 작동하는 가장 널리 사용되는 동적 언어입니다. 많은 수의 프로그래머들이 자바 스크립트에 능숙하고 그것의 실행을 최적화하는데 많은 노력을 기울여 왔다. ECMAInternational과 같은 표준 기관을 통해 언어는 신중하고 지속적으로 개선되어 왔습니다. 당사는 브라우저 환경이든 독립형 프로세스이든 동적 언어 도구 사용을 위한 자연스러운 선택은 JavaScript라고 생각합니다.

이 분야에서 우리가 처음 맡은 Node.js는 매우 성공적인 소프트웨어 플랫폼임이 입증되었다. 사람들은 웹 개발 도구를 구축하고, 독립 실행형 웹 서버를 구축하고, 수많은 다른 사용 사례에 유용하다는 것을 알게 되었습니다. 그러나 노드는 2009년 자바 스크립트가 언어가 많이 달랐던 시기에 설계되었다. 노드는 필연적으로 나중에 표준 조직에 의해 채택되고 언어에 다르게 추가된 개념을 개발해야 했습니다. 노드의 설계 실수 프레젠테이션에서 이에 대해 자세히 설명합니다. 노드에 있는 사용자 수가 많기 때문에 시스템 개발이 어렵고 느립니다.

JavaScript언어가 변경되고 TypeScript와 같은 새로운 추가 사항으로 인해, 빌딩 노드 프로젝트는 빌드 시스템과 동적 언어 스크립팅의 재미를 없애는 다른 무거운 도구를 관리하는 것을 포함하여 힘든 노력이 될 수 있습니다. 또한 외부 라이브러리에 연결하기 위한 메커니즘은 웹의 이상에 대해 인라인 상태가 아닌 NPM저장소를 통해 기본적으로 중앙 집중화됩니다.

우리는 자바 스크립트의 환경과 주변 소프트웨어 인프라가 단순화할 가치가 있을 정도로 충분히 변화했다고 생각한다. 우리는 다양한 작업에 사용할 수 있는 즐겁고 생산적인 스크립팅 환경을 찾고 있습니다.

명령줄 스크립트를 위한 웹 브라우저

Deno는 웹 브라우저 외부에서 JavaScript및 TypeScript를 실행하기 위한 새로운 런타임입니다.

Deno는 복잡한 기능의 신속한 스크립팅을 위한 독립 실행형 도구를 제공하려고 하지 않습니다. Deno는 단일 실행 파일이며 항상 실행 가능합니다. 웹 브라우저처럼 외부 코드를 가져오는 방법을 알고 있습니다. Deno에서는 다른 도구 없이도 임의로 복잡한 동작을 정의할 수 있습니다.

import { serve } from "https://deno.land/std@0.50.0/http/server.ts";

for await (const req of serve({ port: 8000 })) {
  req.respond({ body: "Hello World\n" });
}

 

여기에 완전한 HTTP서버 모듈이 한줄에 종속성으로 추가됩니다. 추가 구성 파일이 없으며 미리 설치할 필요가 없습니다. 단지 denorunexample.js입니다.

브라우저와 마찬가지로, 코드는 기본적으로 보안 샌드 박스에서 실행됩니다. 스크립트는 사용 권한 없이 하드 드라이브에 액세스 하거나, 네트워크 연결을 열거나, 다른 잠재적으로 악의적인 작업을 수행할 수 없습니다. 브라우저는 카메라와 마이크에 액세스 할 수 있는 API를 제공하지만 사용자는 먼저 권한을 부여해야 합니다. Deno는 터미널에서 유사한 동작을 제공합니다. 위의 예는 다음과 같지 않으면 실패합니다.--allow-net명령줄 플래그가 제공됩니다.

Deno는 표준화된 브라우저 JavaScriptAPI에서 벗어나지 않도록 주의합니다. 물론 모든 브라우저 API가 Deno와 관련이 있는 것은 아니지만, Deno는 표준에서 벗어나지 않는다.

첫번째 클래스 유형 스크립트 지원

우리는 Deno가 작은 한줄 스크립트에서부터 복잡한 서버 측 비즈니스 로직에 이르기까지 광범위한 문제 도메인에 적용되기를 원합니다. 프로그램이 점점 더 복잡해짐에 따라 특정 형식의 유형 확인이 점점 더 중요해 지고 있습니다. TypeScript는 사용자가 선택적으로 유형 정보를 제공할 수 있도록 해 주는 JavaScript언어의 확장자입니다.

Deno는 추가 공구 없이 TypeScript를 지원합니다. 런타임은 TypeScript를 염두에 두고 설계되었습니다. 그deno types명령어는 Deno가 제공하는 모든 항목에 대해 유형 선언을 제공합니다. Deno의 표준 모듈은 모두 TypeScript로 작성되어 있습니다.

끝까지 약속하다

노드는 JavaScript에 Promises또는 async/Idawait개념이 적용되기 전에 설계되었습니다. 노드의 약속 상대는 EventEmitter로, 중요한 API가 소켓과 HTTP를 기반으로 한다. Async/Obawait의 인체 공학적 이점은 차치하고 EventEmitter패턴은 역압에 문제가 있다. TCP소켓을 예로 들어 보겠습니다. 소켓은 들어오는 패킷을 수신할 때"데이터"이벤트를 방출합니다. 이러한 "데이터"콜백은 제약 없이 방출되어 프로세스에 이벤트가 가득 차게 됩니다. 노드가 계속해서 새 데이터 이벤트를 수신하기 때문에 기본 TCP소켓에 적절한 백업 압력이 없으며 원격 보낸 사람은 서버가 오버 로드되어 데이터를 계속 보내는지 모릅니다. 이 문제를 완화하기 위해 apause()방법이 추가되었습니다. 이렇게 하면 문제를 해결할 수 있지만 추가 코드가 필요했습니다. 그리고 홍수 문제는 프로세스가 매우 바쁠 때만 나타나므로 많은 노드 프로그램에 데이터가 쇄도할 수 있습니다. 그 결과 꼬리 대기 시간이 나쁜 시스템이 되었다.

Deno에서 소켓은 여전히 비동기적이지만 새 데이터를 수신하려면 사용자가 명시적으로 해야 합니다.read()수신 소켓을 적절하게 구성하기 위해 추가적인 휴지가 필요하지 않다. 이것은 TCP소켓에만 고유한 것이 아닙니다. 시스템에 대한 가장 낮은 수준의 바인딩 계층은 기본적으로 약속과 연관되어 있습니다. 우리는 이러한 바인딩을 "운영"이라고 부릅니다. 어떤 형태로든 데노에서 모든 콜백은 약속에서 발생한다.

녹은 퓨처스라고 불리는 그 자체의 약속 같은 추상화를 가지고 있다. "Op"추상화를 통해 Deno는 Lust미래 기반 API를 JavaScript약속에 쉽게 묶을 수 있습니다.

녹 API

제공되는 기본 구성 요소는 Deno명령줄 인터페이스(CLI)입니다. CLI는 오늘날 버전 1.0입니다. 하지만 Deno는 획일적인 프로그램이 아니라 다양한 층에서 통합할 수 있도록 RusticCress의 모음으로 설계되었습니다.

deno_core상자는 Deno의 매우 노출된 bone버전입니다. TypeScript또는 Tokio에 종속성이 없습니다. 운영 및 리소스 인프라만 제공합니다. 즉, 그것은 자바 스크립트 약속에 녹 선물을 결합하는 체계적인 방법을 제공한다. CLI는 물론 deno_core위에 구축되어 있습니다.

rusty_v8box는 V8의 C++API에 고품질의 녹 바인딩을 제공합니다. API는 가능한 한 원본 C++API와 일치하도록 시도합니다. 비용이 전혀 들지 않는 결합입니다. 녹에 노출된 물체는 정확히 C++로 조작한 물체입니다.(예를 들어, 녹 V8바인딩에 대한 이전의 시도로 영구 핸들을 사용할 수밖에 없었습니다.) 이 상자는 GithubActionsCI에 구축된 이진 파일을 제공하지만 V8을 처음부터 컴파일하여 여러 빌드 구성을 조정할 수도 있습니다. V8소스 코드는 모두 상자 자체에 분산되어 있습니다. 마지막으로 run_y는 안전한 인터페이스가 되려고 시도합니다. 아직 100%안전하진 않지만 거의 다 왔어요 V8처럼 복잡한 VM과 안전한 방식으로 상호 작용할 수 있다는 것은 매우 놀라운 일이며 Deno자체에서 많은 어려운 버그를 발견할 수 있게 해 주었습니다.

안정성

Deno에서 안정적인 API를 유지할 것을 약속합니다. Deno는 많은 인터페이스와 구성 요소를 가지고 있습니다. 따라서"안정적"이라는 것이 무엇을 의미하는지에 대해 투명하게 이해하는 것이 중요합니다. 운영 체제와 상호 작용하기 위해 개발한 JavaScriptAPI는 모두"Deno"네임 스페이스(예:Deno.open()() 이러한 변경 사항은 주의 깊게 검토되었으며, 역 호환되지 않는 변경 사항은 적용되지 않습니다.

안정화를 위해 아직 준비되지 않은 모든 기능이 뒤에 숨겨져 있습니다.--unstable명령줄 플래그. 불안정한 인터페이스에 대한 설명서를 보려면 여기를 참조하십시오. 이후 릴리즈에서는 이러한 API의 일부도 안정화될 예정입니다.

글로벌 네임 스페이스에는 다른 모든 종류의 객체가 있음)를 찾을 수 있습니다.setTimeout()그리고fetch()). 이러한 인터페이스를 브라우저의 인터페이스와 동일하게 유지하기 위해 매우 노력했지만, 의도하지 않은 비호 환성이 발견되면 수정 사항을 발표할 것입니다. 브라우저 표준은 이러한 인터페이스를 정의합니다. 우리가 아닙니다. 우리에 의해 발행된 수정은 인터페이스 변경이 아니라 버그 수정이다. 브라우저 표준 API와 호환되지 않는 경우 주요 릴리스 전에 비호 환성이 해결될 수 있습니다.

Deno또한 많은 녹 API, 즉 deno_core와 rusty_v8crash를 가지고 있습니다. 이러한 API중 아직 1.0이 아닙니다. 우리는 그것들을 계속 반복할 것이다.

제한 사항

Deno는 노드의 포크가 아니라 완전히 새로운 구현이라는 점을 이해하는 것이 중요합니다. Deno는 개발된 지 2년밖에 되지 않았고, Node는 10년 이상 개발되어 왔다. Deno에 대한 관심의 양을 고려할 때, 우리는 Deno가 계속 진화하고 성숙할 것으로 기대한다.

일부 애플리케이션의 경우 Deno가 오늘날 적합한 선택이 될 수 있으며, 아직 선택되지 않은 애플리케이션의 경우도 있습니다. 그것은 요구 사항에 따라 달라질 것이다. 우리는 사람들이 Deno사용을 고려할 때 정보에 입각한 결정을 내리는 데 도움이 되도록 이러한 제한에 대해 투명하게 밝히고 싶습니다.

호환성.

안타깝게도, 많은 사용자들은 기존 자바 스크립트 툴과의 호환성이 부족하다는 것을 알게 될 것이다. Deno는 일반적으로 노드(NPM)패키지와 호환되지 않습니다. ht에서 초기 호환성 계층이 구축되고 있지만 완전하지는 않습니다.

Deno는 모듈 시스템을 단순화하기 위해 강경한 접근 방식을 취했지만, 궁극적으로 Deno와 Node는 유사한 목표를 가진 매우 유사한 시스템입니다. 시간이 지남에 따라 Deno는 기본 제공되는 노드 프로그램을 점점 더 많이 실행할 수 있을 것으로 예상합니다.

HTTP서버 성능

우리는 Deno의 HTTP서버의 성능을 지속적으로 추적합니다. hello-worldDenoHTTP서버는 초당 약 25k요청을 수행하며 최대 대기 시간은 1.3밀리 초입니다. 비교 가능한 노드 프로그램은 초당 34k 요청을 수행하고 다소 불규칙한 최대 지연 시간은 2~300밀리 초입니다.

Deno의 HTTP서버는 기본 TCP소켓 위에 있는 TypeScript에서 구현됩니다. 노드의 HTTP서버는 C로 작성되고 JavaScript에 대한 상위 수준 바인딩으로 노출됩니다. TCP소켓 레이어를 최적화하고 보다 일반적으로 op인터페이스를 원하기 때문에 Deno에 네이티브 HTTP서버 바인딩을 추가하려는 요구를 거부해 왔습니다.

Deno는 적절한 비동기 서버이며 대부분의 경우 초당 25k요청만으로도 충분합니다. ( 그렇지 않다면, JavaScript가 최선의 선택이 아닐 수도 있습니다.) 또한, 우리는 Deno가 일반적으로 널리 사용되는 약속(위에서 논의한)으로 인해 더 나은 꼬리 지연 시간을 보일 것으로 예상합니다. 그렇기는 하지만, 우리는 이 시스템에서 더 많은 성과를 거둘 수 있을 것으로 믿고 있으며, 앞으로 출시될 제품에서 이를 달성하기를 희망합니다.

TSC병목

내부적으로 Deno는 Microsoft의 TypeScript컴파일러를 사용하여 유형을 확인하고 JavaScript를 생성합니다. V8로 자바 스크립트를 분석하는 데 걸리는 시간에 비하면 매우 느리다. 프로젝트 초기에는 "V8스냅 샷"이 상당한 개선 효과를 제공할 것으로 기대했었습니다. 스냅 샷은 확실히 도움이 되었지만 여전히 만족스럽지 못할 정도로 느립니다. 우리는 기존의 TypeScript컴파일러 외에도 여기서 개선할 수 있는 사항이 있다고 생각하지만, 궁극적으로 녹(rust)에 형식 검사를 구현해야 한다는 것은 분명합니다. 이는 엄청난 작업이 될 것이며 가까운 시일 내에 이루어지지는 않을 것입니다. 그러나 개발자들이 경험하는 중요한 경로에서 엄청난 성능 향상을 제공할 것입니다. TSC에 녹이 슬었는지 확인해야 합니다. 이 문제에 대해 협력할 의향이 있으시면 연락 주십시오.

플러그 인/확장

사용자 지정 작업을 통해 Deno런타임을 확장하기 위한 초기 플러그 인 시스템이 있습니다. 그러나 이 인터페이스는 여전히 개발 중이며 불안정한 것으로 표시되었습니다. 따라서 Deno가 제공하는 것 이외의 기본 시스템에 액세스 하기란 어렵습니다.

감사의 말

많은 분들이 이 발표를 가능하게 해 주신 많은 기부자들에게 감사 드립니다. 특히, TypeScript컴파일러 호스트, deno_stpescript, deno번들, deno설치, deno설치, deno유형, 스트림 구현을 포함하여(이에 국한되지 않음)시스템의 많은 부분에서 많은 작업을 수행한@kitsonk. @kevinkassimo는 프로젝트의 전체 역사에 걸쳐 수많은 버그 수정을 제공해 왔습니다. 그가 기여한 것들 중에는 타이머 시스템, TTY통합, 워버스 지원 등이 있다. Deno.make TempFile, Deno.kill, Deno.hostname, Deno.realPath, std4node의 요구 사항, 창. queueMircotask및 REPL내역. 그는 또한 이 로고를 만들었다. @kt는 지속적인 벤치 마크 시스템(거의 모든 주요 인자에 중요한 역할을 했다), 신호 처리기, 권한 API, 그리고 많은 중요 버그 수정들을 구현했다. @Nayeemrmn은 Deno의 많은 부분에서 버그 수정을 제공합니다. 특히 그는 스택 추적과 오류 보고를 크게 개선했으며 1.0의 API안정화를 위해 강력한 도움을 주었습니다.@justjavac는 DenoAPI를 웹 표준에 맞추기 위해 많은 작지만 중요한 해결책을 제공했으며, 가장 유명한 것은 VSCodeDeno플러그 인을 작성했습니다. @zekth는 많은 모듈들을 std에 기여했다. std//encoding/csv, std///coding/tol/html, std/html/totp/cookies, 그리고 많은 다른 버그 수정들. @Axetroy는 더 예뻐 보이는 것과 관련된 모든 것을 도왔고 많은 버그 수정을 제공했으며 VS코드 플러그 인을 유지해 왔습니다. @msinch7은 플러그 인 시스템을 구현했습니다. @keroxp는 websocket서버를 구현하고 많은 버그 수정을 제공했다. @cknight는 많은 문서와 std//nodepolyfills를 제공했다. @lucasonato는 거의 모든 deno.land웹 사이트를 구축했다. @hashrock는 doc.deno.land의 로딩 페이지와 이 페이지의 상단에 있는 사랑스러운 이미지와 같은 많은 놀라운 예술 작품들을 했다.

 

 

원문:

 

Dynamic languages are useful tools. Scripting allows users to rapidly and succinctly tie together complex systems and express ideas without worrying about details like memory management or build systems. In recent years programming languages like Rust and Go have made it much easier to produce sophisticated native machine code; these projects are incredibly important developments in computer infrastructure. However, we claim it is still important to have a powerful scripting environment that can address a wide range of problem domains.

JavaScript is the most widely used dynamic language, operating on every device with a web browser. Vast numbers of programmers are fluent in JavaScript and much effort has been put into optimizing its execution. Through standards organizations like ECMA International, the language has been carefully and continuously improved. We believe JavaScript is the natural choice for dynamic language tooling; whether in a browser environment or as standalone processes.

Our original undertaking in this area, Node.js, proved to be a very successful software platform. People have found it useful for building web development tooling, building standalone web servers, and for a myriad of other use-cases. Node, however, was designed in 2009 when JavaScript was a much different language. Out of necessity, Node had to invent concepts which were later taken up by the standards organizations and added to the language differently. In the presentation Design Mistakes in Node, this is discussed in more detail. Due to the large number of users that Node has, it is difficult and slow to evolve the system.

With the changing JavaScript language, and new additions like TypeScript, building Node projects can become an arduous endeavor, involving managing build systems and other heavy handed tooling that takes away from the fun of dynamic language scripting. Furthermore the mechanism for linking to external libraries is fundamentally centralized through the NPM repository, which is not inline with the ideals of the web.

We feel that the landscape of JavaScript and the surrounding software infrastructure has changed enough that it was worthwhile to simplify. We seek a fun and productive scripting environment that can be used for a wide range of tasks.

A Web Browser for Command-Line Scripts

Deno is a new runtime for executing JavaScript and TypeScript outside of the web browser.

Deno attempts to provide a standalone tool for quickly scripting complex functionality. Deno is (and always will be) a single executable file. Like a web browser, it knows how to fetch external code. In Deno, a single file can define arbitrarily complex behavior without any other tooling.

 

import { serve } from "https://deno.land/std@0.50.0/http/server.ts";

for await (const req of serve({ port: 8000 })) {
  req.respond({ body: "Hello World\n" });
}

Here a complete HTTP server module is added as a dependency in a single line. There are no additional configuration files, there is no install to do beforehand, just deno run example.js.

Also like browsers, code is executed in a secure sandbox by default. Scripts cannot access the hard drive, open network connections, or make any other potentially malicious actions without permission. The browser provides APIs for accessing cameras and microphones, but users must first give permission. Deno provides analogous behaviour in the terminal. The above example will fail unless the --allow-net command-line flag is provided.

Deno is careful to not deviate from standardized browser JavaScript APIs. Of course, not every browser API is relevant for Deno, but where they are, Deno does not deviate from the standard.

First Class TypeScript Support

We want Deno to be applicable to a wide range of problem domains: from small one-line scripts, to complex server-side business logic. As programs become more complex, having some form of type checking becomes increasingly important. TypeScript is an extension of the JavaScript language that allows users to optionally provide type information.

Deno supports TypeScript without additional tooling. The runtime is designed with TypeScript in mind. The deno types command provides type declarations for everything provided by Deno. Deno's standard modules are all written in TypeScript.

Promises All The Way Down

Node was designed before JavaScript had the concept of Promises or async/await. Node's counterpart to promises was the EventEmitter, which important APIs are based around, namely sockets and HTTP. Setting aside the ergonomic benefits of async/await, the EventEmitter pattern has an issue with back-pressure. Take a TCP socket, for example. The socket would emit "data" events when it received incoming packets. These "data" callbacks would be emitted in an unconstrained manner, flooding the process with events. Because Node continues to receive new data events, the underlying TCP socket does not have proper back-pressure, the remote sender has no idea the server is overloaded and continues to send data. To mitigate this problem, a pause() method was added. This could solve the problem, but it required extra code; and since the flooding issue only presents itself when the process is very busy, many Node programs can be flooded with data. The result is a system with bad tail latency.

In Deno, sockets are still asynchronous, but receiving new data requires users to explicitly read(). No extra pause semantics are necessary to properly structure a receiving socket. This is not unique to TCP sockets. The lowest level binding layer to the system is fundamentally tied to promises - we call these bindings "ops". All callbacks in Deno in some form or another arise from promises.

Rust has its own promise-like abstraction, called Futures. Through the "op" abstraction, Deno makes it easy to bind Rust future-based APIs into JavaScript promises.

Rust APIs

The primary component that we ship is the Deno command-line interface (CLI). The CLI is the thing that is version 1.0 today. But Deno is not a monolithic program, but designed as a collection of Rust crates to allow integration at different layers.

The deno_core crate is a very bare bones version of Deno. It does not have dependencies on TypeScript nor on Tokio. It simply provides our Op and Resource infrastructure. That is, it provides an organized way of binding Rust futures to JavaScript promises. The CLI is of course built entirely on top of deno_core.

The rusty_v8 crate provides high quality Rust bindings to V8's C++ API. The API tries to match the original C++ API as closely as possible. It's a zero-cost binding - the objects that are exposed in Rust are exactly the object you manipulate in C++. (Previous attempts at Rust V8 bindings forced the use of Persistent handles, for example.) The crate provides binaries that are built in Github Actions CI, but it also allows users to compile V8 from scratch and adjust its many build configurations. All of the V8 source code is distributed in the crate itself. Finally rusty_v8 attempts to be a safe interface. It's not yet 100% safe, but we're getting close. Being able to interact with a VM as complex as V8 in a safe way is quite amazing and has allowed us to discover many difficult bugs in Deno itself.

Stability

We promise to maintain a stable API in Deno. Deno has a lot of interfaces and components, so it's important to be transparent about what we mean by "stable". The JavaScript APIs that we have invented to interact with the operating system are all found inside the "Deno" namespace (e.g. Deno.open()). These have been carefully examined and we will not be making backwards incompatible changes to them.

All functionality which is not yet ready for stabilization has been hidden behind the --unstable command-line flag. You can see the documentation for the unstable interfaces here. In subsequent releases, some of these APIs will be stabilized as well.

In the global namespace you'll find all sorts of other objects (e.g. setTimeout() and fetch()). We've tried very hard to keep these interfaces identical to those in the browser; but we will issue corrections if we discover inadvertent incompatibilities. The browser standards define these interfaces, not us. Any corrections issued by us are bug fixes, not interface changes. If there is an incompatibility with a browser standard API, that incompatibility may be corrected before a major release.

Deno also has many Rust APIs, namely the deno_core and rusty_v8 crates. None of these APIs are at 1.0 yet. We will continue to iterate on them.

Limitations

It's important to understand that Deno is not a fork of Node - it's a completely new implementation. Deno has been under development for just two years, while Node has been under development for over a decade. Given the amount of interest in Deno, we expect it to continue to evolve and mature.

For some applications Deno may be a good choice today, for others not yet. It will depend on the requirements. We want to be transparent about these limitations to help people make informed decisions when considering to use Deno.

Compatibility

Unfortunately, many users will find a frustrating lack of compatibility with existing JavaScript tooling. Deno is not compatible, in general, with Node (NPM) packages. There is a nascent compatibility layer being built at https://deno.land/std/node/ but it is far from complete.

Although Deno has taken a hardline approach to simplifying the module system, ultimately Deno and Node are pretty similar systems with similar goals. Over time, we expect Deno to be able to run more and more Node programs out-of-the-box.

HTTP Server Performance

We continuously track the performance of Deno's HTTP server. A hello-world Deno HTTP server does about 25k requests per second with a max latency of 1.3 milliseconds. A comparable Node program does 34k requests per second with a rather erratic max latency between 2 and 300 milliseconds.

Deno's HTTP server is implemented in TypeScript on top of native TCP sockets. Node's HTTP server is written in C and exposed as high-level bindings to JavaScript. We have resisted the urge to add native HTTP server bindings to Deno, because we want to optimize the TCP socket layer, and more generally the op interface.

Deno is a proper asynchronous server and 25k requests per second is quite enough for most purposes. (If it's not, probably JavaScript is not the best choice.) Furthermore, we expect Deno to generally exhibit better tail latency due to the ubiquitous use of promises (discussed above). All that said, we do believe there are more performance wins to be had in the system, and we hope to achieve that in future releases.

TSC Bottleneck

Internally Deno uses Microsoft's TypeScript compiler to check types and produce JavaScript. Compared to the time it takes V8 to parse JavaScript, it is very slow. Early on in the project we had hoped that "V8 Snapshots" would provide significant improvements here. Snapshots have certainly helped but it's still unsatisfyingly slow. We certainly think there are improvements that can be done here on top of the existing TypeScript compiler, but it's clear to us that ultimately the type checking needs to be implemented in Rust. This will be a massive undertaking and will not happen any time soon; but it would provide order of magnitude performance improvements in a critical path experienced by developers. TSC must be ported to Rust. If you're interested in collaborating on this problem, please get in touch.

Plugins / Extensions

We have a nascent plugin system for extending the Deno runtime with custom ops. However this interface is still under development and has been marked as unstable. Therefore, accessing native systems beyond that which is provided by Deno is difficult.

Acknowledgements

Many thanks to the many contributors who helped make this release possible. Especially: @kitsonk who has had a massive hand in many parts of the system, including (but not limited to) the TypeScript compiler host, deno_typescript, deno bundle, deno install, deno types, streams implementation. @kevinkassimo has contributed countless bug fixes over the whole history of the project. Among his contributions are the timer system, TTY integration, wasm support. Deno.makeTempFile, Deno.kill, Deno.hostname, Deno.realPath, std/node's require, window.queueMircotask, and REPL history. He also created the logo. @kt3k implemented the continuous benchmark system (which has been instrumental in almost every major refactor), signal handlers, the permissions API, and many critical bug fixes. @nayeemrmn contributes bug fixes in many parts of Deno, most notably he greatly improved the stack trace and error reporting, and has been a forceful help towards the stabilizing the APIs for 1.0. @justjavac has contributed many small but critical fixes to align deno APIs with web standards and most famously he wrote the VS Code deno plugin. @zekth has contributed a lot of modules to std, among them the std/encoding/csv, std/encoding/toml, std/http/cookies, as well as many other bug fixes. @axetroy has helped with all things related to prettier, contributed many bug fixes, and has maintained the VS Code plugin. @afinch7 implemented the plugin system. @keroxp implemented the websocket server and provided many bug fixes. @cknight has provided a lot of documentation and std/node polyfills. @lucacasonato built almost the entire deno.land website. @hashrock has done a lot of amazing artwork, like the loading page on doc.deno.land and the lovely image at the top of this page!

 

출처 : https://deno.land/v1

반응형

+ Recent posts