diff --git a/1-js/01-getting-started/1-intro/article.md b/1-js/01-getting-started/1-intro/article.md index 6a998c78ab..693d29b18d 100644 --- a/1-js/01-getting-started/1-intro/article.md +++ b/1-js/01-getting-started/1-intro/article.md @@ -1,10 +1,6 @@ # 자바스크립트란? -<<<<<<< HEAD 자바스크립트(JavaScript)가 언어로서 지닌 특징에 대해 알아보겠습니다. 이어서 자바스크립트로 무엇을 할 수 있을지, 다른 기술들이 자바스크립트를 어떻게 활용하고 있는지도 이야기해 보겠습니다. -======= -Let's see what's so special about JavaScript, what we can achieve with it, and what other technologies play well with it. ->>>>>>> upstream/master ## 정의 @@ -28,44 +24,26 @@ Let's see what's so special about JavaScript, what we can achieve with it, and w 엔진의 종류는 다양한데, 엔진마다 특유의 코드네임이 있습니다. 아래처럼 말이죠. -<<<<<<< HEAD - [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- Chrome과 Opera에서 쓰입니다. - [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- Firefox에서 쓰입니다. - IE는 버전에 따라 'Trident'나 'Chakra'라 불리는 엔진을 사용합니다. 'ChakraCore'는 Microsoft Edge에 사용되며, 'SquirrelFish'는 Safari에 사용됩니다. 위의 코드네임은 개발 관련 글에서 종종 언급되기 때문에 기억해 두는 것이 좋습니다. 본 튜토리얼에서도 해당 코드네임을 사용할 예정입니다. "X라는 기능은 V8에서만 지원합니다."라는 식으로 말이죠. 이런 문장을 만나면 Chrome과 Opera에서만 이 기능을 지원한다고 이해하시면 됩니다. -======= -- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome, Opera and Edge. -- [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- in Firefox. -- ...There are other codenames like "Chakra" for IE, "JavaScriptCore", "Nitro" and "SquirrelFish" for Safari, etc. - -The terms above are good to remember because they are used in developer articles on the internet. We'll use them too. For instance, if "a feature X is supported by V8", then it probably works in Chrome, Opera and Edge. ->>>>>>> upstream/master ```smart header="엔진은 어떻게 동작하나요?" 엔진이 어떻게 동작하는지 이해하려면 상당한 시간을 쏟아부어야 합니다. 하지만 기본 원리는 다음과 같이 간단합니다. -<<<<<<< HEAD 1. 엔진(브라우저라면 내장 엔진)이 스크립트를 읽습니다(파싱). 2. 읽어 들인 스크립트를 기계어로 전환합니다(컴파일). 3. 기계어로 전환된 코드가 실행됩니다. 기계어로 전환되었기 때문에 실행 속도가 빠릅니다. -======= -1. The engine (embedded if it's a browser) reads ("parses") the script. -2. Then it converts ("compiles") the script to machine code. -3. And then the machine code runs, pretty fast. ->>>>>>> upstream/master 엔진은 프로세스 각 단계마다 최적화를 진행합니다. 심지어 컴파일이 끝나고 실행 중인 코드를 감시하면서, 이 코드로 흘러가는 데이터를 분석하고, 분석 결과를 토대로 기계어로 전환된 코드를 다시 최적화하기도 합니다. 이런 과정을 거치면 스크립트 실행 속도는 더욱 더 빨라집니다. ``` ## 브라우저에서 할 수 있는 일 -<<<<<<< HEAD 모던 자바스크립트는 '안전한' 프로그래밍 언어입니다. 메모리나 CPU 같은 저수준 영역의 조작을 허용하지 않습니다. 애초에 이러한 접근이 필요치 않은 브라우저를 대상으로 만든 언어이기 때문이죠. -======= -Modern JavaScript is a "safe" programming language. It does not provide low-level access to memory or the CPU, because it was initially created for browsers which do not require it. ->>>>>>> upstream/master 자바스크립트의 능력은 실행 환경에 상당한 영향을 받습니다. [Node.js](https://wikipedia.org/wiki/Node.js) 환경에선 임의의 파일을 읽거나 쓰고, 네트워크 요청을 수행하는 함수를 지원합니다. @@ -81,11 +59,7 @@ Modern JavaScript is a "safe" programming language. It does not provide low-leve ## 브라우저에서 할 수 없는 일 -<<<<<<< HEAD 브라우저는 보안을 위해 자바스크립트의 기능에 제약을 걸어놓았습니다. 이런 제약은 악성 웹페이지가 개인 정보에 접근하거나 사용자의 데이터를 손상하는 것을 막기 위해 만들어졌습니다. -======= -JavaScript's abilities in the browser are limited to protect the user's safety. The aim is to prevent an evil webpage from accessing private information or harming the user's data. ->>>>>>> upstream/master 몇 가지 제약사항을 소개해 드리겠습니다. @@ -93,7 +67,6 @@ JavaScript's abilities in the browser are limited to protect the user's safety. 모던 브라우저를 사용하면 파일을 다룰 순 있습니다. 하지만 접근은 제한되어 있습니다. 사용자가 브라우저 창에 파일을 '끌어다 두거나' `` 태그를 통해 파일을 선택할 때와 같이 특정 상황에서만 파일 접근을 허용합니다. -<<<<<<< HEAD 카메라나 마이크 같은 디바이스와 상호 작용하려면 사용자의 명시적인 허가가 있어야 합니다. 자바스크립트가 활성화된 페이지라도 사용자 몰래 웹 카메라를 작동 시켜 수집한 정보를 [국가안보국(NSA)](https://en.wikipedia.org/wiki/National_Security_Agency)과 같은 곳에 몰래 전송할 수 없습니다. - 브라우저 내 탭과 창은 대개 서로의 정보를 알 수 없습니다. 그런데 자바스크립트를 사용해 한 창에서 다른 창을 열 때는 예외가 적용됩니다. 하지만 이 경우에도 도메인이나 프로토콜, 포트가 다르다면 페이지에 접근할 수 없습니다. @@ -105,44 +78,21 @@ JavaScript's abilities in the browser are limited to protect the user's safety. ![](limitations.svg) 브라우저 환경 밖, 예를 들어 서버라면 이러한 제약은 존재하지 않을 것입니다. 다만, 모던 브라우저에선 추가 권한 허가를 요청하는 플러그인이나 익스텐션 설치가 허용됩니다. -======= - There are ways to interact with the camera/microphone and other devices, but they require a user's explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the [NSA](https://en.wikipedia.org/wiki/National_Security_Agency). -- Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other page if they come from different sites (from a different domain, protocol or port). - - This is called the "Same Origin Policy". To work around that, *both pages* must agree for data exchange and must contain special JavaScript code that handles it. We'll cover that in the tutorial. - - This limitation is, again, for the user's safety. A page from `http://anysite.com` which a user has opened must not be able to access another browser tab with the URL `http://gmail.com`, for example, and steal information from there. -- JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is severely limited. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that's a safety limitation. - -![](limitations.svg) - -Such limitations do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugins/extensions which may ask for extended permissions. ->>>>>>> upstream/master ## 자바스크립트만의 강점 자바스크립트엔 다양한 장점이 있지만 여기선 *세 가지*만 언급해 보도록 하겠습니다. ```compare -<<<<<<< HEAD + HTML/CSS와 완전히 통합할 수 있음 + 간단한 일은 간단하게 처리할 수 있게 해줌 + 모든 주요 브라우저에서 지원하고, 기본 언어로 사용됨 -======= -+ Full integration with HTML/CSS. -+ Simple things are done simply. -+ Supported by all major browsers and enabled by default. ->>>>>>> upstream/master ``` 이 세 가지 모두를 지원하는 브라우저 연관 기술은 자바스크립트뿐입니다. 이런 특징 때문에 자바스크립트는 브라우저 인터페이스를 만들 때 가장 널리 사용되고 있습니다. -<<<<<<< HEAD 이 외에도 자바스크립트를 이용해 서버나 모바일 앱 등을 만드는 것도 가능합니다. -======= -That said, JavaScript can be used to create servers, mobile applications, etc. ->>>>>>> upstream/master ## 자바스크립트 '너머의' 언어들 @@ -150,42 +100,21 @@ That said, JavaScript can be used to create servers, mobile applications, etc. 프로젝트마다 요구사항이 천차만별이기 때문에 이는 당연한 현상입니다. -<<<<<<< HEAD 이로 인해 근래엔 브라우저에서 실행 되기 전에 자바스크립트로 *트랜스파일(transpile, 변환)* 할 수 있는 새로운 언어들이 많이 등장했습니다. -======= -So, recently a plethora of new languages appeared, which are *transpiled* (converted) to JavaScript before they run in the browser. ->>>>>>> upstream/master 최신 툴을 사용하면 트랜스파일을 빠르고 명확하게 수행할 수 있습니다. 최신도구는 자바스크립트 이외의 언어로 작성한 코드를 '보이지 않는 곳에서' 자바스크립트로 자동 변환해줍니다. 자바스크립트로 트랜스파일이 가능한 언어 몇 가지를 소개해 드리겠습니다. -<<<<<<< HEAD - [CoffeeScript](http://coffeescript.org/)는 자바스크립트를 위한 'syntactic sugar'입니다. 짧은 문법을 도입하여 명료하고 이해하기 쉬운 코드를 작성할 수 있습니다. Ruby 개발자들이 좋아합니다. - [TypeScript](http://www.typescriptlang.org/)는 개발을 단순화 하고 복잡한 시스템을 지원하려는 목적으로 '자료형의 명시화(strict data typing)'에 집중해 만든 언어입니다. Microsoft가 개발하였습니다. - [Flow](http://flow.org/) 역시 자료형을 강제하는데, TypeScript와는 다른 방식을 사용합니다. Facebook이 개발하였습니다. - [Dart](https://www.dartlang.org/)는 모바일 앱과 같이 브라우저가 아닌 환경에서 동작하는 고유의 엔진을 가진 독자적 언어입니다. Google이 개발하였습니다. 이 외에도 자바스크립트로 트랜스파일 할 수 있는 언어는 다양합니다. 개발 언어로 이런 언어 중 하나를 택한다고 하더라도 자신이 무엇을 하고 있는지 이해하려면 결국엔 자바스크립트를 알아야 합니다. -======= -- [CoffeeScript](https://coffeescript.org/) is "syntactic sugar" for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it. -- [TypeScript](https://www.typescriptlang.org/) is concentrated on adding "strict data typing" to simplify the development and support of complex systems. It is developed by Microsoft. -- [Flow](https://flow.org/) also adds data typing, but in a different way. Developed by Facebook. -- [Dart](https://www.dartlang.org/) is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google. -- [Brython](https://brython.info/) is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript. -- [Kotlin](https://kotlinlang.org/docs/reference/js-overview.html) is a modern, concise and safe programming language that can target the browser or Node. - -There are more. Of course, even if we use one of these transpiled languages, we should also know JavaScript to really understand what we're doing. ->>>>>>> upstream/master ## 요약 -<<<<<<< HEAD - 자바스크립트는 브라우저에서만 쓸 목적으로 고안된 언어이지만, 지금은 다양한 환경에서 쓰이고 있습니다. - 오늘날 자바스크립트는 브라우저 환경에서 가장 널리 사용되는 언어로 자리매김하였습니다. HTML/CSS와 완전한 통합이 가능합니다. - 자바스크립트로 '트랜스파일'할 수 있는 언어는 많습니다. 각 언어마다 고유한 기능을 제공하죠. 자바스크립트에 숙달한 뒤에 이 언어들을 살펴볼 것을 추천드립니다. -======= -- JavaScript was initially created as a browser-only language, but it is now used in many other environments as well. -- Today, JavaScript has a unique position as the most widely-adopted browser language, fully integrated with HTML/CSS. -- There are many languages that get "transpiled" to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript. ->>>>>>> upstream/master diff --git a/1-js/01-getting-started/2-manuals-specifications/article.md b/1-js/01-getting-started/2-manuals-specifications/article.md index 5213d5acf3..c0507a6337 100644 --- a/1-js/01-getting-started/2-manuals-specifications/article.md +++ b/1-js/01-getting-started/2-manuals-specifications/article.md @@ -1,11 +1,7 @@ # 매뉴얼과 명세서 -<<<<<<< HEAD 본 *튜토리얼*은 자바스크립트를 기본부터 차근차근 배울 수 있도록 만들어졌습니다. 그런데 어느 정도 자바스크립트가 익숙해지면 튜토리얼 이외의 자료가 필요한 시점이 옵니다. -======= -This book is a *tutorial*. It aims to help you gradually learn the language. But once you're familiar with the basics, you'll need other resources. ->>>>>>> upstream/master ## 명세서 @@ -13,23 +9,14 @@ This book is a *tutorial*. It aims to help you gradually learn the language. But ECMA-262 명세서의 고유한 형식 때문에 명세서를 처음 접하는 사람은 그 내용을 이해하기가 쉽지 않습니다. 자바스크립트에 관한 정보를 얻을 수 있는 가장 신뢰할 만한 자료이긴 하지만 일상적인 참고 자료로는 적합하지 않죠. -<<<<<<< HEAD ECMA-262명세서는 새로운 버전이 매년 나옵니다. 공식 버전이 나오기 이전의 최신 초안은 에서 확인할 수 있습니다. -======= -A new specification version is released every year. Between these releases, the latest specification draft is at . ->>>>>>> upstream/master 갓 명세서에 등록된 기능이나 '등록되기 바로 직전'에 있는 기능(스테이지(stage)3 상태의 기능), 제안 목록은 에서 확인할 수 있습니다. -<<<<<<< HEAD 본 튜토리얼의 [두 번째 대 단원](info:browser-environment)에서 브라우저와 관련된 명세서를 다룰 예정이므로, 만약 브라우저에서 돌아가는 기능을 구현하는 개발자라면 해당 내용을 확인해 보시기 바랍니다. -======= -Also, if you're developing for the browser, then there are other specifications covered in the [second part](info:browser-environment) of the tutorial. ->>>>>>> upstream/master ## 매뉴얼 -<<<<<<< HEAD - Mozilla 재단이 운영하는 **MDN JavaScript Reference**엔 다양한 예제와 정보가 있습니다. 특정 함수나 메서드에 대한 깊이 있는 정보를 얻고 싶다면 이 사이트가 제격입니다. 링크는 다음과 같습니다. @@ -41,28 +28,10 @@ Also, if you're developing for the browser, then there are other specifications 자바스크립트는 끊임없이 발전하는 언어입니다. 새로운 기능이 정기적으로 추가되죠. 특정 브라우저나 엔진이 내가 사용하려는 기능을 지원하는지 확인할 땐, 아래 두 사이트가 좋습니다. -======= -- **MDN (Mozilla) JavaScript Reference** is the main manual with examples and other information. It's great to get in-depth information about individual language functions, methods etc. - - You can find it at . - -Although, it's often best to use an internet search instead. Just use "MDN [term]" in the query, e.g. to search for the `parseInt` function. ->>>>>>> upstream/master - 에선 브라우저가 특정 기능을 지원하는지 (표 형태로) 확인할 수 있습니다. 암호화 관련 기능인 cryptography를 특정 브라우저에서 사용할 수 있는지 아닌지를 보려면 를 확인하면 됩니다. - 에선 자바스크립트 기능 목록이 있고, 해당 기능을 특정 엔진이 지원하는지 여부를 거대한 표를 통해 보여줍니다. 실제 개발을 하다 보면 위에 언급 드린 자료가 아주 유용할 겁니다. 메서드나 함수 관련 정보, 브라우저 지원 여부 등은 의사결정을 내릴 때 꼭 필요한 정보이기 때문입니다. -<<<<<<< HEAD 말씀드린 사이트나 이 페이지를 기억해 놓았다가 특정 기능에 대한 상세한 정보가 필요할 때 방문해 보시길 바랍니다. -======= -To see their support among browser-based and other engines, see: - -- - per-feature tables of support, e.g. to see which engines support modern cryptography functions: . -- - a table with language features and engines that support those or don't support. - -All these resources are useful in real-life development, as they contain valuable information about language details, their support, etc. - -Please remember them (or this page) for the cases when you need in-depth information about a particular feature. ->>>>>>> upstream/master diff --git a/1-js/01-getting-started/3-code-editors/article.md b/1-js/01-getting-started/3-code-editors/article.md index f18a823a1f..21e365ba21 100644 --- a/1-js/01-getting-started/3-code-editors/article.md +++ b/1-js/01-getting-started/3-code-editors/article.md @@ -12,13 +12,8 @@ IDE를 이용하면 수많은 파일로 구성된 프로젝트를 불러오고, 아직 어떤 IDE를 사용할지 결정하지 못했다면, 아래 두 옵션을 고려해 보시길 바랍니다. -<<<<<<< HEAD - [Visual Studio Code](https://code.visualstudio.com/) (크로스 플랫폼, 무료) - [WebStorm](http://www.jetbrains.com/webstorm/) (크로스 플랫폼, 유료) -======= -- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free). -- [WebStorm](https://www.jetbrains.com/webstorm/) (cross-platform, paid). ->>>>>>> upstream/master Windows 사용자라면 'Visual Studio'라는 IDE를 들어보셨을 겁니다. Visual Studio는 'Visual Studio Code'와는 다릅니다. 'Visual Studio'는 .NET 플랫폼 개발에 쓰이는 유료 에디터로, Windows에서만 사용할 수 있습니다. 자바스크립트도 지원합니다. Visual Studio의 무료 버전인 [Visual Studio Community](https://www.visualstudio.com/vs/community/)도 있으니 참고하시기 바랍니다. @@ -34,7 +29,6 @@ Windows 사용자라면 'Visual Studio'라는 IDE를 들어보셨을 겁니다. 경량 에디터는 다양한 플러그인을 지원합니다. 디렉터리 레벨 문법 분석기나 자동완성기능 등을 플러그인을 설치해 사용할 수 있습니다. 플러그인을 사용하면 경량 에디터에서도 IDE 못지않게 다양한 기능을 사용할 수 있죠. 요즘엔 경량 에디터와 IDE 사이의 엄격한 구분이 사라져가는 추세입니다. -<<<<<<< HEAD 추천하는 에디터는 다음과 같습니다. - [Atom](https://atom.io/) (크로스 플랫폼, 무료) @@ -42,13 +36,6 @@ Windows 사용자라면 'Visual Studio'라는 IDE를 들어보셨을 겁니다. - [Sublime Text](http://www.sublimetext.com) (크로스 플랫폼, 셰어웨어) - [Notepad++](https://notepad-plus-plus.org/) (Windows, 무료) - [Vim](http://www.vim.org/)이나 [Emacs](https://www.gnu.org/software/emacs/)도 에디터로 사용법만 잘 숙지하면 충분히 에디터 역할을 잘합니다. -======= -There are many options, for instance: - -- [Sublime Text](https://www.sublimetext.com/) (cross-platform, shareware). -- [Notepad++](https://notepad-plus-plus.org/) (Windows, free). -- [Vim](https://www.vim.org/) and [Emacs](https://www.gnu.org/software/emacs/) are also cool if you know how to use them. ->>>>>>> upstream/master ## 논쟁하지 맙시다 @@ -56,13 +43,10 @@ There are many options, for instance: 이 외에도 제가 모르는 훌륭한 에디터가 있을 수 있으니 여러분이 가장 좋아하는 것 하나를 택하시면 됩니다. -<<<<<<< HEAD 여타 툴과 마찬가지로 에디터를 선택하는 것은 프로젝트의 종류, 개발 습관, 개인 성향에 따라 다르므로 이에 관한 논쟁은 지양하도록 합시다. -======= -The choice of an editor, like any other tool, is individual and depends on your projects, habits, and personal preferences. -The author's personal opinion: +저자의 개인적인 의견은 다음과 같습니다. + +- 프론트엔드 개발을 주로 한다면 [Visual Studio Code](https://code.visualstudio.com/)를 사용하는 편이 좋습니다. +- 반대로 다른 언어·플랫폼 개발이 주가 되고 프론트엔드는 일부만 다룬다면 Xcode(Mac), Microsoft Visual Studio(Windows), 또는 JetBrains 계열 IDE(WebStorm, PHPStorm, RubyMine 등)를 고려해볼 수 있습니다. 사용하는 언어에 따라 적절한 제품을 선택하면 됩니다. -- I'd use [Visual Studio Code](https://code.visualstudio.com/) if I develop mostly frontend. -- Otherwise, if it's mostly another language/platform and partially frontend, then consider other editors, such as XCode (Mac), Visual Studio (Windows) or Jetbrains family (Webstorm, PHPStorm, RubyMine etc, depending on the language). ->>>>>>> upstream/master diff --git a/1-js/01-getting-started/4-devtools/article.md b/1-js/01-getting-started/4-devtools/article.md index 7b98beeb99..aaaf27ea00 100644 --- a/1-js/01-getting-started/4-devtools/article.md +++ b/1-js/01-getting-started/4-devtools/article.md @@ -49,11 +49,7 @@ Mac 전용 브라우저인 Safari에서 개발자 도구를 사용하려면 '개발자 메뉴(Develop menu)'를 명시적으로 활성화해주어야 합니다. -<<<<<<< HEAD 환경설정(Preferences)의 '고급(Advanced)' 패널을 클릭한 후 '메뉴 막대에서 개발자용 메뉴 보기' 체크 박스를 체크해 개발자 도구를 활성화해봅시다. -======= -Open Settings and go to the "Advanced" pane. There's a checkbox at the bottom: ->>>>>>> upstream/master ![safari](safari.png) diff --git a/1-js/13-modules/01-modules-intro/article.md b/1-js/13-modules/01-modules-intro/article.md index e5dff1ef63..c164cb3b32 100644 --- a/1-js/13-modules/01-modules-intro/article.md +++ b/1-js/13-modules/01-modules-intro/article.md @@ -9,19 +9,11 @@ 그 시도는 다음과 같은 모듈 시스템으로 이어졌습니다. -<<<<<<< HEAD - [AMD](https://en.wikipedia.org/wiki/Asynchronous_module_definition) -- 가장 오래된 모듈 시스템 중 하나로 [require.js](http://requirejs.org/)라는 라이브러리를 통해 처음 개발되었습니다. - [CommonJS](http://wiki.commonjs.org/wiki/Modules/1.1) -- Node.js 서버를 위해 만들어진 모듈 시스템입니다. - [UMD](https://github.com/umdjs/umd) -- AMD와 CommonJS와 같은 다양한 모듈 시스템을 함께 사용하기 위해 만들어졌습니다. 이런 모듈 시스템은 오래된 스크립트에서 여전히 발견할 수 있는데, 이제는 역사의 뒤안길로 사라져가고 있습니다. -======= -- [AMD](https://en.wikipedia.org/wiki/Asynchronous_module_definition) -- one of the most ancient module systems, initially implemented by the library [require.js](https://requirejs.org/). -- [CommonJS](https://wiki.commonjs.org/wiki/Modules/1.1) -- the module system created for Node.js server. -- [UMD](https://github.com/umdjs/umd) -- one more module system, suggested as a universal one, compatible with AMD and CommonJS. - -Now these all slowly became a part of history, but we still can find them in old scripts. ->>>>>>> upstream/master 모듈 시스템은 2015년에 표준으로 등재되었습니다. 이 이후로 관련 문법은 진화를 거듭해 이제는 대부분의 주요 브라우저와 Node.js가 모듈 시스템을 지원하고 있습니다. 이제 본격적으로 모던 자바스크립트에서 쓰이는 모듈에 대해 알아봅시다. @@ -65,13 +57,8 @@ sayHi('John'); // Hello, John! 브라우저가 자동으로 모듈을 가져오고 평가한 다음, 이를 실행한 것을 확인할 수 있습니다. -<<<<<<< HEAD ```warn header="모듈은 로컬 파일에서 동작하지 않고, HTTP 또는 HTTPS 프로토콜을 통해서만 동작합니다." 로컬에서 `file://` 프로토콜을 사용해 웹페이지를 열면 `import`, `export` 지시자가 동작하지 않습니다. 예시를 실행하려면 로컬 웹 서버인 [static-server](https://www.npmjs.com/package/static-server#getting-started)나, 코드 에디터의 '라이브 서버' 익스텐션(Visual Studio Code 에디터의 경우 [Live Server Extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer))을 사용하세요. -======= -```warn header="Modules work only via HTTP(s), not locally" -If you try to open a web-page locally, via `file://` protocol, you'll find that `import/export` directives don't work. Use a local web-server, such as [static-server](https://www.npmjs.com/package/static-server#getting-started) or use the "live server" capability of your editor, such as VS Code [Live Server Extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) to test modules. ->>>>>>> upstream/master ``` ## 모듈의 핵심 기능 @@ -82,11 +69,7 @@ If you try to open a web-page locally, via `file://` protocol, you'll find that ### 엄격 모드로 실행됨 -<<<<<<< HEAD 모듈은 항상 `엄격 모드(use strict)`로 실행됩니다. 선언되지 않은 변수에 값을 할당하는 등의 코드는 에러를 발생시킵니다. -======= -Modules always work in strict mode. E.g. assigning to an undeclared variable will give an error. ->>>>>>> upstream/master ```html run ``` -<<<<<<< HEAD 참고로 브라우저 환경에서 부득이하게 window 레벨 전역 변수를 만들어야 한다면 `window` 객체에 변수를 명시적으로 할당하고 `window.user`와 같이 접근하는 방식을 취하시면 됩니다. 그런데 이 방법은 정말 필요한 경우에만 사용하길 권유합니다. -======= -```smart -In the browser, we can make a variable window-level global by explicitly assigning it to a `window` property, e.g. `window.user = "John"`. - -Then all scripts will see it, both with `type="module"` and without it. - -That said, making such global variables is frowned upon. Please try to avoid them. -``` ->>>>>>> upstream/master ### 단 한 번만 평가됨 -<<<<<<< HEAD 동일한 모듈이 여러 곳에서 사용되더라도 모듈은 최초 호출 시 단 한 번만 실행됩니다. 실행 후 결과는 이 모듈을 가져가려는 모든 모듈에 내보내 집니다. 이런 작동 방식은 중요한 결과를 초래합니다. 예시를 통해 이에 대해 알아봅시다. -======= -If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers. - -The one-time evaluation has important consequences, that we should be aware of. - -Let's see a couple of examples. ->>>>>>> upstream/master alert 함수가 있는 모듈(`alert.js`)을 여러 모듈에서 가져오기로 해봅시다. 얼럿 창은 단 한 번만 나타납니다. @@ -187,17 +135,11 @@ import `./alert.js`; // 얼럿창에 '모듈이 평가되었습니다!'가 출 import `./alert.js`; // 아무 일도 발생하지 않습니다. ``` -<<<<<<< HEAD -실무에선 최상위 레벨 모듈을 대개 초기화나 내부에서 쓰이는 데이터 구조를 만들고 이를 내보내 재사용하고 싶을 때 사용합니다. - -이제 좀 더 어려운 예시를 살펴보겠습니다. -======= -The second import shows nothing, because the module has already been evaluated. +두 번째 import에서는 아무것도 출력되지 않습니다. 모듈 코드가 이미 한 번 실행되었기 때문입니다. -There's a rule: top-level module code should be used for initialization, creation of module-specific internal data structures. If we need to make something callable multiple times - we should export it as a function, like we did with `sayHi` above. +이때 기억해야 할 원칙이 있습니다. 최상위 레벨 모듈 코드는 초기화나 모듈 내부에서 사용하는 데이터 구조를 생성하는 용도로 사용해야 합니다. 여러 번 호출해야 하는 기능이 필요하다면 앞서 sayHi에서 살펴본 것처럼 함수로 내보내야 합니다. -Now, let's consider a deeper example. ->>>>>>> upstream/master +이제 좀 더 어려운 예시를 살펴보겠습니다. 객체를 내보내는 모듈을 만들어봅시다. @@ -222,7 +164,6 @@ import {admin} from './admin.js'; alert(admin.name); // Pete *!* -<<<<<<< HEAD // 1.js와 2.js 모두 같은 객체를 가져오므로 // 1.js에서 객체에 가한 조작을 2.js에서도 확인할 수 있습니다. */!* @@ -233,34 +174,12 @@ alert(admin.name); // Pete 이런 특징을 이용하면 모듈 *설정(configuration)*을 쉽게 할 수 있습니다. 최초로 실행되는 모듈의 객체 프로퍼티를 원하는 대로 설정하면 다른 모듈에서 이 설정을 그대로 사용할 수 있기 때문이죠. 예시를 통해 이에 대해 자세히 알아봅시다. 아래 `admin.js` 모듈은 어떤 특정한 기능을 제공해주는데, 이 기능을 사용하려면 외부에서 `admin` 객체와 관련된 인증 정보를 받아와야 한다고 가정해봅시다. -======= -// Both 1.js and 2.js reference the same admin object -// Changes made in 1.js are visible in 2.js -*/!* -``` - -As you can see, when `1.js` changes the `name` property in the imported `admin`, then `2.js` can see the new `admin.name`. - -That's exactly because the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the `admin` object, other importers will see that. - -**Such behavior is actually very convenient, because it allows us to *configure* modules.** - -In other words, a module can provide a generic functionality that needs a setup. E.g. authentication needs credentials. Then it can export a configuration object expecting the outer code to assign to it. - -Here's the classical pattern: -1. A module exports some means of configuration, e.g. a configuration object. -2. On the first import we initialize it, write to its properties. The top-level application script may do that. -3. Further imports use the module. - -For instance, the `admin.js` module may provide certain functionality (e.g. authentication), but expect the credentials to come into the `config` object from outside: ->>>>>>> upstream/master ```js // 📁 admin.js export let config = { }; export function sayHi() { -<<<<<<< HEAD alert(`${admin.name}님, 안녕하세요!`); } ``` @@ -280,29 +199,6 @@ admin.name = "보라"; import {admin, sayHi} from './admin.js'; alert(admin.name); // *!*보라*/!* -======= - alert(`Ready to serve, ${config.user}!`); -} -``` - -Here, `admin.js` exports the `config` object (initially empty, but may have default properties too). - -Then in `init.js`, the first script of our app, we import `config` from it and set `config.user`: - -```js -// 📁 init.js -import {config} from './admin.js'; -config.user = "Pete"; -``` - -...Now the module `admin.js` is configured. - -Further importers can call it, and it correctly shows the current user: - -```js -// 📁 another.js -import {sayHi} from './admin.js'; ->>>>>>> upstream/master sayHi(); // *!*보라*/!*님, 안녕하세요! ``` @@ -312,20 +208,11 @@ sayHi(); // *!*보라*/!*님, 안녕하세요! `import.meta` 객체는 현재 모듈에 대한 정보를 제공해줍니다. -<<<<<<< HEAD 호스트 환경에 따라 제공하는 정보의 내용은 다른데, 브라우저 환경에선 스크립트의 URL 정보를 얻을 수 있습니다. HTML 안에 있는 모듈이라면, 현재 실행 중인 웹페이지의 URL 정보를 얻을 수 있습니다. ```html run height=0 ``` @@ -351,11 +238,7 @@ Its content depends on the environment. In the browser, it contains the URL of t 브라우저 환경에서 `type="module"`이 붙은 스크립트가 일반 스크립트와 어떤 점이 다른지 알아봅시다. -<<<<<<< HEAD 자바스크립트 초심자나 브라우저 환경에서 자바스크립트를 사용하지 않고 있다면 이 내용은 넘어가셔도 됩니다. -======= -You may want to skip this section for now if you're reading for the first time, or if you don't use JavaScript in a browser. ->>>>>>> upstream/master ### 지연 실행 @@ -366,11 +249,7 @@ You may want to skip this section for now if you're reading for the first time, - 모듈 스크립트는 HTML 문서가 완전히 준비될 때까지 대기 상태에 있다가 HTML 문서가 완전히 만들어진 이후에 실행됩니다. 모듈의 크기가 아주 작아서 HTML보다 빨리 불러온 경우에도 말이죠. - 스크립트의 상대적 순서가 유지됩니다. 문서상 위쪽의 스크립트부터 차례로 실행됩니다. -<<<<<<< HEAD 이런 특징 때문에 모듈 스크립트는 항상 완전한 HTML 페이지를 '볼 수' 있고 문서 내 요소에도 접근할 수 있습니다. -======= -As a side effect, module scripts always "see" the fully loaded HTML-page, including HTML elements below them. ->>>>>>> upstream/master 예시: @@ -386,11 +265,7 @@ As a side effect, module scripts always "see" the fully loaded HTML-page, includ diff --git a/1-js/13-modules/02-import-export/article.md b/1-js/13-modules/02-import-export/article.md index 047003bf90..22328364c2 100644 --- a/1-js/13-modules/02-import-export/article.md +++ b/1-js/13-modules/02-import-export/article.md @@ -93,7 +93,6 @@ say.sayBye('John'); 이렇게 하는 데는 몇 가지 이유가 있습니다. -<<<<<<< HEAD 1. [웹팩(webpack)](http://webpack.github.io)과 같은 모던 빌드 툴은 로딩 속도를 높이기 위해 모듈들을 한데 모으는 번들링과 최적화를 수행합니다. 이 과정에서 사용하지 않는 리소스가 삭제되기도 합니다. 아래와 같이 프로젝트에 서드파티 라이브러리인 `say.js`를 도입하였다 가정합시다. 이 라이브러리엔 수 많은 함수가 있습니다. @@ -113,16 +112,6 @@ say.sayBye('John'); 2. 어떤 걸 가지고 올지 명시하면 이름을 간결하게 써줄 수 있습니다. `say.sayHi()`보다 `sayHi()`가 더 간결하네요. 3. 어디서 어떤 게 쓰이는지 명확하기 때문에 코드 구조를 파악하기가 쉬워 리팩토링이나 유지보수에 도움이 됩니다. -======= -1. Explicitly listing what to import gives shorter names: `sayHi()` instead of `say.sayHi()`. -2. Explicit list of imports gives better overview of the code structure: what is used and where. It makes code support and refactoring easier. - -```smart header="Don't be afraid to import too much" -Modern build tools, such as [webpack](https://webpack.js.org/) and others, bundle modules together and optimize them to speedup loading. They also remove unused imports. - -For instance, if you `import * as library` from a huge code library, and then use only few methods, then unused ones [will not be included](https://github.com/webpack/webpack/tree/main/examples/harmony-unused#examplejs) into the optimized bundle. -``` ->>>>>>> upstream/master ## import 'as' @@ -332,11 +321,7 @@ export {default as User} from './user.js'; // default export를 다시 내보내 다시 내보내기가 왜 필요한건지 의문이 드실 겁니다. 유스 케이스를 통해 다시 내보내기가 실무에서 언제 사용되는지 알아봅시다. -<<<<<<< HEAD NPM을 통해 외부에 공개할 '패키지(package)'를 만들고 있다고 가정합시다. 이 패키지는 수많은 모듈로 구성되어있는데, 몇몇 모듈은 외부에 공개할 기능을, 몇몇 모듈은 이러한 모듈을 도와주는 '헬퍼' 역할을 담당하고 있다고 합시다. -======= -Imagine, we're writing a "package": a folder with a lot of modules, with some of the functionality exported outside (tools like NPM allow us to publish and distribute such packages, but we don't have to use them), and many modules are just "helpers", for internal use in other package modules. ->>>>>>> upstream/master 패키지 구조는 아래와 같습니다. ``` @@ -352,27 +337,13 @@ auth/ ... ``` -<<<<<<< HEAD 진입점 역할을 하는 '주요 파일'인 `auth/index.js`을 통해 기능을 외부에 노출시키면 이 패키지를 사용하는 개발자들은 아래와 같은 코드로 해당 기능을 사용할 겁니다. -======= -We'd like to expose the package functionality via a single entry point. - -In other words, a person who would like to use our package, should import only from the "main file" `auth/index.js`. - -Like this: ->>>>>>> upstream/master ```js import {login, logout} from 'auth/index.js' ``` -<<<<<<< HEAD 이때 우리가 만든 패키지를 사용하는 외부 개발자가 패키지 안의 파일들을 뒤져 내부 구조를 건드리게 하면 안 됩니다. 그러려면 공개할 것만 `auth/index.js`에 넣어 내보내기 하고 나머지는 숨기는 게 좋겠죠. -======= -The "main file", `auth/index.js` exports all the functionality that we'd like to provide in our package. - -The idea is that outsiders, other programmers who use our package, should not meddle with its internal structure, search for files inside our package folder. We export only what's necessary in `auth/index.js` and keep the rest hidden from prying eyes. ->>>>>>> upstream/master 이때 내보낼 기능을 패키지 전반에 분산하여 구현한 후, `auth/index.js`에서 이 기능들을 가져오고 이를 다시 내보내면 원하는 바를 어느 정도 달성할 수 있습니다. @@ -395,36 +366,19 @@ export {User}; ```js // 📁 auth/index.js -<<<<<<< HEAD // login과 logout을 가지고 온 후 바로 내보냅니다. export {login, logout} from './helpers.js'; // User 가져온 후 바로 내보냅니다. -======= -// re-export login/logout -export {login, logout} from './helpers.js'; - -// re-export the default export as User ->>>>>>> upstream/master export {default as User} from './user.js'; ... ``` -<<<<<<< HEAD ### default export 다시 내보내기 -======= -The notable difference of `export ... from` compared to `import/export` is that re-exported modules aren't available in the current file. So inside the above example of `auth/index.js` we can't use re-exported `login/logout` functions. - -### Re-exporting the default export ->>>>>>> upstream/master 기본 내보내기를 다시 내보낼 때는 주의해야 할 점들이 있습니다. -<<<<<<< HEAD `user.js` 내의 클래스 `User`를 다시 내보내기 한다고 가정해 봅시다. -======= -Let's say we have `user.js` with the `export default class User` and would like to re-export it: ->>>>>>> upstream/master ```js // 📁 user.js @@ -433,35 +387,19 @@ export default class User { } ``` -<<<<<<< HEAD 1. `User`를 `export User from './user.js'`로 다시 내보내기 할 때 문법 에러가 발생합니다. 어디가 잘못된 걸까요? default export를 다시 내보내려면 위 예시처럼 `export {default as User}`를 사용해야 합니다. -======= -We can come across two problems with it: - -1. `export User from './user.js'` won't work. That would lead to a syntax error. - - To re-export the default export, we have to write `export {default as User}`, as in the example above. ->>>>>>> upstream/master 2. `export * from './user.js'`를 사용해 모든 걸 한 번에 다시 내보내면 default export는 무시되고, named export만 다시 내보내집니다. -<<<<<<< HEAD 두 가지를 동시에 다시 내보내고 싶다면 두 문을 동시에 사용해야 합니다. -======= - If we'd like to re-export both named and default exports, then two statements are needed: ->>>>>>> upstream/master ```js export * from './user.js'; // named export를 다시 내보내기 export {default} from './user.js'; // default export를 다시 내보내기 ``` -<<<<<<< HEAD default export를 다시 내보낼 땐 이런 특이한 상황도 인지하고 있다가 처리해줘야 하므로 몇몇 개발자들은 default export를 다시 내보내는것을 선호하지 않습니다. -======= -Such oddities of re-exporting a default export are one of the reasons why some developers don't like default exports and prefer named ones. ->>>>>>> upstream/master ## 요약 @@ -480,7 +418,6 @@ Such oddities of re-exporting a default export are one of the reasons why some d 가져오기 타입 역시 정리해 봅시다. -<<<<<<< HEAD - named export 가져오기: - `import {x [as y], ...} from "mod"` - default export 가져오기: @@ -490,17 +427,6 @@ Such oddities of re-exporting a default export are one of the reasons why some d - `import * as obj from "mod"` - 모듈을 가져오긴 하지만(코드는 실행됨), 변수에 할당하지 않기: - `import "mod"` -======= -- Importing named exports: - - `import {x [as y], ...} from "module"` -- Importing the default export: - - `import x from "module"` - - `import {default as x} from "module"` -- Import all: - - `import * as obj from "module"` -- Import the module (its code runs), but do not assign any of its exports to variables: - - `import "module"` ->>>>>>> upstream/master `import/export` 문은 스크립트의 맨 위나 맨 아래에 올 수 있는데 이 둘엔 차이가 없습니다.