<?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 Stefano Saffran on Medium]]></title>
        <description><![CDATA[Stories by Stefano Saffran on Medium]]></description>
        <link>https://medium.com/@stefanosaffran?source=rss-e7dee8413791------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m3ScT36bjbkea_hy-1Hf4w.jpeg</url>
            <title>Stories by Stefano Saffran on Medium</title>
            <link>https://medium.com/@stefanosaffran?source=rss-e7dee8413791------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:01:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefanosaffran/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[Temporal API]]></title>
            <link>https://medium.com/profusion-engineering/temporal-api-e4c2489ef06b?source=rss-e7dee8413791------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c2489ef06b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[date]]></category>
            <category><![CDATA[temporal-api]]></category>
            <dc:creator><![CDATA[Stefano Saffran]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 12:50:19 GMT</pubDate>
            <atom:updated>2023-03-13T12:50:19.102Z</atom:updated>
            <content:encoded><![CDATA[<h4>the API to solve all the Date problems in JavaScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LHiDotK9g_vN0coJ0sVrqg.jpeg" /></figure><p>Hello guys,</p><p>In this post, we will be diving into the new JavaScript Temporal API and exploring its features and capabilities in detail.</p><p>Date and time are a crucial part of any application, whether it’s a simple to-do list or a complex scheduling system. Unfortunately, working with dates in JavaScript has been a challenge for many developers, due to the limited built-in functionality and inconsistencies across different browsers and environments. This has led to the popularity of libraries like <a href="https://momentjs.com/">Moment.js</a> and <a href="https://date-fns.org/">DateFns</a>, which provide a rich set of tools for working with dates. However, even with those libraries, there are still challenges with accuracy, consistency, and performance. Especially when we talk about time and timezones.</p><p>Dealing with times and timezones computationally can be challenging due to the complex nature of time. Time is not a constant and is affected by factors such as the Earth’s rotation, leap years, daylight saving time, and more. Additionally, timezones add another layer of complexity, as they are based on geopolitical boundaries rather than physical ones. It can also be particularly difficult when working with historical dates, as the timezone rules may have changed over time.</p><p>To solve this, here comes the <a href="https://tc39.es/proposal-temporal/docs/">Temporal API</a>: The New Standard for Working with Dates in JavaScript.</p><p>The Temporal API is a new, standards-based approach in JavaScript to work with dates, times, durations, and periods. It is a global Object that acts as a top-level namespace (like <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a>) and provides a simple, consistent, and efficient way to perform a wide range of operations with temporal data, from parsing dates from strings to performing complex arithmetic calculations. The Temporal API is part of the ECMAScript Internationalization API and is based on the latest standards from the International Organization for Standardization (ISO). This means that it provides a reliable, high-quality solution that is backed by an international community of experts.</p><p>If you want to see more details about some of the problems JavaScript Date has and the motivations for Temporal, see <a href="https://maggiepint.com/2017/04/09/fixing-javascript-date-getting-started/">Fixing JavaScript Date</a>.</p><h4>Why is the Temporal API better than current libraries?</h4><p>There are several reasons why the Temporal API is a better solution than current libraries like Moment.js and DateFns.</p><ul><li>As I said before, it is a standards-based API, which means that it provides a consistent and reliable way to work with dates and times that is not dependent on a single library and the way the creator drives it;</li><li>It is highly optimized for performance, with a focus on providing fast and efficient algorithms for working with temporal data;</li><li>It provides a rich set of features specifically designed for working with dates and times, such as built-in support for time zones, leap years, and leap seconds;</li><li>It is designed to be easy to use, with a simple and intuitive API that is easy to understand and integrate into your applications.</li></ul><h4><strong>Now, let&#39;s take a look at some features of Temporal API</strong></h4><p>In this post, we’ll cover some of the most important data types and static methods available in Temporal. If you want to explore all of them, head over to the <a href="https://tc39.es/proposal-temporal/docs">Temporal docs</a>.</p><h4><strong>PlainDateTime</strong></h4><blockquote><strong>PlainDateTime</strong> represents a calendar date and wall-clock time that does not carry time zone information</blockquote><p>To create a PlainDateTime object, you can use the Temporal.PlainDateTime constructor, which takes in a year, month, and day as required arguments, and also, hour, minute, second, millisecond, microsecond, nanosecond, and calendar as optional arguments, in that order.</p><pre>const dateTime = new Temporal.PlainDateTime(2023, 2, 23, 10, 30, 0, 0);</pre><p>This creates a PlainDateTime object representing February 23, 2023 at 10:30.</p><p>The temporal object offers many utility methods inside it.</p><pre>const dateTime = new Temporal.PlainDateTime(2023, 2, 23, 10, 30, 0, 0);<br><br>console.log(dateTime.year);                  <br>// 2023<br>console.log(dateTime.hour);                  <br>// 10<br>console.log(dateTime.minute);                <br>// 30<br>console.log(dateTime.nanosecond);            <br>// 0<br>console.log(dateTime.calendar.toString());   <br>// iso8601</pre><p>An alternative way is to use the <a href="https://tc39.es/proposal-temporal/docs/#Temporal-Now">Temporal.Now</a> object, that has several methods which give information about the current time and date.</p><p>Using Now we also have access to the same static methods we had using the PlainDateTime constructor.</p><pre>const today = Temporal.Now.plainDateTimeISO()<br>console.log(today.toString()); <br>// 2023-02-23T10:45:40.438072454<br>console.log(today.toPlainMonthDay().toString());<br>// &#39;02-23&#39;</pre><h4>ZonedDateTime</h4><blockquote><strong>ZonedDateTime</strong> is a Temporal object that represents a date and time in the context of a specific time zone.</blockquote><p>We can do the same as withPlainDateTime, using the Temporal.ZonedDateTimeconstructor, which takes in a required epochNanoseconds (bigint), and optional timeZone and calendar as arguments or we can also use Temporal.Now .</p><pre>const zonedDateTime = new Temporal.ZonedDateTime(<br>  1677265360653057483n, &#39;America/Campo_Grande&#39;, &#39;iso8601&#39;<br>);<br>console.log(zonedDateTime.toString()); <br>// 2023-02-24T15:02:40.653057483-04:00[America/Campo_Grande]<br>console.log(zonedDateTime.startOfDay().toString()) <br>// 2023-02-24T00:00:00-04:00[America/Campo_Grande]<br>console.log(zonedDateTime.dayOfWeek);        <br>// 5<br>console.log(zonedDateTime.day);              <br>// 24<br>console.log(zonedDateTime.epochNanoseconds); <br>// 1677265360653057483n<br><br>const todayZoned = Temporal.Now.zonedDateTimeISO()<br>console.log(todayZoned.toString());<br>// 2023-02-23T16:44:32.454458232-04:00[America/Campo_Grande]</pre><h4>PlainDate</h4><blockquote><strong>PlainDate</strong> object represents a calendar date that is not associated with a particular time or time zone.</blockquote><pre>const today = Temporal.Now.plainDateISO()<br>console.log(today.toString())<br>// 2023-02-23<br>const date1 = new Temporal.PlainDate(2023, 02, 19)<br>console.log(date1.toString())<br>// 2023-02-19<br>const date2 = Temporal.PlainDate.from(&quot;2023-02-19&quot;)<br>console.log(date2.toString())<br>// 2023-02-19<br>const date3 = Temporal.PlainDate.from({ year: 2023, month: 2, day: 19 })<br>console.log(date3.toString())<br>// 2023-02-19</pre><p><em>Note that we used the static method </em><em>from above, and there are quite a few of them and we’ll talk a little bit about them later.</em></p><h4>PlainTime</h4><blockquote><strong>PlainTime</strong> object represents a wall-clock time that is not associated with a particular date or time zone</blockquote><pre>const today = Temporal.Now.plainTimeISO()<br>console.log(today.toString())<br>// 16:36:50.739773623<br>const time1 = new Temporal.PlainTime(12, 25)<br>console.log(time1.toString())<br>// 12:25:00<br>const time2 = Temporal.PlainTime.from(&quot;05:43:17&quot;)<br>console.log(time2.toString())<br>// 05:43:17<br>const time3 = Temporal.PlainTime.from({ hour: 1, minute: 3, second: 44 })<br>console.log(time3.toString())<br>// 01:03:44</pre><h4><strong>Instant</strong></h4><blockquote><strong>Instant</strong> is a single point in time (called &quot;exact time&quot;), with a precision in nanoseconds. It is always in UTC time , and no time zone or calendar information is present. To obtain local date/time units like year, month, day, or hour, a Temporal.Instant must be combined with a Temporal.TimeZone instance or a time zone string.</blockquote><pre>const now = Temporal.Now.instant()<br>console.log(now.toString())<br>// 2023-02-23T13:53:45.308214163Z<br><br>const dateInstant = Temporal.Instant.from(&quot;2000-01-01T00:00+04:00&quot;)<br>console.log(dateInstant.toString())<br>// 1999-12-31T20:00:00Z<br>console.log(dateInstant.year); <br>// =&gt; undefined<br><br>const tokyoZonedDateTime = dateInstant.toZonedDateTimeISO(&#39;Asia/Tokyo&#39;);<br>console.log(tokyoZonedDateTime.toString())<br>// 2000-01-01T05:00:00+09:00[Asia/Tokyo]&#39;<br>console.log(tokyoZonedDateTime.year);<br>// 2000</pre><h4>Duration</h4><blockquote><strong>Duration</strong> represents a duration of time that can be used in date/time arithmetic, and when printed, it produces a string according to the ISO 8601 <a href="https://en.wikipedia.org/wiki/ISO_8601#Durations">notation</a> for durations.</blockquote><pre>const duration = Temporal.Duration.from({ years: 1, days: 5, months: 22 });<br>console.log(duration.toString());<br>// P1Y22M5D<br>console.log(new Temporal.Duration(1, 2, 3, 4, 5, 6, 7, 888, 999, 0).toString());<br>// P1Y2M3W4DT5H6M7.888999S<br><br>const duration1 = Temporal.Duration.from({ hours: 2, minutes: 30, seconds: 10 });<br>// PT2H30M10S (2 hours, 30 minutes, and 10 seconds)<br>const duration2 = Temporal.Duration.from({ hours: 1, minutes: 45, seconds: 30 });<br>// PT1H45M30S (1 hours, 45 minutes, and 30 seconds)<br><br>// Adding two durations<br>const sum = duration1.add(duration2);<br>console.log(sum.toString()); <br>// PT4H15M40S (4 hours, 15 minutes, and 40 seconds)<br><br>// Subtracting two durations<br>const difference = duration1.subtract(duration2);<br>console.log(difference.toString()); <br>// PT44M40S (44 minutes and 40 seconds)</pre><h4>Static methods</h4><p>There are several static methods in the API, we saw some of them in this post, like from , add and subtract . They provide utility functions for working with temporal data and you can use them to convert types, do some calculations, compare and sort dates, and much more.</p><p>Here are some examples of what we can do:</p><ul><li>Calculate how many days are left until the end of the year</li></ul><pre>const today = Temporal.Now.plainDateTimeISO(); // get current date and time<br>const end = Temporal.PlainDate.from(&#39;2023-12-31&#39;); // set the end of the year<br><br>const diff = Temporal.Duration.from({ days: today.until(end).days });<br>console.log(`Days until end of year: ${diff.days}`); <br>// Days until end of year: 310</pre><ul><li>Scheduling tasks</li></ul><pre>let start = Temporal.Now.plainDateTimeISO();<br>const duration = Temporal.Duration.from({ hours: 1, minutes: 30, seconds: 0 });<br>const end = start.add(duration);<br>const interval = Temporal.Duration.from({ minutes: 15 });<br><br>while (Temporal.PlainDateTime.compare(start, end) &lt; 0) {<br>  console.log(`Scheduled task for: ${start.toString()}`);<br>  start = start.add(interval);<br>}<br>/* <br>  Scheduled task for: 2023-02-23T15:51:50.394704559<br>  Scheduled task for: 2023-02-23T16:06:50.394704559<br>  Scheduled task for: 2023-02-23T16:21:50.394704559<br>  Scheduled task for: 2023-02-23T16:36:50.394704559<br>  Scheduled task for: 2023-02-23T16:51:50.394704559<br>  Scheduled task for: 2023-02-23T17:06:50.394704559<br>*/<br></pre><ul><li>Flight arrival time in destination time zone (from <a href="https://tc39.es/proposal-temporal/docs/cookbook.html#flight-arrivaldepartureduration">docs</a>)</li></ul><pre>const departure = Temporal.ZonedDateTime.from(&#39;2020-03-08T11:55:00+08:00[Asia/Hong_Kong]&#39;);<br>const flightTime = Temporal.Duration.from({ minutes: 775 });<br><br>const arrival = departure.add(flightTime).withTimeZone(&#39;America/Los_Angeles&#39;);<br>console.log(arrival.toString())<br>// &#39;2020-03-08T09:50:00-07:00[America/Los_Angeles]&#39;</pre><p>As you can see the API provides a robust set of methods that can be really helpful in many different situations and will for sure simplify the developer&#39;s lives when it comes to working with dates and times in JavaScript.</p><h4>How to use it?</h4><p>The API is still a proposal in <a href="https://github.com/tc39/proposals#stage-3">Stage 3</a> (meaning the draft is almost final and ready for last feedback) as of now (March 2023) and no browser supports it at the moment, but they should support it soon.</p><p>If you want to test it now, you can use this polyfill: <a href="https://github.com/js-temporal/temporal-polyfill">@js-temporal/polyfill</a>. Just install it and you’re ready to go.</p><h4>References</h4><ul><li><a href="https://tc39.es/proposal-temporal/docs/">Temporal Docs</a></li><li><a href="https://github.com/tc39/proposal-temporal">Github repository</a></li><li><a href="https://blog.lsantos.dev/temporal-api/">Temporal: a nova forma de se trabalhar com data em JavaScript</a></li><li><a href="https://nitayneeman.com/posts/introducing-all-stages-of-the-tc39-process-in-ecmascript/">ESMAScript — Introducing all stages of the TC39 process</a></li></ul><p>That’s all! I hope you enjoyed reading it, bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c2489ef06b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/profusion-engineering/temporal-api-e4c2489ef06b">Temporal API</a> was originally published in <a href="https://medium.com/profusion-engineering">ProFUSION Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vite: Next Generation Frontend Tooling]]></title>
            <link>https://medium.com/profusion-engineering/vite-next-generation-frontend-tooling-af4d68292fbf?source=rss-e7dee8413791------2</link>
            <guid isPermaLink="false">https://medium.com/p/af4d68292fbf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[bundler]]></category>
            <dc:creator><![CDATA[Stefano Saffran]]></dc:creator>
            <pubDate>Wed, 25 May 2022 16:25:28 GMT</pubDate>
            <atom:updated>2022-11-25T15:35:39.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BazVPAGwGA7v1H3893G1xg.png" /><figcaption>Vite logo</figcaption></figure><p>Por muito tempo o CRA (Create React App) foi a opção mais prática para iniciar uma aplicação SPA React, pois debaixo dos panos ele já configurava Webpack, Babel, ESLint e outras ferramentas sem você precisar saber como elas funcionam, ou seja, sem precisar se preocupar com as limitações dos browsers, gerenciamento de pacotes de terceiros e deixar o app pronto para produção.</p><h4>O que é Vite?</h4><p>Vite (palavra francesa para “rápido”, pronunciada /vit/) é uma ferramenta para construção de aplicações frontend que melhora significativamente a experiência de <strong>desenvolvimento</strong>.</p><p>O Vite vem como uma das opções (a mais popular segundo <a href="https://risingstars.js.org/2021/en#section-build">BestOfJS</a> em 2021) que se aproveitam da evolução do ecossistema JavaScript para solucionar os problemas encontrados no CRA.</p><p><em>A otimização é exclusiva para a fase de desenvolvimento. O build para produção é feito utilizando </em><a href="https://rollupjs.org/guide/en/"><em>Rollup</em></a><em> e não promete nenhum ganho comparado com outras ferramentas.</em></p><h4>Qual o problema com o CRA?</h4><p>Com o passar do tempo as aplicações começaram a ficar cada vez mais complexas, aumentando assim a quantidade de código JavaScript nelas. Com isso o CRA começa a ter problemas de desempenho ao trabalhar com tantos módulos, ocasionando esperas excessivas e afetando a produtividade no desenvolvimento.</p><h4>Como o Vite resolve?</h4><p>Para poder entender melhor como ele resolve, vamos primeiro dar uma olhada em como o webpack funciona.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuNiE3fnHShp5HlM6_tXOQ.png" /><figcaption>Fluxo do webpack</figcaption></figure><p>Ao iniciar seu projeto em desenvolvimento, o webpack segue as seguintes etapas:</p><ol><li>O empacotamento (Bundling) de todo o código;</li><li>Inicia o servidor que vai servir o código empacotado;</li><li>Faz a configuração necessária para lidar com o HMR (Hot Module Reloading);</li><li>Depois de tudo pronto, inicia a aplicação.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*2V3UPSeullpsfaJ31lHj2g.png" /><figcaption>Fluxo do Vite</figcaption></figure><p>Vite, por outro lado, segue um fluxo diferente: Quando inicia a aplicação, serão feitas apenas pre-otimizações em seu node_modules e logo depois a aplicação já é iniciada, sem a necessidade de aguardar empacotamento. Isso é possível pois ele divide o código em duas partes: <strong>código fonte</strong> e <strong>dependências</strong>.</p><p>As <strong>dependências</strong> são geralmente arquivos JavaScript que não sofrerão alterações com frequência. O Vite pre-empacota esses arquivos utilizando o <a href="https://esbuild.github.io/">ESBuild</a> que faz o serviço de 10 a 100 vezes mais rápido do que qualquer outro empacotador JavaScript do mercado.</p><p>O <strong>código fonte </strong>por sua vez, é o código que vai mudar com frequência e precisa ser transformado (Typescript, JSX, CSS, etc). Vite serve o código fonte como módulos JavaScript nativos (ESM), com isso o browser acaba ajudando no trabalho de empacotamento (bundler). Como nem todo código precisa ser carregado ao mesmo tempo, Vite transforma o código sob demanda, conforme o browser for solicitando.</p><p>Vite também se aproveita dos headers HTTP para acelerar os ‘reloads’ das páginas. As solicitações dos módulos de código fonte são feitas condicionalmente via código 304 (Not Modified) e as de módulos de dependências são armazenadas em cache, para que, uma vez armazenadas, não precisem atingir o servidor novamente.</p><p>Agora vamos criar um projeto React/TypeScript utilizando CRA e Vite.</p><ul><li>Criando com CRA</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*i1dzLLv3fkRMk0_cOnXsKg.png" /><figcaption>Criando projeto react com Create React App</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*mfwtgyZ9Cr_ajVrKHhEx8w.png" /></figure><ul><li>Criando com Vite</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*orBwSP-Nj1mWwZriJFWAuA.png" /><figcaption>Criando projeto React com Vite</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*Iz5V90tA7Og1EOJMLyD2oA.png" /></figure><p>Logo na criação já é possível notar uma boa diferença no tempo, o projeto com Vite foi criado em menos de 2 segundos. Mas a diferença fica bem mais acentuada na execução do projeto conforme ele começa a crescer e ter vários módulos.</p><h4>Referências</h4><ul><li><a href="https://vitejs.dev/">Documentação do Vite</a></li><li><a href="https://javascript.plainenglish.io/time-to-say-goodbye-to-webpack-5bf06ff48823">Is it Time To Say Goodbye To Webpack?</a></li><li><a href="https://harlanzw.com/blog/how-the-heck-does-vite-work/">How does Vite work?</a></li></ul><p>Isso é tudo. Espero que tenham gostado da leitura e até a próxima!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af4d68292fbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/profusion-engineering/vite-next-generation-frontend-tooling-af4d68292fbf">Vite: Next Generation Frontend Tooling</a> was originally published in <a href="https://medium.com/profusion-engineering">ProFUSION Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>