<?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 Itelo Nogueira on Medium]]></title>
        <description><![CDATA[Stories by Itelo Nogueira on Medium]]></description>
        <link>https://medium.com/@itelonog?source=rss-88b68dbffa99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g0akgQUnkvBT18svBOCcTQ.jpeg</url>
            <title>Stories by Itelo Nogueira on Medium</title>
            <link>https://medium.com/@itelonog?source=rss-88b68dbffa99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:34:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itelonog/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[Passar a escrever os seus componentes no padrão “compound components” pode te salvar muitas horas…]]></title>
            <link>https://itelonog.medium.com/passar-a-escrever-os-seus-componentes-no-padr%C3%A3o-compound-components-pode-te-salvar-muitas-horas-517677fd9f3f?source=rss-88b68dbffa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/517677fd9f3f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Itelo Nogueira]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 16:12:59 GMT</pubDate>
            <atom:updated>2021-06-19T16:12:59.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Passar a escrever os seus componentes no padrão “compound components” pode te salvar muitas horas de refactor.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fDNoQKUS5c1ZowCu" /><figcaption>Photo by <a href="https://unsplash.com/@ganzaro?utm_source=medium&amp;utm_medium=referral">Marko Ganzaro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Como eu quero que esse texto seja uma leitura rápida, não vou colocar nenhuma implementação do código</blockquote><p>Vamos começar imaginando que o time de design lhe entregou o Menu abaixo no figma e agora chegou a sua hora de implementa-lo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ua-7SYCcDRQ8iDzlHaHMQ.png" /></figure><p>Uma implementação válida poderia ser:</p><pre>&lt;Menu<br>  trigger={&lt;MoreIcon /&gt;}<br>  config={{<br>    onClick: someFunction,<br>    label: &quot;Delete&quot;<br>  }}<br>/&gt;</pre><p>Parabéns! Você conseguiu entregar o menu e já pode pegar outras tarefas.</p><p>Passou algum tempo e agora aquele menu que você fez precisa ser mais flexível e capaz de receber mais features, como por exemplo, mais um botão para poder editar algo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8n_gXPNZ62kOrvhnBw3vA.png" /></figure><p>Vendo o novo design, você decide atualizar o objeto de configuração, para algo semelhante com o código abaixo:</p><pre>&lt;Menu<br>  trigger={&lt;MoreIcon /&gt;}<br>  config={[<br>    {<br>      label: &#39;Edit&#39;,<br>      onClick: someFunction1,<br>    },<br>    {<br>      label: &#39;Delete&#39;,<br>      onClick: someFunction2,<br>    }<br>  ]}<br>/&gt;</pre><p>uhuuuul! Esse menu não é mais probl… POW, surge do nada, sem nenhum aviso um novo menu…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enf2OjSxX_3BaSW4EqcUaA.png" /></figure><p>Agora você começa a ficar chateado por estar preso nesse menu durante um bom tempo e, mais uma vez, você precisa voltar nele e alterá-lo.</p><pre>&lt;Menu trigger={&lt;MoreIcon /&gt;} config={[<br>  {<br>    title: &quot;safe actions&quot;,<br>    items: [<br>      {<br>        label: &#39;Edit&#39;,<br>        onClick: someFunction1,<br>        align: &#39;left&#39;,<br>      }<br>    ],<br>    hasDividerBellow: true,<br>  },<br>  {<br>    title: &quot;unsafe actions&quot;,<br>    items: [<br>      {<br>        label: &#39;Edit&#39;,<br>        onClick: someFunction2,<br>        align: &#39;left&#39;,<br>        color: &#39;red&#39;,<br>      }<br>    ],<br>    hasDividerBellow: false,<br>  },<br>]} /&gt;</pre><p>Você decide seguir a implementação com o objeto de configuração a cima e pronto! Acabamos com a nossa historinha e já podemos analisar alguns fatores sobre ela.</p><p>Se em algum momento você chegou nesse ponto, provavelmente pensou algumas coisas, como:</p><ul><li><em>Esse código tá uma bagunça!!!</em></li><li><em>Se eu soubesse que o componente final seria, teria feito um código muito melhor!</em></li><li><em>Esse código tá muito complexo, acho que vou fazer um refactor depois</em> (SPOILER: O depois nunca chegou)</li></ul><p><strong>ISSO É NORMAL</strong>, principalmente se você for iniciante. Então, vamos seguir adiante e analisar quais os maiores problemas da abordagem a cima:</p><ul><li>Toda feature nova vai precisar de um novo refactor</li><li>Conforme a quantidade de features do seu objeto aumentar, mais difícil vai ser manter o componente devido ao aumento da complexidade, ou seja não é muito escalável</li><li>A legibilidade do seu código vai diminuindo cada vez mais.</li></ul><p>OK, o que podemos fazer para evitar isso? existe uma solução? SIM!</p><h3><strong>Compound Components no lugar de objetos de configuração</strong></h3><p>A ideia por trás dos <em>compound components </em>baseia-se na mudança da quantidade de componentes: anteriormente, você possuía apenas um componente com um objeto de configuração; e agora, você tem dois ou mais componentes que trabalham juntos para realizar algo. Ou seja, você vai separar a sua solução única em mais de um componente para que depois eles possam compor a solução final. (daí o nome 🤯)</p><p>Vamos ver então como ficaria as implementações acima utilizando o padrão do <em>compound components.</em></p><p>Para o primeiro caso:</p><pre>&lt;Menu trigger={&lt;MoreIcon /&gt;}&gt;<br>  &lt;Menu.Container&gt;<br>    &lt;Menu.Button label=&quot;Delete&quot; onClick={someFunction1} /&gt;<br>  &lt;/Menu.Container&gt;<br>&lt;/Menu&gt;</pre><p>Enquanto o segundo ficaria parecido com:</p><pre>&lt;Menu trigger={&lt;MoreIcon /&gt;}&gt;<br>  &lt;Menu.Container&gt;<br>    &lt;Menu.Button label=&quot;Edit&quot; onClick={someFunction1} /&gt;<br>    &lt;Menu.Button label=&quot;Delete&quot; onClick={someFunction1} <br>  &lt;/Menu.Container&gt;<br>&lt;/Menu&gt;</pre><p>E o último ficaria:</p><pre>&lt;Menu trigger={&lt;MoreIcon /&gt;}&gt;<br>  &lt;Menu.Container&gt;<br>    &lt;Menu.Section title=&quot;safe actions&quot;&gt;<br>      &lt;Menu.Button label=&quot;Edit&quot; onClick={someFunction1} /&gt;<br>    &lt;/Menu.Section&gt;<br>    &lt;Menu.Divider /&gt;<br>    &lt;Menu.Section title=&quot;unsafe actions&quot;&gt;<br>      &lt;Menu.Button label=&quot;Delete&quot; onClick={someFunction1} <br>    &lt;/Menu.Section&gt;<br>  &lt;/Menu.Container&gt;<br>&lt;/Menu&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*UWp9J5vGv-bSn4ZY7ygjcA.jpeg" /></figure><h3>Concluindo</h3><p>A grande vantagem de seguir esse padrão esta na sua flexibilidade. No caso acima, por exemplo, você não precisaria ficar voltando no componente e refatorando o código toda vez que o menu precisasse de uma feature nova, você iria apenas criar novos componentes.</p><p>Outra vantagem está na legibilidade, já que cada componente tende a ser pequeno e/ou ter uma responsabilidade bem específica, facilitando a manutenção dos mesmos.</p><p>Eu espero que você tenha gostado da leitura e que ela tenha contribuído em algo a sua vida 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517677fd9f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the init command of create-react-app from scratch]]></title>
            <link>https://itelonog.medium.com/building-the-init-command-of-create-react-app-from-scratch-b8c4384ebe1a?source=rss-88b68dbffa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8c4384ebe1a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Itelo Nogueira]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 23:03:33 GMT</pubDate>
            <atom:updated>2020-10-22T23:03:33.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BEcnd8YmATfRFMeS" /><figcaption>Photo by <a href="https://unsplash.com/@miklevasilyev?utm_source=medium&amp;utm_medium=referral">Mikhail Vasilyev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have ever worked with React, you probably had used the create-react-app (<a href="https://create-react-app.dev/">https://create-react-app.dev/</a>) at some point. This post will cover only part of generating a configured and ready-to-use folder. The init command.</p><blockquote>Before I start, I’m going to warn you that I’m going to use patterns like <em>Promise Chain</em>, so I recommend looking at this link <a href="https://developers.google.com/web/fundamentals/primers/promises?hl=en">https://developers.google.com/web/fundamentals/primers/promises?hl=en</a> if you are not familiar with it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*brT9EkUaUQQIJPRa" /><figcaption>Photo by <a href="https://unsplash.com/@theluckyneko?utm_source=medium&amp;utm_medium=referral">The Lucky Neko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To generate our CLI, we will use Gluegun, a toolkit made in typescript that helps us create node command-line programs.</p><pre>$ npx gluegun new create-react-app-from-zero</pre><pre># choose TypeScript</pre><pre>$ cd create-react-app-from-zero</pre><pre># and link your new executable</pre><pre>$ yarn link</pre><pre># and run it!</pre><pre>$ create-react-app-from-zero help</pre><pre># Sometimes, depending on your configuration, the yarn link may not work, but no problem, just run ./bin/create-react-app-from-zero when you want to execute the commands.</pre><p>Gluegun is a framework with much functionality. It comes with several configuration files in the project. As this CLI will only have the init command, we will delete everything and create a file called init.ts inside src/commands.</p><p>Delete the files that we are not going to use with the following commands and create the init.ts file:</p><pre>rm -rf src/templates<br>rm -rf src/extensions<br>rm src/types.ts<br>rm src/commands/*<br>touch src/commands/init.ts</pre><p>Our folder should be like this now:</p><pre>src<br>├── cli.ts<br>└── commands<br>    └── init.ts</pre><p>Now you can copy the code below and paste it into the init.ts file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b6f99854fc99292989b948ec3749635/href">https://medium.com/media/0b6f99854fc99292989b948ec3749635/href</a></iframe><p>Try to run the init command now.</p><pre>$ create-react-app-from-zero init</pre><pre>base command created with success</pre><p>When creating the init.ts file inside src, we tell Gluegun that this file will be a CLI command.</p><p>We can now declare a set of functions, types, and variables to help us in the rest of the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a96c71bf13f81449c54382fb702722/href">https://medium.com/media/32a96c71bf13f81449c54382fb702722/href</a></iframe><ul><li><strong>ExtractPromiseGeneric:</strong> will help us to extract the types encapsulated in promises, for example, if we have:</li></ul><pre>type PromiseString = Promise&lt;string&gt;</pre><p>we can extract the string type from the promise with ExtractPromiseGeneric as follows:</p><pre>type PromiseString = Promise&lt;string&gt;</pre><pre>type StringWithoutPromise = ExtractPromiseGeneric&lt;PromiseString&gt;</pre><ul><li><strong>currentDirectory:</strong> Similar to __dirname, which tells us which directory the script resides in, currentDirectory tells us in which directory the command was executed.</li><li><strong>throwErrorandCatchError:</strong> As the whole script was made with the promise chain in mind, I created these two functions to be able to handle the errors better, separating the expected errors from the errors of internal libraries, thus being able to give more informative feedback to the user.</li></ul><p>Now we have the setup ready, and we can start building our CLI.</p><p>Before going into action, let’s list everything that our CLI needs to do to imitate the CLI command and immediately turn that list into functions.</p><ol><li>Check that there isn’t a folder or file with the name passed in the current directory.</li><li>Check if we should use the standard template or one given by the user.</li><li>Search the template URL in pm.</li><li>Download the template to a temporary directory</li><li>Copy the files of interest to the project directory.</li><li>Delete the temporary directory.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bee3ad61011abfcfd219e101e675ff5/href">https://medium.com/media/2bee3ad61011abfcfd219e101e675ff5/href</a></iframe><h3>Check that that there isn’t a folder or file with the name passed in the current directory</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b44c305d4ada2b0ff255d66fe312be0a/href">https://medium.com/media/b44c305d4ada2b0ff255d66fe312be0a/href</a></iframe><blockquote>Deviating a little from the point of this post, note the name of my role. A tip I can give you is to worry about putting as much meaning in the function name instead of worrying about the size of the variable/function name, in the end, who will read the code is a person and not a machine.</blockquote><p>In this function, we are using the fs-extra library, for now, believe me, that creating/copying/removing directories/files is better than the standard node fs.</p><p>This function has two interesting points that will be repeated throughout our code, both linked by promise chain. The first point is that the “parent” function returns a promise through async (I believe the right term would be a higher-order function). I used this method to facilitate the function’s call in the final code because instead of calling:</p><pre>starting()<br>  .then(() =&gt; checkIfNameExistsInDirectory(appDirectory))<br>  .then(/** more core **/)</pre><p>we can write:</p><pre>starting()<br>  .then(checkIfNameExistsInDirectory(appDirectory))<br>  .then(/** more core **/)</pre><p>The difference is minimal, but if you want to know more about functions that call functions, you can take a look at <a href="https://stackoverflow.com/questions/23535316/higher-order-functions-in-javascript">https://en.stackoverflow.com/questions/54406/fun%C3%A7%C3%A3o-que-retorna- fun% C3% A7% C3% A3o-in-javascript</a></p><p>The second point is the creation of throwError. We use it to handle the errors within the promise chain and still, know if the error was a standard error created by us or an error thrown by some library. For example, in the above function, the expected error is an invalid name for creating the folder, and an unexpected error could be the lack of writing permission on the current directory.</p><h3>Check if we should use the standard template or one passed by the user.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d279ef550420cd8c1604efc6d931537/href">https://medium.com/media/6d279ef550420cd8c1604efc6d931537/href</a></iframe><p>This function verifies if the user passed any template name by the flag or not. The important thing here is to notice that we will always search npm for packages with the name of cra-clone-template and cra-clone-&lt;template-name&gt;-template, so we can go to the URL <a href="https://www.npmjs.com/search?q=cra-clone">https://www.npmjs.com/search?q=cra-clone</a> and see the template options that exist.</p><p>To demonstrate this post’s purposes, the project template in the cra-clone-template is the default template of the create-react-app.</p><h3>Search the template URL in npm.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7cbe4ed037646542c6dd358a25a34f5/href">https://medium.com/media/c7cbe4ed037646542c6dd358a25a34f5/href</a></iframe><p>Before I had to create my own version of create-react-app I had never heard of the command npm v &lt;package-name-in-npm&gt;. This command is used to search for a set of information about the desired package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*My84QbG0caMTvMqk.png" /></figure><p>In the image above, we see the result of npm v passing the <a href="http://twitter.com/material">@material</a>-ui/core package as an argument. But what would be the dist.tarball at the end of the command that our code is used? It’s a filter! Therefore, the output of npm v <a href="http://twitter.com/material">@material</a>-ui/core dist.tarball is the URL we need to download the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*gt1-5XEFU4ZL2rHn.png" /></figure><h3>Download the template to a temporary directory</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc0092b452b21b0fbbd3cc28c9f80d65/href">https://medium.com/media/dc0092b452b21b0fbbd3cc28c9f80d65/href</a></iframe><p>In this code snippet, we have two new packages. The tar-pack serves to deal with the packaging and unpacking of files, in this case, we will only use the unpack function to extract the downloaded content from npm. (You can see at the end of the URL that the file we are going to download is a .tgz). The other package is hyperquest, and its role in the code is downloading the package via streaming for the unpack function to unpack it.</p><h3>Copy the files of interest to the project directory.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6840832cf862f24e64bf430ab642bdec/href">https://medium.com/media/6840832cf862f24e64bf430ab642bdec/href</a></iframe><p>Remember when I said that the fs-extra library was better for our use case? We can finally see it’s power. To copy a file or folder from one place to another, pass the paths as an argument and say which configuration we want.</p><p>If we were to do this command using only the standard fs of the node we would have to do an exhaustive collection of checks. So we will let this library take care of copying what we need.</p><p>To ensure that no problems will happen when overwriting an existing file or paste in the desired folder (appDirectory) I chose to configure the copy function to break the CLI and throw an error in our face. Although step 1 of this tutorial is to check the current directory to ensure this, it is better to be safe than regretful.</p><h3>We’re done !!!</h3><p>Now run our init command and see the result,</p><pre>create-react-app-from-zero init --name teste</pre><p>The command will generate a folder with the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*lOQtkuWXcLuaF2ih.png" /></figure><p>As the cra-clone-template is the default project for the create-react-app ejected, we can enter the folder and see that the project is working. 🥳🥳</p><h3>but let’s analyze how he got…</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7796954e26f689152aab74eab3a5e5c6/href">https://medium.com/media/7796954e26f689152aab74eab3a5e5c6/href</a></iframe><blockquote>I ended up creating a more called function to be the bootsrap of the promise chain.</blockquote><p>The promise chain worked perfectly with typescript, and I believe that the most exciting thing you can take with you from this reading is precisely the structure implemented.</p><p>The code was thought to be as Type-Safe as possible, so when trying to add/remove/update any function, the developer will have to analyze the types and ensure that the chain is not broken.</p><p>That’s all, folks :)</p><p>Repositories:</p><ul><li><a href="https://github.com/itelofilho/create-react-app-from-zero">itelofilho/create-react-app-from-zero</a></li><li><a href="https://github.com/itelofilho/cra-clone-template">itelofilho/cra-clone-template</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8c4384ebe1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando a sua biblioteca de UI para react native, react web e FramerX do zero]]></title>
            <link>https://itelonog.medium.com/criando-a-sua-biblioteca-de-ui-para-react-native-react-web-e-framerx-do-zero-8205a63cbd15?source=rss-88b68dbffa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/8205a63cbd15</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-web]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Itelo Nogueira]]></dc:creator>
            <pubDate>Sun, 10 May 2020 21:12:30 GMT</pubDate>
            <atom:updated>2020-05-10T21:12:30.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*881om8-nGiwn0Ikk" /><figcaption>Photo by <a href="https://unsplash.com/@raouldroog?utm_source=medium&amp;utm_medium=referral">Raoul Droog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Isto vai ser uma série na qual vou mostrar o passo a passo de criar uma biblioteca do zero de UI utilizando tecnologias como o storybook, react-native, react-native-web, FramerX, testes unitários e se tudo der certo regressão visual. Neste primeiro Artigo irei cobrir apenas parte do setup.</p><h3>Antes de começar</h3><p>Todos os nossos componentes vão seguir a seguinte estrutura</p><pre>ComponentName<br>├── index.ts                <br>├── ComponentName.tsx       # código do componente<br>├── ComponentName.story.js  # código do storybook do componente<br>└── ComponentName.test.js   # código de teste unitário do componente</pre><p>Escolhi essa estrutura, pois acredito que a longo prazo ela é melhor para manter projetos em react, você pode usar a que você preferir, mas recomendo pelo menos experimentar ela.</p><p>Recomendo também que você use o cheatsheets abaixo quando estiver desenvolvendo em typescript para react</p><p><a href="https://github.com/typescript-cheatsheets/react-typescript-cheatsheet">typescript-cheatsheets/react-typescript-cheatsheet</a></p><h3>Setup do projeto</h3><p>Beleza, vamos iniciar utilizando o comando padrão do CLI do react-native abaixo</p><pre>$ npx react-native init mycooluilib --template typescript</pre><p>Não sei dizer o motivo, mas toda vez que utilizo o template do typescript, o CLI se confunde e acaba criando uma pasta chamada template dentro do projeto que acabamos de criar, ficando assim</p><pre>mycooluilib<br>├── __tests__<br>├── ios<br>│   └── ios files...<br>├── android<br>│   └── android files<br>├── template<br>│   ├── __tests__<br>│   ├── ios<br>│   │   └── ios files...<br>│   ├── android<br>│   │   └── android files<br>│   └── other files ...<br>└── other files ...</pre><p>Para corrigir esse pequeno problema vamos ter que rodar os comandos abaixo</p><pre># primeiro vamos mover o template (que é pasta de configurada correta) para outro local<br>$ mv mycooluilib/template /tmp/mycooluilib</pre><pre># agora podemos apagar a pasta &quot;defeituosa&quot;<br>$ rm -rf mycooluilib</pre><pre># e por ultimo vamos mover a pasta template para o local correto<br>$ mv /tmp/mycooluilib mycooluilib</pre><pre># vamos aproveitar para apagar a pasta __tests__ que não iremos usar<br>$ cd mycooluilib<br>$ rm -rf __tests__</pre><pre># e por ultimo vamos instalar os pacotes do npm (eu prefiro usar o yarn, mas você utilizar o npm sem problemas com, npm install)<br>$ yarn</pre><p>Se tudo deu certo, o nosso diretório deve estar assim agora</p><pre>mycooluilib<br>├── ios<br>│   └── ios files...<br>├── android<br>│   └── android files<br>├── node_modules<br>│   └── node_modules files<br>├── .buckconfig<br>├── .eslintrc.js<br>├── .gitattributes<br>├── .gitignore<br>├── .prettierrc.js<br>├── .watchmanconfig<br>├── App.tsx<br>├── app.json<br>├── babel.config.js<br>├── index.js<br>├── metro.config.js<br>├── package.json<br>├── tsconfig.json<br>└── yarn.lock</pre><p>Vamos rodar as linhas de comando abaixo somente para garantir que esta tudo funcionando corretamente</p><pre># em um terminal execute<br>$ yarn start</pre><pre># em outro terminal execute<br>$ yarn run ios/android</pre><p>Se tudo estive correto, teremos o emulador/simulador igual a imagem abaixo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*soc3E4eXu74vcvs3qHnQ2g.png" /></figure><h4>Quase lá…</h4><p>Antes de dizer que terminamos o setup, gostaria de cobrir também a opção de usar caminho absoluto ao invés de relativo, afinal ninguém merece ter que ficar digitando ../ toda hora.</p><p>Para isso precisamos adicionar o pacote babel-plugin-module-resolver</p><pre>$ yarn add --dev babel-plugin-module-resolver</pre><p>depois precisamos editar o arquivo babel.config.js e deixar igual ao código abaixo</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f57f1b253f79cbafd9bf7e7fb3c876/href">https://medium.com/media/c5f57f1b253f79cbafd9bf7e7fb3c876/href</a></iframe><p>e por último temos que editar o arquivo tsconfig.json e adicionar as seguintes opções ao compilador</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>     <em>/* Base directory to resolve non-absolute module names. */<br>     </em>&quot;baseUrl&quot;: &quot;./&quot;,<br>     &quot;paths&quot;: {<br>        &quot;@mycooluilib/*&quot;: [&quot;./src/*&quot;]<br>     },<br>     // other compiler options<br>   }<br>}</pre><h4>Adicionando Storybook</h4><p>Vamos utilizar o storybook para desenvolver os componentes da nossa biblioteca, rodando a linha de comando abaixo iniciaremos o setup do storybook</p><pre>$ npx -p @storybook/cli sb init --type react_native</pre><p>ele vai perguntar se queremos instalar as dependências, basta aperta y para sim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*ChDhVJ3nph13dU4FhX0r_g.png" /></figure><p>A estrutura da pasta storybook deve estar igual a abaixo</p><pre>$ tree storybook<br>storybook<br>├── addons.js<br>├── index.js<br>├── rn-addons.js<br>└── stories<br>    ├── Button<br>    │   ├── index.android.js<br>    │   └── index.ios.js<br>    ├── CenterView<br>    │   ├── index.js<br>    │   └── style.js<br>    ├── Welcome<br>    │   └── index.js<br>    └── index.js</pre><pre>4 directories, 9 files</pre><p>Como a instalação padrão vem alguns arquivos que não iremos utilizar, vamos deletar eles</p><pre>rm -rf storybook/stories</pre><p>Agora falta alterar o arquivo index.js na root do projeto para que ele leia asconfigurações do storybook. Para isso, você deve alterar a linha 6 e importar a pastastorybook ao inves do arquivo App.ts, deixando-o igual o código abaixo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/061c6a751d4666f451b77c649aaf6806/href">https://medium.com/media/061c6a751d4666f451b77c649aaf6806/href</a></iframe><h4>Uma última configuração no setup do storybook</h4><p>Se você já usou o storybook alguma vez na vida, sabe como é chato ter que ficar atualizando as configurações do storybook toda vez que criamos algum componente novo, para resolver isso vamos adicionar uma biblioteca chamda react-native-storybook-loader , que vai acabar com esse trabalho braçal de uma vez por todas.</p><pre>yarn add --dev react-native-storybook-loader</pre><p>Agora vamos editar o nosso package.json para colocar o comando que vai ser responsável por adicionar os .story ao storybook sempre que iniciarmos ele.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;prestorybook&quot;: &quot;rnstl --pattern &#39;src/**/*.story.tsx&#39;&quot;<br>  }<br>}</pre><p>O parâmetro pattern serve para dizer o padrão dos arquivos a serem observados. Pode ser um arquivo específico ou qualquer glob válido, no nosso caso é NomeDoComponete.story.tsx .</p><p>Para finalizar o processo de instalação do storybook vamos editar o arquivo index.ts dentro da pasta storybook e trocar a configuração (linha 8) para que ela carregue os stories gerados pelo loader que acabamos de adicionar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4febc17471217e024771cfeb5ce733/href">https://medium.com/media/cf4febc17471217e024771cfeb5ce733/href</a></iframe><h3>Adicionando a biblioteca de testes unitarios</h3><p>Neste projeto vamos a biblioteca react-native-testing-library para realizar os nossos testes unitários. Para instalar basta rodar o comando abaixo</p><pre>yarn add --dev react-native-testing-library</pre><h3>Adicionando Nosso Primeiro Componente</h3><p>Finalmente chegamos na parte legal. Para não perdermos muito o foco desse artigo, que é o setup, vamos criar apenas um componente básico para provar que todo o nosso setup esta funcionado e enviar ele para o npm. Acredito que o componente mais comum que poderíamos ter em uma biblioteca em seus estados iniciais seja o botão, por isso vamos criar um botão sem muitas features com o intuito de deixar isso para outro o segundo ou terceiro post da série.</p><p>Crie uma pasta chamada components e dentro dela crie um arquivo chamado index.ts e outra pasta chamada Button. O arquivo index.ts dentro de components vai servir para exportar todos os nossos components. A pasta Button deve estar no padrão que eu comentei la em cima.</p><p>códio index que exporta todos os componentes em src/components/index.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbacb983f63514caa3ccef4ca1659cab/href">https://medium.com/media/fbacb983f63514caa3ccef4ca1659cab/href</a></iframe><p>códio index que exporta o Botão em src/components/Button/index.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97f3fd77297afab46d1af7240428cef8/href">https://medium.com/media/97f3fd77297afab46d1af7240428cef8/href</a></iframe><p>código do botão em src/components/Button/Button.tsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eee9c9a2bb6a3adf82af81ee638b884/href">https://medium.com/media/1eee9c9a2bb6a3adf82af81ee638b884/href</a></iframe><p>código do story do botão em src/components/Button/Button.story.tsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/879d214e779590a88ac4cd74ee452220/href">https://medium.com/media/879d214e779590a88ac4cd74ee452220/href</a></iframe><p>E por fim, abaixo temos o código de teste do botão, lembrando que o meu foco aqui não é demonstrar as técnicas de teste, então vou testar apenas a prop color do botão que acabei de criar.</p><p>código de teste do botão em src/components/Button/Button.test.tsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ee237a6a81ed37d1be814d06656fcf/href">https://medium.com/media/56ee237a6a81ed37d1be814d06656fcf/href</a></iframe><p>A estrutura da pasta src deve estar assim</p><pre>src<br>└── components<br>    ├── Button<br>    │   ├── Button.story.tsx<br>    │   ├── Button.test.tsx<br>    │   ├── Button.tsx<br>    │   └── index.ts<br>    └── index.ts</pre><h3>Resultados…</h3><p>Finalmente podemos rodar o projeto e ver o resultado do nosso trabalho. Para isso vamos precisar abrir novamente dois terminais e rodar os comandos abaixo</p><pre># em um terminal execute<br>$ yarn storybook</pre><pre># em outro terminal<br>$ yarn ios/android</pre><p>O resultado vai ser algo parecido com o do gif abaixo. Repare que é possível controlar qual elemento você queremos testar/visualizar usando o browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*bhvXPdy1a4wCHnXY.gif" /></figure><p>Para testar os nossos componentes bastar rodar o comando abaixo.</p><pre>yarn test</pre><p>A saída desse comando vai ser igual a imagem abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*W7FNH9M419MbLBWughmg8A.png" /></figure><h3>Publicando no NPM</h3><p>Chegou a tão temida hora de publicarmos no npm. Para alcançar este objetivo, neste primeiro artigo vamos apenas “compilar” (transpilar) a nossa biblioteca usando o próprio typescript e depois envia-la ao npm.</p><p>Primeiro precisaremos adicionar um arquivo chamado tsconfig.prod.json na raiz do projeto que será responsável por alterar as opções de compilação na hora de gerar a versão que irá de fato para o npm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2503b1e575c9dcfc778058c726acaac9/href">https://medium.com/media/2503b1e575c9dcfc778058c726acaac9/href</a></iframe><p>Agora vamos adicionar dois scripts ao package.json que farão o processo de build</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;prebuild&quot;: &quot;rm -rf build&quot;,<br>    &quot;build&quot;: &quot;yarn tsc -p tsconfig.prod.json&quot;,<br>  }<br>}</pre><p>Podemos finalmante rodar o comando abaixo para compilar a nossa biblioteca</p><pre>$ yarn build</pre><p>Tendo como resultado algo parecido com a figura abaixo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8qlIDyqjvD3m4yaumFx_w.png" /></figure><p>Agora vamos adicionar duas tags ao package.json,main e types. A primeira irá dizer qual código o javascript deverá carregar ao ser chamado na hora da importação. A tag types tem a mesma função da main, só que para os tipos do typescript.</p><pre>{<br>  // package.json<br>  &quot;main&quot;: &quot;build/src/components/index.js&quot;,<br>  &quot;types&quot;: &quot;build/src/components/index.d.ts&quot;,<br>}</pre><p>E por fim podemos publicar a nossa humilde biblioteca com o comando abaixo.</p><pre>npm publish</pre><h3>Terminamos</h3><p>Nesse momento você já pode baixar a sua biblioteca em outros projetos e ser feliz. Espero que a leitura tenha contribuído no seu conhecimento e vou deixar os links do repositório e do npm caso você queira ver algo neles.</p><ul><li><a href="https://github.com/itelofilho/mycooluilib">itelofilho/mycooluilib</a></li><li><a href="https://www.npmjs.com/package/mycooluilib2">mycooluilib2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8205a63cbd15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recriando o comando init do create-react-app]]></title>
            <link>https://itelonog.medium.com/recriando-o-comando-init-do-create-react-app-35e58b0083f0?source=rss-88b68dbffa99------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e58b0083f0</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Itelo Nogueira]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 21:53:19 GMT</pubDate>
            <atom:updated>2020-04-27T13:44:24.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iChgZIJE-0tw6j6d" /><figcaption>Photo by <a href="https://unsplash.com/@joeyc?utm_source=medium&amp;utm_medium=referral">Joe Caione</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Se você já trabalhou alguma vez com React provavelmente usou o create-react-app (<a href="https://create-react-app.dev/">https://create-react-app.dev/</a>) em algum momento. Nesse post eu vou cobrir apenas a parte de gerar uma pasta configurada e pronta para o uso, o comando init (sem os scripts com webpack e etc.).</p><blockquote>Antes de começar vou logo avisando que vou utilizar padrões como Promise Chain, então recomendo dar uma olhada nesse link <a href="https://developers.google.com/web/fundamentals/primers/promises?hl=pt-br">https://developers.google.com/web/fundamentals/primers/promises?hl=pt-br</a> caso não tenha familiaridade com isso.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WtTs3h6_j-X8SebL" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">Charles</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Para gerar o nosso CLI vamos usar o Gluegun, um toolkit feito em typescript que nos ajuda a criar programas para linha de comando em node.</p><pre>$ npx gluegun new create-react-app-from-zero</pre><pre># choose TypeScript</pre><pre>$ cd create-react-app-from-zero</pre><pre># and link your new executable</pre><pre>$ yarn link</pre><pre># and run it!</pre><pre>$ create-react-app-from-zero help</pre><pre># As vezes, dependendo da sua configuração o yarn link pode não funcionar, mas não tem problema, basta rodar ./bin/create-react-app-from-zero quando quiser executar os comandos.</pre><p>O Gluegun é framework com bastantes funcionalidades, ele vem com diversos arquivos de configuração no projeto, como esse CLI só vai ter o comando init vamos apagar tudo e criar um arquivo chamado init.ts dentro de src/commands .</p><p>Comandos para apagar o que não vamos e criar o arquivo init.ts:</p><pre>rm -rf src/templates<br>rm -rf src/extensions<br>rm src/types.ts<br>rm src/commands/*<br>touch src/commands/init.ts</pre><p>Árvore de arquivo da pasta src :</p><pre>src<br>├── cli.ts<br>└── commands<br>    └── init.ts</pre><p>Agora você pode copiar o código abaixo e colá-lo dentro do arquivo init.ts .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc44892a2c71508e4ed955e7b76181e3/href">https://medium.com/media/bc44892a2c71508e4ed955e7b76181e3/href</a></iframe><p>Tente executar o comando init agora.</p><pre>$ create-react-app-from-zero init</pre><pre>base command created with success</pre><p>Beleza! Ao criar o arquivo init.ts dentro de src já estamos dizendo para o Gluegun que este arquivo vai ser um comando do CLI.</p><p>Agora já podemos declarar um conjunto de funções, tipos e variáveis que vão nos ajudar no restante do código.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71114ccab701127b76b223bc058032cb/href">https://medium.com/media/71114ccab701127b76b223bc058032cb/href</a></iframe><ul><li><strong>ExtractPromiseGeneric: </strong>vai nos ajudar a extrair os tipos encapsulados em promises, por exemplo, se tivermos:</li></ul><pre>type PromiseString = Promise&lt;string&gt;</pre><p>podemos extrair o tipo string da promise com o <strong>ExtractPromiseGeneric </strong>da seguinte forma:</p><pre>type PromiseString = Promise&lt;string&gt;</pre><pre>type StringWithoutPromise = ExtractPromiseGeneric&lt;PromiseString&gt;</pre><ul><li><strong>currentDirectory: </strong>Semelhante ao __dirname que nos diz qual o diretório em que script reside, o currentDirectory nos diz em qual diretório o comando foi executado.</li><li><strong>throwError </strong>e<strong> CatchError: </strong>Como todo o script foi feito pensando em promise chain, criei essas duas funções para poder tratar melhor os erros, separando os erros esperados dos erros de bibliotecas internas, podendo assim, dá um feedback mais informativo para o usuário.</li></ul><p>UFA!!! Agora já temos o setup todo pronto e podemos começar a construir o nosso CLI.</p><p>Antes de partir para a ação, vamos listar tudo que o nosso cli precisa fazer para imitar o comando cli, e logo em seguida transformar essa lista em funções.</p><ol><li>Verificar se já não existe uma pasta ou arquivo com o nome passado no diretório atual.</li><li>Verificar se devemos usar o template padrão ou algum passado pelo usuário.</li><li>Buscar no npm a URL do template.</li><li>Baixar o template para um diretório temporario</li><li>Copiar os arquivos de interesse para o diretório do projeto.</li><li>Apagar o diretório temporário.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b1b98a8e393176312d3fd282a28190/href">https://medium.com/media/40b1b98a8e393176312d3fd282a28190/href</a></iframe><h3>Verificar se já não existe uma pasta or arquivo com o nome passado no diretório atual</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5de738871aa3b18787c9be89f9d5ea5f/href">https://medium.com/media/5de738871aa3b18787c9be89f9d5ea5f/href</a></iframe><blockquote>Desvirtuando um pouco do tema deste post, repare no nome da minha função. Uma dica que eu posso dar para vocês é que se preocupem em por o máximo de significado no nome da função ao invés de se preocuparem com o tamanho do nome da variável/função, no final quem vai ler o código é uma pessoa e não uma maquina.</blockquote><p>Nessa função estamos utilizando a biblioteca fs-extra , por enquanto basta acreditar em mim que para trabalhar com criação/copia/remoção de diretórios/arquivos ela é melhor que o fs padrão do node.</p><p>Acredito que essa função apresenta dois pontos interessantes que vão se repetir durante todo o nosso código, ambos ligados com promise chain. O primeiro ponto é que a função “pai” retorna uma promise através do async (acredito que o termo certo seria higher order function), utilizei deste método para facilitar a chamada da função no código final, pois ao invés de chamarmos:</p><pre>starting()<br>  .then(() =&gt; checkIfNameExistsInDirectory(appDirectory))<br>  .then(/** more core **/)</pre><p>podemos escrever:</p><pre>starting()<br>  .then(checkIfNameExistsInDirectory(appDirectory))<br>  .then(/** more core **/)</pre><p>A diferença é pouca, mas se quiser saber mais sobre funções que chamam funções você pode dar uma olhada em: <a href="https://pt.stackoverflow.com/questions/54406/fun%C3%A7%C3%A3o-que-retorna-fun%C3%A7%C3%A3o-em-javascript">https://pt.stackoverflow.com/questions/54406/fun%C3%A7%C3%A3o-que-retorna-fun%C3%A7%C3%A3o-em-javascript</a></p><p>O segundo ponto é a criação da throwError, ela vai ser usada para que eu possa tratar os errors dentro da promise chain e ainda saiba quando foi um erro esperado ou um erro de alguma biblioteca que utilizei. Na função acima por exemplo, o erro esperado é um nome inválido para criação da pasta e um erro inesperado poderia ser a falta de permissão de escrita no diretório atual.</p><h3>Verificar se devemos usar o template padrão ou algum passado pelo usuário.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a455525d54c45ec2a1f86391171acb40/href">https://medium.com/media/a455525d54c45ec2a1f86391171acb40/href</a></iframe><p>Essa função verificar se o usuário passou algum nome de template pela flag ou não. O importante aqui é reparar que vamos sempre buscar no npm por pacotes com o nome de cra-clone-template e cra-clone-&lt;template-name&gt;-template, então podemos ir na url <a href="https://www.npmjs.com/search?q=cra-clone">https://www.npmjs.com/search?q=cra-clone</a> e ver as opções de template que existem.</p><blockquote>Para fins de demonstração desse post o projeto que esta como template no cra-clone-template é o template padrão do create-react-app ejetado.</blockquote><h3>Buscar no npm a URL do template.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e91773af99b7b49ba1eb4ecd32931542/href">https://medium.com/media/e91773af99b7b49ba1eb4ecd32931542/href</a></iframe><p>A função execSync serve para que consigamos executar um comando do shell. O mais relevante aqui é o comando que ele está executando, antes de ter que criar a minha versão do create-react-app eu nunca tinha ouvido falar do comando npm v &lt;nome-do-pacote-no-npm&gt; . Este comando serve para buscar um conjunto de informações sobre o pacote desejado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*aKlbIjziY5xTx43E8JYVxw.png" /></figure><p>Na imagem acima vemos o resultado de executar o npm v passando o pacote @material-ui/core como argumento. Mas o que seria o dist.tarball no final do comando que é utilizado nosso código? É um filtro! Logo, o output de npm v @material-ui/core dist.tarball é a url que precisamos para baixar o projeto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*krvXk1igdoRmJEHNUsvE3g.png" /></figure><h3>Baixar o template para um diretório temporario</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5bef34f5bac6af691d0b7180b85a22c/href">https://medium.com/media/b5bef34f5bac6af691d0b7180b85a22c/href</a></iframe><p>Nesse trecho do código temos dois novos pacotes. O tar-pack serve para lidar com o “empacotamento” e “desempacotamento” de arquivos, no caso vamos usar apenas a função unpack para extrair o conteúdo baixado do npm. (Você pode observar no final da URL que o arquivo que vamos baixar é um .tgz ). O outro pacote é o hyperquest , e o papel dele no código é de fato baixar o pacote via streamming para a função unpack descompacta-lo.</p><h3>Copiar os arquivos de interesse para o diretório do projeto.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5955bc2a37ccfd46bfd1799a0af0a040/href">https://medium.com/media/5955bc2a37ccfd46bfd1799a0af0a040/href</a></iframe><p>Lembra que falei que a biblioteca fs-extra era melhor para o nosso caso de uso? Finalmente poderemos ver ela em ação. Para copiar um arquivo ou pasta de um lugar para o outro basta passar como argumento os caminhos e dizer qual a configuração queremos. Se fossemos fazer esse comando utilizando apenas o fs padrão do node teríamos que fazer um conjunto exaustivo de verificações, por isso vamos deixar que essa biblioteca se encarregue de copiar o que precisamos.</p><p>Com o intuito de garantir que não haja problemas de sobrescrever um arquivo ou paste existentes na pasta desejada (appDirectory) optei por configurar a função copy para quebrar o CLI e jogar um erro na nossa cara caso ela tente fazer isto. Apesar do passo 1 desse tutorial ser justamente verificar o diretório atual para garantir isso, é melhor prevenir do que remediar.</p><h3>Terminamos!!!</h3><p>Agora basta rodar o nosso comando init e ver o resultado,</p><pre>create-react-app-from-zero init --name teste</pre><p>O comando irá gerar uma pasta com a estrutura a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*UVKYShuhWn3HLlhFSbAdAQ.png" /></figure><p>Como o cra-clone-template é o projeto padrão do create-react-app ejetado, podemos entrar na pasta e ver que o projeto em react esta funcionado. 🥳🥳</p><h4>mas bora analizar como ele ficou…</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/547cbfaa5389054533b485b35270b434/href">https://medium.com/media/547cbfaa5389054533b485b35270b434/href</a></iframe><blockquote>Eu acabei criando uma função a mais chamada starting somente para ser o bootsrap da promise chain .</blockquote><h4>Bonzão!!!</h4><p>A promise chain funcionou perfeitamente com o typescript, e acredito que o mais interessante que você pode levar consigo desta leitura é justamente a estrutura que foi implementada.</p><p>O código foi pensado para ser o mais Type Safe possível, logo ao tentar adicionar/remover/atualizar qualquer função o desenvolvedor vai ter que analisar os tipos e garantir que a cadeia não seja quebrada.</p><p>Isso é tudo pessoal :)</p><p>Repositórios:</p><ul><li><a href="https://github.com/itelofilho/create-react-app-from-zero">itelofilho/create-react-app-from-zero</a></li><li><a href="https://github.com/itelofilho/cra-clone-template">itelofilho/cra-clone-template</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e58b0083f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>