<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Björn Tegelund on Medium]]></title>
        <description><![CDATA[Stories by Björn Tegelund on Medium]]></description>
        <link>https://medium.com/@bjrnt?source=rss-cff697bd1635------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OQUmSBc_xWup2PGNPf_2gw.jpeg</url>
            <title>Stories by Björn Tegelund on Medium</title>
            <link>https://medium.com/@bjrnt?source=rss-cff697bd1635------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:42:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bjrnt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Yoga in Isolation: A Reflection on my First 10 Days]]></title>
            <link>https://medium.com/@bjrnt/yoga-in-isolation-a-reflection-on-my-first-10-days-6c33068e828d?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c33068e828d</guid>
            <category><![CDATA[quarantine]]></category>
            <category><![CDATA[yoga]]></category>
            <category><![CDATA[exercise]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 22:04:16 GMT</pubDate>
            <atom:updated>2020-07-25T22:04:16.791Z</atom:updated>
            <content:encoded><![CDATA[<p>After moving to Vancouver for work, I was stuck self-isolating in a hotel for 14 days. As a very active person, I needed a physical outlet, and decided to give yoga a try by doing an hour every day. Here’s a reflection after my first 10 days:</p><h4>Getting started: a low barrier of entry and easy to turn into a habit</h4><p>When starting something new, we typically don’t want to spend a lot of time or money just to get started. Yoga is excellent here as it requires only a mat (or, generally, just a surface you could comfortably kneel on — hotel carpet flooring in my case), and some comfy clothes.</p><p>Sticking with an exercise routine can be difficult if you’re required to do a lot of planning before sessions (e.g. how many sets of what exercise, finding new routes for runs, and so on), and here yoga again really doesn’t ask anything of you. A workout can be done as simply as turning on a YouTube video and following along, and the ones targeted at beginners won’t even make you break a sweat. If you have an app with adjustable difficulty, I reckon this is ideally all you’d ever need. This made it super easy for me to keep coming back.</p><p>One downside that I noticed pretty fast is that yoga is riddled in absolute difficulty barriers. That is, most poses slightly above your level will be impossible to pull off until you have made the necessary flexibility/strength/balance gains. Contrasting this with running where there aren’t really any hard barriers (you can just run slower/shorter if it’s too hard), this is a slight negative as mastering new poses will take a lot of dedication that is hard to muster in the beginning.</p><h4>Keeping at it: a good mix of short-, medium-, and long-term rewards</h4><p>It’s important to consistently feel rewarded for your practice to keep your motivation high and, so far, yoga has had a good mix of rewards to keep making me want to come back.</p><p>Short-term rewards are frequent in the beginning as you recognize the names of poses or manage to get in a smooth transition from one pose to another. After a few hours of solid practice, these did get somewhat rarer but I still feel really happy whenever I manage to pull off a one-legged balance without having to steady myself.</p><p>The largest medium-term rewards I’ve noticed was pain-relief in my lower back and hips. I’ve done a lot of quad-heavy endurance sports and very inconsistent when it comes to mobility work and recovery. This has lead to tight hip flexors along with weak hamstrings and glutes. Yoga is fun enough for me to keep wanting to do it, which alleviated discomfort and pain in just a few days (!) of practice. This has by far been the biggest win for me.</p><p>In the long term, I expect to see improvement both in terms of flexibility and balance, and I hope these will carry over into other sports too. I started noticing improved flexibility in my hamstrings after just a few days, and I hope this will keep going.</p><h4>Getting rid of preconceptions</h4><p>Before starting my practice, I had a lot of preconceptions about yoga; namely that it contained a lot of spiritual mumbo-jumbo that doesn’t really contribute to it as a physical activity and that it is mainly for people who want to look like they’re active but actually hate exercising. I think I was mistaken on both of these points.</p><p>The spiritual stuff can easily be skipped if that’s not your thing. If you browse through yoga YouTube channels and apps, you’ll be able to find something that suits your personal style. I decided to go with the <a href="https://www.downdogapp.com/">Down Dog app</a> as it let me get right into it. No montages of people meditating, smiling, and drinking tea for me, thanks!</p><p>In terms of being a legitimate form of exercise, yoga will make you sweat and will burn a fair amount of calories. During my sessions so far, I’ve averaged out at around 270 calories/hour (according to my Apple Watch), which lands it at about a third of the calories I’d burn during a run for the same amount of time. Not amazing, but it sure beats being watching Netflix!</p><h4>In conclusion</h4><p>I’d call my 10 day yoga experiment very successful and I look forward to continuing my practice post-quarantine!</p><p>If you’re interested in trying yoga out, I recommend you download the Down Dog app, put on some comfy clothes, and simply give it a go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c33068e828d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exercising Startup Stock Options in South Korea]]></title>
            <link>https://medium.com/@bjrnt/exercising-startup-stock-options-in-south-korea-de8400b4c06b?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8400b4c06b</guid>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Sun, 03 May 2020 11:04:17 GMT</pubDate>
            <atom:updated>2020-05-03T11:04:17.120Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently went through the experience of exercising stock options for a startup I worked for and thought I’d share my experience in the hope that it might help others. While the actual exercising of the options themselves will vary depending on the specifics of your stock option contract, there are some commonalities that could be helpful to go over.</p><p><em>Quick disclaimer: I am merely sharing my experience and what I learnt in this post and you will want to double-check the specifics with a tax accountant/lawyer. This post may contain errors.</em></p><p>The most important thing to take into account is that <strong>you are required by law to pay capital gains taxes when you exercise the options</strong> and later again if/when you liquidate the resulting stock. Depending on the value of your grant, the tax burden can be very large. Your company will most likely leave it to you to figure this out which can be daunting at first.</p><p>To give an overall idea of how your taxes will be calculated, here are some of the major variables that go into it:</p><ul><li>Your capital gains will be classified as 근로소득 (labor income) if you are still employed by the company and 기타소득 (other income) if you are not. This may have tax implications based on whether you are currently residing in South Korea or not. There are also typically more tax deductibles within the labor income category. If you are a foreign citizen residing within the country, the classification does not seem to make much of a difference.</li><li>It does not matter whether the company that granted you the options is a Korean or a foreign company — from a tax perspective they are treated the same way. Note that if it is a foreign company, exchange rates come into play.</li><li>To calculate the taxes, the stock options have to be valued, i.e. a 시가 (market value) needs to be established for them. This is typically based on previous transactions of the company’s stock or, in the case where it lacks such transactions, a heuristic based on the company’s finances can be used. Taxes are typically much lower <em>if</em> you can go with the second option. Your company will be able to tell you what the market value of their stock is.</li><li>Income taxes each year are bracketed, where your labor income and other income are added together to produce your total income. This number is used to place you in one of the tax brackets as defined below for 2020:</li></ul><pre>+-------------------+-------------------+----------+<br>| Lower Bound (KRW) | Upper Bound (KRW) | Tax Rate |<br>+===================+===================+==========+<br>|                 0 |        12,000,000 | 6%       |<br>|        12,000,000 |        46,000,000 | 15%      |<br>|        46,000,000 |        88,000,000 | 24%      |<br>|        88,000,000 |       150,000,000 | 35%      |<br>|       150,000,000 |       300,000,000 | 38%      |<br>|       300,000,000 |       500,000,000 | 40%      |<br>|       500,000,000 |                 - | 42%      |<br>+-------------------+-------------------+----------+</pre><ul><li>To figure out what your current labor and other income is, you can ask your company for a 원천징수영수증 (withholding income tax statement), which details all of the compensation they have paid out to you during the year as well as how much of that has already gone to taxes. To figure out which bracket you will end up in, extrapolate from your currently paid taxes and income and add the capital gains from the exercising of the stock options to that. Note that if you have secondary sources of income outside of your main employment or have switched jobs within the last year, these factors also need to be taken into account.</li><li>You will also have to pay an extra 10% of the <em>taxed</em> amount as 지방소득세 (provincial income tax). Essentially, you multiple your tax rate from the above table by 1.1.</li></ul><p>As you can probably tell, tax calculations are complex, but the whole process isn’t that much work if you take some time to prepare. Here are some of the things I wish I had known before starting all this:</p><ul><li>Contact a 세무사 (tax accountant), as they will be able to help you with calculating, reporting, and paying your taxes. They will also be able to offer advice for your particular situation. When you reach out, be sure to include details about what it is you are planning to do, as most tax accountants have specializations and not every one may be able to assist you in your specific case. Expect to pay up toward a couple hundred thousand won for this. To find one, I simply searched for 세무사 on Naver Maps and reached out to a few nearby.</li><li>Your tax bracket is calculated on a yearly basis so if you can spread out the exercising of your options over multiple years, you can greatly reduce the tax burden by staying in lower brackets. Note that doing this also comes with additional risk if you are not sure whether you will be able to liquidate the stock later or not.</li><li>The income tax rate is fixed for non-residents, so if you can time it in such a way that you won’t be classified as a resident at the time of exercise (the conditions for this are complex and not as simple as “having left the country”), that may be worth looking into.</li><li>Your boss and coworkers may not have/share accurate information about how these things work. They are acting in their own best interests, and you should do the same. Again, a tax accountant can help you with this.</li></ul><p>I hope the above can give some rough ideas about things you might want to consider and look into further before making a decision regarding your own stock options, <em>especially</em> if you aren’t able to liquidate immediately upon exercise.</p><p>Feel free to reach out if you want to know more about how I went about things. I would also love it if you’d let me know about any errors I might’ve made in the post so that I can correct them for future readers!</p><p>Best of luck! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8400b4c06b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On-Demand VPN using Google Cloud]]></title>
            <link>https://medium.com/@bjrnt/on-demand-vpn-using-google-cloud-8fd1f813be23?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd1f813be23</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 11:31:45 GMT</pubDate>
            <atom:updated>2020-04-23T03:33:36.479Z</atom:updated>
            <content:encoded><![CDATA[<p>Given the amount of geo-restricted content on the internet, it can be nice to be able to reach for a VPN on demand to get around this. Paying for a subscription to a VPN service is one way to do this but if you, like me, find your VPN needs to be very sporadic, then a subscription model probably doesn’t feel like the right way to go.</p><p>I am going to share my solution to this problem on MacOS, which is to use a SOCKS proxy to a cloud VM. Instead of paying a monthly subscription, this means that you only pay for as much as you use. For some light video streaming, this will most likely be below $1/month.</p><p>To get started, make sure that you have a Google Cloud account with valid billing info and a project set up. If not, you can make one <a href="https://cloud.google.com/">here</a>.</p><p>After that install the <a href="https://cloud.google.com/sdk/docs/quickstart-mac-os-x">Google Cloud SDK</a> and follow their guide to get it initialized. Make sure you select the compute engine zone that corresponds to the country you’d like to have your VM in. You can find a list of the compute engine zones and their locations <a href="https://cloud.google.com/compute/docs/regions-zones/regions-zones#available">here</a>.</p><p>What we now want to do can be summarized in the following steps:</p><ol><li>Create a micro VM</li><li>Set up a SSH tunnel to it</li><li>Tell your computer to use this tunnel as a SOCKS proxy</li><li>Use the tunnel</li><li>Tear everything down</li></ol><p>Using the SDK and some native terminal commands, we can turn all of this into a handy little script:</p><pre>#!/usr/bin/env bash</pre><pre>trap &#39; &#39; INT</pre><pre>echo &quot;Initializing...&quot;</pre><pre># Start the VPN instance<br>gcloud compute instances create   tmp-vpn   --machine-type f1-micro</pre><pre># Set up the SSH tunnel and activate proxy<br># Sleep a bit first to make sure that the SSH connection is up before the proxy is enabled<br>(sleep 5; networksetup -setsocksfirewallproxy Wi-Fi localhost 4242) &amp; gcloud compute ssh tmp-vpn   --strict-host-key-checking=no   --command=&quot;echo &quot;VPN activated. Press Ctrl+C to exit.&quot; &amp;&amp; tail -f /dev/null&quot;   -- -D 4242</pre><pre>echo &quot;Cleaning up...&quot;</pre><pre># Deactivate SOCKS proxy<br>networksetup -setsocksfirewallproxystate Wi-Fi off</pre><pre># Delete the VPN instance<br>gcloud compute instances delete   tmp-vpn</pre><pre>echo &quot;Cleanup complete.&quot;</pre><p>As you can see, there isn’t really much to it so applying a similar approach to another cloud provider should be pretty straight forward. While it does take a little bit of time to set up the connection and later tear down the VM, we now have ourselves a very cost-effective on-demand VPN.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd1f813be23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting a Master’s Degree in Korea]]></title>
            <link>https://medium.com/@bjrnt/getting-a-masters-degree-in-korea-e9b7e65e026b?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9b7e65e026b</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[kaist]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[korea]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 11:30:22 GMT</pubDate>
            <atom:updated>2020-01-08T08:19:04.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpZ27gTEKQqrWHjDylRZlw.jpeg" /></figure><p>(Originally written in July, 2017)</p><p>In this post I would like to share my experience of getting a master’s in computer science at KAIST in Daejeon and address some of the main concerns people might have when deciding whether they should do a masters in Korea or not.</p><h3>Background</h3><p>Before getting into the main body of this post, I would like to briefly mention my background as well as the process that led to my graduation. I mention this as all of the comparisons I draw are based on my own personal experience and may be very different depending on where you are coming from.</p><p>I was born and raised in Sweden and did my undergrad (also in computer science) at The Royal Institute of Science and Technology (KTH) in Stockholm. Before starting my masters in Korea, I was originally enrolled in a combined 5 year undergrad + masters program at my university in Sweden. For the first year of my masters, i.e. my 4th year, I applied to go as an exchange student to KAIST but due to the large number of applicants, I was only allowed to go for one semester. This decision was not optimal for me, as the reason I wanted to go to Korea in the first place was to learn a new language and explore a new culture.</p><p>However, once I arrived in Korea, I set out to find a way to be able to stay longer than one semester. Fortunately, I had been assigned an advisor once I arrived and after a couple of months doing research in his lab, my advisor suggested that I drop out of the program I was enrolled in in Sweden and do my entire masters at KAIST instead. Since this was exactly what I had been hoping for, I gladly accepted his offer. Since I missed the application period, I had to spent one semester as a research assistant before enrolling, and 3 semesters later I graduated from KAIST. I would now like to go into more details about the topics I expect would be of interest to readers.</p><h3>Scholarships</h3><p>I received a full scholarship from the Korean government which covered all educational costs and provided a small stipend. It did not seem that difficult to get a scholarship as there are not that many international students. If you cannot get a scholarship, expect each semester to cost you a couple of thousands of dollars.</p><h3>Education</h3><p>I had expected the courses at KAIST to be of very high quality, given that the university’s ranking is quite a bit higher than KTH’s. However, this was not quite the case. While KTH is a very education-oriented university aiming to produce engineers with a lot of practical knowledge, KAIST is much more geared towards research. As such, course quality suffered quite a bit, and it was not uncommon for professors to come poorly prepared to classes or even cancel several classes to attend a conference.</p><p>The course difficulty was also much lower than in Sweden. I think this mainly had to do with the way students are graded. I was used to absolute performance evaluation, meaning that all criteria for grades are set in advance and it is up to each student to fulfill the criteria to get the grade they want. Schools in Korea employ a relative performance evaluation scheme, meaning that your grade is determined based on your performance relative to your peers. It is also worth mentioning that you get points for attendance, so showing up to classes has an immediate effect on your grade.</p><p>KAIST is pretty unique in that all classes are officially supposed to be in English. Depending on the portion of classes given in English, you might have a hard time finding classes that fit your interests or requirements for graduation. Worth mentioning is that although a class is advertised as being in English, this is not guaranteed. Some professors know that many local students have a hard time following classes taught in English and opt to instead lecture in Korean. You will probably want to double-check what language the course will be held in.</p><p>Most courses are designed to follow a textbook, and if you do the course readings and attend the classes, you will have no problem passing. Even with relatively poor performance, you will probably be able to scape together a C.</p><h3>Research</h3><p>Most (engineering) masters programs in Korea require you to join a lab for the time you are enrolled. Students coming from abroad usually do not have that much choice in which lab to join. I recommend that you talk in advance to the professor whose lab you would like to join, so that they can make sure you are assigned to them. I was very lucky in randomly getting assigned to the lab I liked the most, but as your lab will greatly affect your experience at the school it is best to try to remove any randomness from this process.</p><p>Your advisor is going to make or break your experience at graduate school. I have heard of labs where the professor sits in front of the lab at 8 am every day to check attendance, where students are not allowed to leave before the professor does at 11 pm. My advisor gave students are lot of freedom as long as we did our assigned work and was almost always available in his office if we wanted to talk. The international students I personally knew at KAIST all seemed to be in pretty decent labs.</p><p>In general, younger professors are going to be more ambitious and demanding (but the work itself might be more exciting), and professors who already have tenure are likely to be more relaxed. It is up to you to find a good match depending on your own goals.</p><p>At your lab, you will get assigned a desk and they will have a computer and other equipment for you to use there. During your time at the lab, you are expected to dig into the research topics the lab is focused on, and eventually find a related topic for your thesis. Depending on your university and professor, there may be certain conditions your research must fulfill before you graduate. In my lab’s case, we had to get accepted into a top-tier conference in order to graduate. If you are not passionate about your research or have a poor work ethic, now might be the time to change that.</p><p>In addition to doing your own research, you will also be working on the lab’s research projects. The way these projects usually work is that you get a grant either from the government, a local company, or some other organization. In return for the grant money, your lab will be required to produce some kind of research output. If your professor is good at their job, these projects will be very well-aligned with your lab members’ research interests and will not incur that much overhead on whatever research you would be doing anyway. These projects will also provide you with a salary. Again, depending on how good your professor is at securing grants, this might be anything from approximately $300/month to $1500/month.</p><p>Depending on your university and lab, you may or may not have winter and summer breaks. Most graduate students I knew were expected to keep doing research during breaks. I was able to travel home for 2 weeks per year and take a couple of days off in addition to this, but any extensive traveling is going to be difficult. Do not expect that you will be able to visit all of Asia during your time at graduate school (learnt this the hard way). Your best bet to visit other countries is going to be by attending conferences.</p><h3>Quality of Life</h3><p>I enjoyed my life at KAIST a lot. There were no large differences in quality of life from Sweden. One thing I appreciated a lot when I first got there was how cheap it was to eat out. During my first year at KAIST, I did not do any cooking at all and had all my meals at restaurants in and around the campus. The vast majority of food is either going to be Korean or a version of the foods you are used to but adjusted for the Korean palette. I like Korean food and did not have any problem at all finding things to eat. If you have dietary restrictions due to health or religion, this can obviously make things difficult for you but the school does try to provide at least <em>some</em> options.</p><p>There is usually at least one cluster of cheap bars around every campus, which is great for when you need to get rid of some grad school-induced stress. You will almost certainly get dragged to karaoke by your Korean friends after drinking. Don’t worry though; it is much more fun than you think it will be, especially if you decide to try to sing Korean songs.</p><p>Depending on where in the country you are, there will most likely be some mountains around, which is amazing if you are into hiking. All cities are also very well-connected with affordable buses and slightly less affordable trains. Going on trips to nearby cities is a really nice way to spend your weekends. I think I went to Seoul at least twice per month, and a round-trip cost me about $50.</p><p>If dormitory life is not for you, i.e. you randomly got assigned a less-than-agreeable roommate, there is usually a decent amount of affordable housing around the campus. I rented a pretty nice place for about $300/month right outside the KAIST campus. Housing will be quite a lot more expensive if you live in Seoul.</p><p>If you are low on cash, you might consider getting a part-time job. This may however be very difficult depending on what type of visa you have. For most student visas, you will not be allowed to work in cafes or bars, and you will most definitely not be allowed to <em>legally</em> work as a private English teacher. Your best bet to get some extra income is probably going to be working as a TA.</p><p>I was a TA for an introductory course to computer science for non-majors for one year. The professor trusted me enough to let me make my own curriculum for the labs. He only asked that the students do some kind of programming project related to their majors by the end of the semester. This was honestly one of my best memories from KAIST. I had a great time teaching and the students’ projects were amazing. I was also a TA for a scientific English writing course for one year which was also great. Depending on the class, you can get paid anything from 500,000원 per semester to 500,000원 per month. Some schools also work by discounting your tuition costs if you TA or simply require you to TA a certain amount of courses to graduate.</p><p>The combined income from working in the lab and doing some TA work was enough for me to be able to live comfortably and not really care too much about money. This included living outside of the campus, going to Seoul a couple of times per month, and the occasional big spend (new phone, tablet, etc.).</p><h3>In conclusion</h3><p>Even if I was able to go back in time and change my decision, I would without hesitation make the exact same choice again. Every decision is obviously going to have its tradeoffs; I traded slightly lower quality education for more research experience, and the familiar and safe culture I had grown up in for a completely new and strange environment on the other side of the world.</p><p>Living abroad is an eye-opening experience that I whole-heartedly recommend, and Korea is a really cool place to visit as it’s just so <em>different</em>. I was the only western student to enroll as a full-time student my first semester, which only made things more interesting to me. If you are bored with your everyday life and you love challenges, consider giving a masters in Korea a try!</p><p>As a last side note, I’m now going on 4 years in Korea, and I enjoy my life here very much.</p><p>Thank you for reading all the way to the end, and I hope this post was helpful to you. Feel free to reach out with questions or feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9b7e65e026b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Codemod를 이용한 코드 변환]]></title>
            <link>https://medium.com/@bjrnt/codemod%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%BD%94%EB%93%9C-%EB%B3%80%ED%99%98-bf04e894f3f1?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf04e894f3f1</guid>
            <category><![CDATA[tumblbug]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[codemod]]></category>
            <category><![CDATA[jscodeshift]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Thu, 23 Mar 2017 01:15:06 GMT</pubDate>
            <atom:updated>2017-03-23T01:15:06.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VprKeElpPObBdzu8cB5Gpw.jpeg" /><figcaption>이 거위들은 codemod가 migration에 많은 도움이 된다는 것을 알고 있습니다. <a href="https://unsplash.com/@kris_ricepees">Gary Bendig</a>의 사진.</figcaption></figure><p>소프트웨어 엔지니어로서 저희는 코드베이스의 많은 파일들에 규정화된 변환을 적용해야할 때가 있습니다. 이는 저희가 쓰는 API가 변화하거나 라이브러리가 더 이상 유지보수가 되지 않거나 프로젝트 전반에 걸쳐 일관된 코드 스타일을 적용하는 경우일 수 있습니다.</p><p>이런 대규모의 코드 변환을 위해 경험이 많지 않은 팀은 다음의 두가지 방법을 택합니다.</p><ol><li>변환을 적용하기에 필요한 도구들이 없어 나중에 하기로 미루거나 코드를 변환하지 않으려 합니다. 이는 라이브러리를 업그레이드하는 시도를 주저하게 만들고 기술 채무가 쌓이는 결과를 초래합니다.</li><li>어떤 엔지니어들은 에디터에서 변환시키려는 코드 패턴을 검색하여 바꾸려 합니다. 코드를 검색해서 바꾸는 방법으로 대량의 코드를 안정적으로 바꿀 수 있다면 좋겠지만, 이 방법은 거의 불가능에 가깝습니다. 쉽지 않기에 보통 엔지니어는 결국 변환 하나 하나를 수동으로 적용하게 됩니다. 바꾸려는 코드의 양에 따라 다르겠지만 이렇게 수동으로 코드를 바꾸는 것은 적어도 귀찮은 일이거나 대부분의 경우 현실적인 대안이 될 수 없습니다.</li></ol><h4>자바스크립트 Codemod</h4><p>텀블벅에서는 최근 많은 양의 코드를 변환하기 위해 codemod를 이용하기 시작했습니다. Codemod는 코드를 바꾸기 위해 디자인된 코드의 종류로 코드 변환을 자동화시킬 수 있는 도구입니다.</p><p>본격적으로 codemod에 대해 이야기하기에 앞서 codemod를 사용하는 것이 언어 내부 작동 원리, 코드 변환 규칙, 그리고 프로그래밍 언어의 마법들을 배워야할 것 같은 엄청난 일이라 생각되겠지만, 그렇게 힘든 작업이 아니라는 것을 말하고 싶습니다 :)</p><p>codemod를 알아보는 예제로 API 중단에 따라 연관된 코드를 변환시키기 위해 자바스크립트로 정말 간단한 codemod를 만들어 봅시다. 다음은 저희가 코드베이스에서 변환할 기존 코드와 목표로 하는 변환된 코드입니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc4ab9ff28be8ead67d35e7dc1a650fb/href">https://medium.com/media/bc4ab9ff28be8ead67d35e7dc1a650fb/href</a></iframe><p>본 작업을 위해 다음의 도구들이 필요합니다:</p><ul><li><a href="https://github.com/facebook/jscodeshift">JSCodeShift</a>: codemod를 적용하기 위한 도구.</li><li><a href="https://astexplorer.net/">AST 탐색기</a>: codemod를 테스트하고 AST 탐색을 위한 도구.</li><li><a href="https://github.com/benjamn/ast-types/tree/master/def">ast-type의 정의들</a>: 새로운 AST 노드를 만들기 위한 API.</li></ul><p>위의 gist를 AST 탐색기에 복사하고 오른쪽에 있는 AST 나무를 보면 다음의 사항들을 확인할 수 있습니다:</p><ul><li>MobX의 ImportDeclaration안에 ImportSpecifier를 map에서 ObservableMap으로 바꿔야 합니다.</li><li>map으로 되어 있는 CallExpression을 ObservableMap으로 된 NewExpression으로 변경해야 합니다.</li></ul><h4>Codemod 만들기</h4><p>AST 탐색기의 “transform” 메뉴 밑에 “jscodeshift”를 선택하여 codemod 생성에 필요한 화면으로 갑니다. 이 화면에는 저희가 만들 codemod의 결과값 또한 확인할 수 있습니다. <a href="https://github.com/facebook/jscodeshift#transform-module">JSCodeShift의 문서</a>와 <a href="https://github.com/facebook/jscodeshift#example-codemods">몇가지 예제</a>를 보면 codemod를 쓰기 위한 준비는 다 되었습니다.</p><p>처음엔 JSCodeShift에서 새로운 AST 노드를 만드는 과정이 헷갈릴 수 있습니다. 상위에 ast-type의 정의들에 대한 링크로 들어가서 core.js를 확인하면 NewExpression은 두가지 매개변수를 받고 있는 걸 확인할 수 있습니다: callee와 arguments. callee는 코드 변환에 영향을 받지 않고 똑같이 Identifier입니다. 참고로 JSCodeShift는 노드를 탐색할때 첫글자를 NewExpression같이 대문자로 쓰고, 노드를 만들때 newExpression(callee, arguments)와 같이 소문자로 쓰는 규칙이 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3c78517b13fe6d0c4cd659b8ed5a30/href">https://medium.com/media/2c3c78517b13fe6d0c4cd659b8ed5a30/href</a></iframe><p>완성된 codemod입니다. 위 코드를 AST 탐색기에 붙여 넣으면, 기존 코드를 저희가 의도한대로 변환되는 것을 확인할 수 있습니다.</p><p>코드를 변환시키기 위해 사용하시는 패키지 매니저를 통해 JSCodeShift를 설치하고 변환 코드와 변환을 적용할 소스 파일을 다음과 같이 설정하면 됩니다.</p><pre>jscodeshift -t ./transform-mobx-map.js ./my-javascripts</pre><p>커멘드 라인 옵션을 비롯한 상세한 정보는 <a href="https://github.com/facebook/jscodeshift#usage-cli">문서</a>를 참고해주세요.</p><h4>결론</h4><p>이제까지 새로운 도구를 배우고, 간단히 코드를 작성했으며 중단된 API를 요청하는 코드를 변환했습니다. 이 정도면 꽤 멋지지 않나요?</p><p>JSCodeShift와 비슷한 도구들은 여러 언어로 제공되고 있으며 배우기도 어렵지 않습니다. 심지어 <a href="https://github.com/jhgg/js-transforms/blob/master/pure-to-composite-component.js">함수형 React 컴포넌트를 composite으로 변환</a>하는 것도 30줄의 코드로 가능합니다.</p><p>무엇보다 이러한 도구는 팀이 API를 변경하고 라이브러리들을 업그레이드하는데 도움을 줍니다. 저는 이것이 이런 도구를 사용하는 진정한 가치라고 믿습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf04e894f3f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Code Using Codemods]]></title>
            <link>https://medium.com/@bjrnt/migrating-code-using-codemods-808e2e29e5f2?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/808e2e29e5f2</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Wed, 22 Mar 2017 05:28:49 GMT</pubDate>
            <atom:updated>2020-04-23T03:28:14.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-MIGsJ0yu40b3NhzlWwpQ.jpeg" /><figcaption>These geese know how helpful codemods can be for migrations. Photo by <a href="https://unsplash.com/@kris_ricepees">Gary Bendig</a>.</figcaption></figure><p>As software engineers, we often have to apply a set of well-defined changes to a large number of files in our codebase. These can be due to changes in APIs we use, deprecations in libraries, or simply to enforce a consistent code style across the project.</p><p>Whenever a need for large-scale changes arises, it is easy to default to one of two approaches:</p><ol><li>The changes get blocked or postponed to a later date, typically never, as the tooling necessary to perform these changes just isn’t there. This ends up adding to technical debt.</li><li>Some unfortunate engineer fires up their editor and does a find-all search for the patterns of code they want to change. Being able to use search-and-replace to reliably make these changes would be great, but that is rarely possible, so the engineer is forced to manually apply the changes one-by-one. Depending on the number of changes required, this is at the very least impractical and can end up sucking up a lot of engineers’ time.</li></ol><h4>JavaScript Codemods</h4><p>At Tumblbug, we’ve recently embraced using codemods to handle these kinds of changes. Codemods are pieces of code designed to implement changes across a codebase — a find-and-replace with built-in logic! This allows engineers to apply changes across huge codebases in exchange for a small upfront investment of time.</p><p>Before getting started with codemods, it can seem like a daunting task where you expect that you’ll have to learn a bunch of language internals and code parsing rules and other kinds of programming language magic, but let me assure you that is not the case.</p><p>To showcase this, we’re going to go through the creation of a super simple codemod for (and in) JavaScript to handle a deprecation in an API. The following are the changes we’re going to look to apply across our codebase:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda5804be6af8d8bd97517f04c4a4f90/href">https://medium.com/media/bda5804be6af8d8bd97517f04c4a4f90/href</a></iframe><p>To do this, we’re going to be using the following tools:</p><ul><li><a href="https://github.com/facebook/jscodeshift">JSCodeShift</a> to apply our codemod to our codebase</li><li><a href="https://astexplorer.net/">AST Explorer</a> to test our codemod out and look at which parts of the AST we need to change</li><li><a href="https://github.com/benjamn/ast-types/tree/master/def">ast-types’s definitions</a> API to create new AST nodes</li></ul><p>Pasting the code from the gist above into AST explorer and looking through the AST tree to the right, we can see that:</p><ul><li>We must change an ImportSpecifier from map to ObservableMap inside the ImportDeclaration for MobX</li><li>We have to change any CallExpression to map to a NewExpression to ObservableMap</li></ul><h4>Writing Our Codemod</h4><p>To start writing our codemod, we choose “jscodeshift” under the “transform” menu on AST Explorer. This gives us another pane to write our codemod, and one more to check the results. Looking at <a href="https://github.com/facebook/jscodeshift#transform-module">JSCodeShift’s documentation</a> and some <a href="https://github.com/facebook/jscodeshift#example-codemods">provided examples</a>, we can start writing our codemod.</p><p>What can be a bit confusing at first is how you create new AST nodes in JSCodeShift. By following the third link above to ast-types and looking inside core.js, we can see that a NewExpression takes two arguments: the callee and the arguments. Our callee will remain anIdentifier, just with the name changed. JSCodeShift has the convention that the first letter is upper-case when you’re looking for a node, e.g. NewExpression, and lower-case when you’re creating one, e.g. newExpression(callee, arguments).</p><p>I’ve included the finished codemod below. If you paste it into AST Explorer, you’ll see that it does indeed transform our original code in the intended way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f79ee0437893b619e83346bf935323cb/href">https://medium.com/media/f79ee0437893b619e83346bf935323cb/href</a></iframe><p>To apply these changes to your codebase, install JSCodeShift with your favorite package manager and supply it with your transformation and the source files you want to apply it to:</p><pre>jscodeshift -t ./transform-mobx-map.js ./my-javascripts</pre><p>See the <a href="https://github.com/facebook/jscodeshift#usage-cli">documentation</a> for more information about command-line options and so on.</p><h4>Conclusion</h4><p>We’ve now learnt a new tool, written some code, and migrated all calls to a deprecated API! How awesome is that?</p><p>Tools similar to JSCodeShift are available for a lot of languages and they aren’t that difficult to use. Even <a href="https://github.com/jhgg/js-transforms/blob/master/pure-to-composite-component.js">turning a functional React component into a composite</a> one can be done in 30 lines of code.</p><p>More than anything, tools like these help your team be less reluctant when it comes to upgrading libraries and changing APIs. The value of these tools lie in their ability to assist an engineering team in being more agile and less afraid of change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808e2e29e5f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESLint 플러그인 만들기]]></title>
            <link>https://medium.com/@bjrnt/eslint-%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-8d6cb4514801?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d6cb4514801</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[eslint]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Sun, 20 Mar 2016 14:37:33 GMT</pubDate>
            <atom:updated>2016-03-21T03:33:18.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zwz6EehpN4-KTDLqbIbkg.jpeg" /></figure><p>우리가 자바스크립트 개발을 할 때 유용한 ESLint 플러그인들이 정말 많습니다. 텀블벅 엔지니어들은 이 중에서 특히 <a href="https://www.npmjs.com/package/eslint-config-airbnb">eslint-config-airbnb</a>와 <a href="https://www.npmjs.com/package/eslint-plugin-react">eslint-plugin-react</a>를 좋아합니다. 하지만 프로젝트가 커지면 개발자들이 프로젝트에 해당하는 best practices 들을 따르도록 하기 위해서 점점 커스텀 규칙들을 추가해야할 수 있습니다. 저는 이 포스트를 통해 텀블벅에서 어떻게 자체 ESLint 플러그인을 만들고 규칙을 작성했는지 설명하겠습니다.</p><h3>Setup</h3><p>우선 <a href="http://yeoman.io/">Yeoman</a>과 플러그인을 만들기 위해 필요한 모든 boiler-plate code 를 제공하는 <a href="https://github.com/eslint/generator-eslint">generator-eslint</a>을 설치하겠습니다:</p><pre>npm install -g yo<br>npm install -g generator-eslint</pre><p>다음은 플러그인의 디렉토리를 만들고 초기화합니다:</p><pre>mkdir eslint-plugin-tutorial<br>cd eslint-plugin-tutorial</pre><pre>yo eslint:plugin</pre><pre>? What is your name? ...<br>? What is the plugin ID? tutorial<br>? Type a short description of this plugin: ...<br>? Does this plugin contain custom ESLint rules? Yes<br>? Does this plugin contain one or more processors? No</pre><pre>npm install</pre><h3>규칙 만들기</h3><p>이제 첫번째 규칙을 만들 시간입니다! 다음과 같은 코드를 금지하는 규칙을 만들어 보도록 하겠습니다:</p><pre>var _ = require(&#39;your favorite fp library&#39;);</pre><p>위와 같이 작성하는 경우, 해당 모듈 안에 너무 많은 코드를 삽입하게 되어 <a href="http://www.2ality.com/2015/12/webpack-tree-shaking.html">tree-shaking</a>을 하기 어렵게 만듭니다.</p><p>우선 규칙을 생성해보겠습니다. <em>generator-eslint</em> 플러그인은 이 작업을 하기 위한 generator도 가지고 있습니다.</p><pre>yo eslint:rule</pre><pre>? What is your name? ...<br>? Where will this rule be published? ESLint Plugin<br>? What is the rule ID? no-full-fp-lib<br>? Type a short description of this rule: ...<br>? Type a short example of the code that will fail: var _ = require(&#39;your favorite fp library&#39;);</pre><p>규칙을 실제로 쓰기 위해서는 ESLint가 자바스크립트를 어떻게 파싱하는지 이해할 필요가 있습니다. ESLint는 자바스크립트 코드의 abstract syntax tree (AST)를 생성하기 위해서 <a href="https://github.com/eslint/espree">Espree</a>라는 자바스크립트 파서를 사용합니다. 규칙들은 tree 안에 있는 특정 node들을 “listen”할 수 있고, 매칭하는 node 가 발견되면, 액션이 취해져야 하는지 체크합니다. 다행히도, <a href="https://astexplorer.net/">astexplorer</a>란 사이트를 이용하면 자바스크립트 코드에서 AST를 쉽게 생성할 수 있습니다. 나중에 ESLint가 espree로 파싱할 테니, 기본값 파서를 ‘Acorn’에서 ‘Espree’로 바꿔 주세요.</p><p>우리가 막고자 하는 코드를 돌려보면, 아래의 AST가 생성됩니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a319c359a6586fe0ebf2bd1d67796b/href">https://medium.com/media/a4a319c359a6586fe0ebf2bd1d67796b/href</a></iframe><p>이 AST 는 우리가 규칙을 만드는데 필요한 모든 정보를 제공합니다. 우선, 우리가 관심있는 노드들은 VariableDeclaration이라는 type을 가지고 있는데, 이는 VariableDeclarator 리스트를 가지고 있습니다. 우리는 각각의 VariableDeclarator를 살펴보고 id with name = _ 와 require를 callee로 가지고 있는 init 을 체크하는 규칙을 구현할 수 있습니다. 규칙을 쓰기 위한 보다 상세한 설명이 필요하다면 <a href="http://eslint.org/docs/developer-guide/working-with-rules">ESLint documentation</a> 을 참고하는 것을 추천합나다.</p><p>위의 규칙 논리를 코드로 바꾸면, 다음과 같이 됩니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91bd34db9b4fbf102dd1eacd1c6b85e2/href">https://medium.com/media/91bd34db9b4fbf102dd1eacd1c6b85e2/href</a></iframe><h3>Testing</h3><p>우리가 만든 규칙에 대한 테스팅을 하기 위해서는 <a href="https://mochajs.org/">Mocha</a> 를 설치하고 <em>package.json</em> 에 있는 test script를 수정하면 됩니다:</p><pre>“scripts”: {<br> “test”: “mocha ./tests/**/*.js”<br> },</pre><p>이미 generator-eslint 가 생성한 코드가 있기 때문에, 에러 메시지, type, 그리고 몇 가지 valid 예제만 추가하면 됩니다!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24c745195e26f30abf05a8e5f53f9c8/href">https://medium.com/media/e24c745195e26f30abf05a8e5f53f9c8/href</a></iframe><p>Mocha를 다음과 같이 돌리면:</p><pre>npm run test</pre><p>모든 테스트들이 통과한다는 것을 확인할 수 있습니다!</p><h3>ES6+</h3><p>ES6를 위한 규칙을 작성하고 테스팅하는 것은 비교적 어려울 수 있는데, 이는 추가적인 설정이 필요하기 때문입니다. 일단은 astexplorer를 계속 쓸 수 있는데, parser settings에서 ecmaVersion이 6인 것 확인해야 합니다.</p><p>ES6로 동일한 코드를 쓸 때, 우리는 다음과 같은 import 들을 금지하고 싶습니다:</p><pre>import _ from &#39;my favorite fp lib&#39;;</pre><p>아까와 같은 논리로 규칙을 만듭니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d47c7d2d48c45285853b930a307313/href">https://medium.com/media/d8d47c7d2d48c45285853b930a307313/href</a></iframe><p>이 규칙을 테스팅을 하기 위해 ESLint 설정을 몇가지 추가해야 합니다. 이제 ES6 쓰고 있으니 ecmaVersion을 6으로 바꿔야 하고, <em>import</em>를 쓸 수 있게 flag도 하나 추가해야 합니다. 사용 가능한 피쳐들에 대한 더 상세한 내용은 <a href="http://eslint.org/docs/user-guide/migrating-to-2.0.0#language-options">ESLint 문서</a>에서 찾아볼 수 있습니다.</p><p>테스트 코드를 다음과 같이 수정합니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e15c8ab62f4083a82bcbc174fedced2/href">https://medium.com/media/5e15c8ab62f4083a82bcbc174fedced2/href</a></iframe><p><em>npm run test</em>을 돌리면, 우리 규칙이 올바르게 작동하는 것을 확인할 수 있습니다!</p><h3>Wrapping Up</h3><p>우리 규칙이 쓰여졌고 테스팅이 되었으니, 유일하게 남은 작업은 패키징을 하는 것입니다.</p><p>ESLint 가 어떤 규칙도 디폴트로 활성화시키지 않기 때문에, 아마도 우리의 새로운 규칙을 활성화시키는 config를 export 해야합니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083178ee5302bbadafdc78a637c5b9b4/href">https://medium.com/media/083178ee5302bbadafdc78a637c5b9b4/href</a></iframe><p>이 추천된 config는 <a href="http://eslint.org/docs/user-guide/configuring">우리의 다른 프로젝트들이 이를 사용하도록 설정</a>하면 사용됩니다.</p><p>이제 npm에 우리 패키지를 선택적으로 publish하고 프로젝트에 사용하는 일만 남았습니다!</p><p><a href="https://github.com/tumblbug/eslint-plugin-tumblbug">Github 에 있는 프로젝트 Repository</a>를 참고해주세요.</p><p>Happy linting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d6cb4514801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an ESLint Plugin]]></title>
            <link>https://medium.com/@bjrnt/creating-an-eslint-plugin-87f1cb42767f?source=rss-cff697bd1635------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f1cb42767f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Björn Tegelund]]></dc:creator>
            <pubDate>Thu, 17 Mar 2016 07:43:10 GMT</pubDate>
            <atom:updated>2016-03-21T05:49:19.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zwz6EehpN4-KTDLqbIbkg.jpeg" /></figure><p>There are a lot of useful ESLint plugins out there. At Tumblbug, we are fans of <a href="https://www.npmjs.com/package/eslint-config-airbnb">eslint-config-airbnb</a> and <a href="https://www.npmjs.com/package/eslint-plugin-react">eslint-plugin-react</a>. However, as a project grows, you might start feeling the need for adding custom rules to ensure that your developers are following best practices. In this blog post, I’ll be going over creating a custom ESLint plugin and writing a simple rule for it.</p><h3>Setup</h3><p>We’ll begin by installing <a href="http://yeoman.io/">Yeoman</a> and the handy <a href="https://github.com/eslint/generator-eslint">generator-eslint</a>, which provides all the boiler-plate code needed to create our plugin:</p><pre>npm install -g yo<br>npm install -g generator-eslint</pre><p>Next, we create a directory for our plugin and initialize it:</p><pre>mkdir eslint-plugin-tutorial<br>cd eslint-plugin-tutorial</pre><pre>yo eslint:plugin</pre><pre>? What is your name? ...<br>? What is the plugin ID? tutorial<br>? Type a short description of this plugin: ...<br>? Does this plugin contain custom ESLint rules? Yes<br>? Does this plugin contain one or more processors? No</pre><pre>npm install</pre><h3>Rule Creation</h3><p>Now it’s time to create our first rule! We’re going to be making a rule that prohibits code like:</p><pre>var _ = require(&#39;your favorite fp library&#39;);</pre><p>as this brings too much code into the current module and makes it difficult to perform <a href="http://www.2ality.com/2015/12/webpack-tree-shaking.html">tree-shaking</a>.</p><p>Let’s begin by generating our rule! The <em>generator-eslint</em> plugin has a generator for this as well.</p><pre>yo eslint:rule</pre><pre>? What is your name? ...<br>? Where will this rule be published? ESLint Plugin<br>? What is the rule ID? no-full-fp-lib<br>? Type a short description of this rule: ...<br>? Type a short example of the code that will fail: var _ = require(&#39;your favorite fp library&#39;);</pre><p>To actually write our rule, we’re going to need to know a bit about how JavaScript is parsed. ESLint uses a JavaScript parser called <a href="https://github.com/eslint/espree">Espree</a> to generate an abstract syntax tree (AST) from JavaScript code. Rules can then “listen” for certain types of nodes in the tree and when a matching node is discovered, rules are invoked to check whether any action needs to be taken. Luckily, there’s a handy site available for turning JavaScript code into an AST, called <a href="https://astexplorer.net/">astexplorer</a>. As we’ll be using the default Espree parser in ESLint to parse our code, it’s a good idea to change parser from the default ‘Acorn’ to ‘Espree’.</p><p>The following AST is generated by the code we want to prohibit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a319c359a6586fe0ebf2bd1d67796b/href">https://medium.com/media/a4a319c359a6586fe0ebf2bd1d67796b/href</a></iframe><p>This AST provides us with all the information needed to create our rule. First off, we can see that the nodes we are interested in are of the type <em>VariableDeclaration, </em>which contains a list of <em>VariableDeclarator</em>. We can implement our rule by looking at each <em>VariableDeclarator</em> and specifically check for an <em>id</em> with <em>name = _ </em>and an <em>init</em> where the <em>callee</em> is <em>require. </em>I recommend consulting the <a href="http://eslint.org/docs/developer-guide/working-with-rules">ESLint documentation</a> for a more in-depth explanation on writing rules.</p><p>Turning the above rule logic into code, we get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91bd34db9b4fbf102dd1eacd1c6b85e2/href">https://medium.com/media/91bd34db9b4fbf102dd1eacd1c6b85e2/href</a></iframe><h3>Testing</h3><p>We can easily test our rule by installing <a href="https://mochajs.org/">Mocha</a> and editing our test script in package.json:</p><pre>“scripts”: {<br> “test”: “mocha ./tests/**/*.js”<br> },</pre><p>We already have some code generated by generator-eslint, so all we have to do is fill in the error message, type, and add a couple of valid examples!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24c745195e26f30abf05a8e5f53f9c8/href">https://medium.com/media/e24c745195e26f30abf05a8e5f53f9c8/href</a></iframe><p>Running mocha using:</p><pre>npm run test</pre><p>We see that all our tests pass!</p><h3>ES6+</h3><p>Writing and testing rules for ES6 is a bit more difficult, as additional configuration is needed to get everything running. We can still use AST explorer to generate an AST, but make sure that the appropriate <em>ecmaVersion </em>is selected under parser options.</p><p>Writing the equivalent code in ES6, we now want to prohibit imports such as:</p><pre>import _ from &#39;my favorite fp lib&#39;;</pre><p>We write the rule using the same logic as earlier, and end up with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d47c7d2d48c45285853b930a307313/href">https://medium.com/media/d8d47c7d2d48c45285853b930a307313/href</a></iframe><p>To test this, we need to provide ESLint with some additional configuration for it to know how to run our rule. First off, as we’re now using ES6, we have to set the <em>ecmaVersion</em> to 6, and as our rule uses <em>import, </em>we also have to set a flag to enable this. A more extensive list of the different features that can be used is available on <a href="http://eslint.org/docs/user-guide/migrating-to-2.0.0#language-options">ESLints documentation</a>.</p><p>We now end up with the following test code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e15c8ab62f4083a82bcbc174fedced2/href">https://medium.com/media/5e15c8ab62f4083a82bcbc174fedced2/href</a></iframe><p>Running <em>npm run test</em>, we see that our rule is doing its job correctly!</p><h4>Wrapping Up</h4><p>Now that our rule is written and tested, all that remains is wrapping up our package.</p><p>As ESLint does not enable any rules by default, we will probably want to export a config that enables our new rule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083178ee5302bbadafdc78a637c5b9b4/href">https://medium.com/media/083178ee5302bbadafdc78a637c5b9b4/href</a></iframe><p>This recommended config can then be used by <a href="http://eslint.org/docs/user-guide/configuring">configuring our other projects to extend it</a>.</p><p>All that’s left now is to optionally publish our package to npm, and to install and use it in our other projects!</p><p>Take a look at the <a href="https://github.com/tumblbug/eslint-plugin-tumblbug">project repository on Github</a>.</p><p>Happy linting!</p><p><strong>Update:</strong> much thanks to Ilya Volodin for sharing a lot of useful resources! This post is now much simpler than it originally was!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f1cb42767f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>