<?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 Marco Martino on Medium]]></title>
        <description><![CDATA[Stories by Marco Martino on Medium]]></description>
        <link>https://medium.com/@mecmartini?source=rss-2324d5a399d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*occB25KrPw2NnwKvIqCP9Q.jpeg</url>
            <title>Stories by Marco Martino on Medium</title>
            <link>https://medium.com/@mecmartini?source=rss-2324d5a399d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:15:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mecmartini/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[Traefik http/https redirect www to non-www]]></title>
            <link>https://medium.com/soulweb-academy/traefik-http-https-redirect-www-to-non-www-925f448f9192?source=rss-2324d5a399d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/925f448f9192</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[redirect]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Marco Martino]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 17:14:43 GMT</pubDate>
            <atom:updated>2022-11-11T17:18:28.339Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting up Traefik to receive requests from both www and non-www, and redirect all of the www requests to non-www (for better SEO).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCbK8Cs28NbM6LSE8hAvgg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markkoenig?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mark König</a> on <a href="https://unsplash.com/s/photos/arrow-sign?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What are we using</h3><ul><li><a href="https://traefik.io/">Traefik v2.9</a></li><li><a href="https://hub.docker.com/r/traefik/whoami">Whoami</a></li></ul><h3>Requirements</h3><ul><li><a href="https://docs.docker.com/engine/install/ubuntu/">Docker</a></li><li><a href="https://www.notion.so/Traefik-redirect-www-to-non-www-b454e02196594d0ba863c16397d9250d">Docker Compose</a></li></ul><h3>Our mission</h3><p>In order to make this work we are going to:</p><ol><li>Setup a basic <em>Traefik</em> container</li><li>Setup the dynamic configuration on <em>Traefik</em> where to place the configuration needed for the <strong>redirect</strong></li><li>Setup the redirect <strong>middlewares</strong> (http + https) for <em>Traefik</em></li><li>Setup a <em>Whoami</em> host service to test the redirect</li></ol><h3>Setup Traefik</h3><p>In a brand new directory, let’s create the traefik.yml file:</p><pre>#traefik.yml<br>version: &#39;3.9&#39;<br><br>services:<br>  traefik:<br>    image: traefik:v2.9<br>    container_name: traefik<br>    command:<br>      - --providers.docker=true<br>      # Define Traefik entry points to port [80] for http and port [443] for https.<br>      - --entrypoints.web.address=:80<br>      - --entrypoints.websecure.address=:443<br>    restart: always<br>    networks:<br>      # Define the network on which traefik is going to operate.<br>      - web<br>    ports:<br>      # Open traefik http [80] and https [443] ports.<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>    labels:<br>      - &quot;traefik.enable=true&quot;<br><br>networks:<br>  # Define the network on which is going to operate Traefik.<br>  web:<br>    external: true</pre><h3>Setup Traefik dynamic conf</h3><p>Now, let’s create the directory traefik.d and add it to our <em>Traefik</em> service.</p><pre>#traefik.yml<br># Configure the Traefik dynamic conf directory<br>command:<br> ...<br> - --providers.file.directory=/traefik/traefik.d<br><br># Mount the dynamic conf directory on the Traefik host<br>volumes:<br> ...<br> - ./traefik.d:/traefik/traefik.d</pre><h3>Setup Traefik middlewares</h3><p>It’s time to setup our redirection!</p><p>To do that, we need to setup a couple of <em>Traefik middlewares</em> for both http and https. So, let’s create the file middlewares.yml within the folder traefik.d:</p><pre># middlewares.yml<br>http:<br>  middlewares:<br>    redirect-http-www:<br>      redirectRegex:<br>        regex: &quot;^http?://www\\.(.+)&quot;<br>        replacement: &quot;http://${1}&quot;<br>        permanent: true<br>    redirect-https-www:<br>      redirectRegex:<br>        regex: &quot;^https?://www\\.(.+)&quot;<br>        replacement: &quot;https://${1}&quot;<br>        permanent: true</pre><h3>Setup test host</h3><p>We’ll use a <em>Whoami</em> host to test the redirection. Let’s add the whoami service to our traefik.yml</p><pre>#traefik.yml<br> ...<br><br> whoami:<br>    image: traefik/whoami:latest<br>    container_name: whoami<br>    networks:<br>      - web<br>    labels:<br>      # Define traefik network to use<br>      - &quot;traefik.docker.network=web&quot;<br>      # Enable https<br>      - &quot;traefik.http.routers.whoami.tls=true&quot;<br>      # Define www and non-www host<br>      - &quot;traefik.http.routers.whoami.rule=Host(`mywhoami.com`) || Host(`www.mywhoami.com`)&quot;<br>      # Add redirect middlewares for http and https<br>      - &quot;traefik.http.routers.whoami.middlewares=redirect-http-www@file,redirect-https-www@file&quot;<br><br>...</pre><p>Finally, we just have to replace the <em>Host domains</em> with the real one and we are done!</p><pre>#traefik.yml<br>      # Replace the Host domains on this row<br>      - &quot;traefik.http.routers.whoami.rule=Host(`mywhoami.com`) || Host(`www.mywhoami.com`)&quot;</pre><h3>Run and test it!</h3><p>To run:</p><pre>docker compose network create web<br>docker compose -f traefik.yml up -d<br><br># or, for oldest docker-compose<br>docker-compose network create web<br>docker-compose -f traefik.yml up -d</pre><p>Once up, open your favorite browser and try to navigate to the <em>www</em> domain you setup just above for the whoami service, in my case they are:</p><ul><li><a href="http://mywhoami.com/"><em>http://www.mywhoami.com</em></a></li><li><a href="https://mywhoami.com/"><em>https://www.mywhoami.com</em></a></li></ul><p>If everything works as aspected, you’ll be redirect to the <em>non-www</em> domain!</p><p>You can find the whole configuration on <a href="https://github.com/mecmartini/traefik-redirect-www-to-non-www">this repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=925f448f9192" width="1" height="1" alt=""><hr><p><a href="https://medium.com/soulweb-academy/traefik-http-https-redirect-www-to-non-www-925f448f9192">Traefik http/https redirect www to non-www</a> was originally published in <a href="https://medium.com/soulweb-academy">Soulweb Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use React Router v6 with Storybook]]></title>
            <link>https://medium.com/soulweb-academy/how-to-use-react-router-v6-with-storybook-bc035ea703f?source=rss-2324d5a399d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc035ea703f</guid>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Marco Martino]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 08:44:34 GMT</pubDate>
            <atom:updated>2022-08-09T08:50:38.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObSDnutAAmiyUi_3AihTBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Etienne Girardet</a> on <a href="https://unsplash.com/s/photos/story?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Mock react-router inside your stories</h4><p>When developing components with <a href="https://reactrouter.com/">react-router</a>, you probably want them to work also inside your <a href="https://storybook.js.org/">Storybook</a> stories.</p><p>Out of the box, <em>Storybook</em> has no support for <em>react-router</em>, and you’ll see your components generating errors when you try to run them into a story.</p><p>Luckily, there is an easy fix for it, and it’s called <a href="https://storybook.js.org/addons/storybook-addon-react-router-v6"><em>Storybook Addon React Router v6</em></a><em>.</em> To make it work, you just need to install and use it as a decorator to add the <em>router</em> support for all the stories.</p><h3>How to install</h3><p>To install the <em>Addon</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dapplication%252Fx-sh%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%252523%252520for%252520Npm%25250Anpm%252520install%252520--save-dev%252520storybook-addon-react-router-v6%25250A%25250A%252523%252520for%252520Yarn%25250Ayarn%252520add%252520-D%252520storybook-addon-react-router-v6&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dapplication%25252Fx-sh%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252523%25252520for%25252520Npm%2525250Anpm%25252520install%25252520--save-dev%25252520storybook-addon-react-router-v6%2525250A%2525250A%25252523%25252520for%25252520Yarn%2525250Ayarn%25252520add%25252520-D%25252520storybook-addon-react-router-v6&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead6e01525b7906f5a5051543a4f3d94/href">https://medium.com/media/ead6e01525b7906f5a5051543a4f3d94/href</a></iframe><p>To load it on <em>Storybook</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520.storybook%25252Fmain.js%25250Amodule.exports%252520%25253D%252520%25257B%25250A%252509...%25250A%252520%252520addons%25253A%252520%25255B%25250A%252509%252509...%25252C%25250A%252509%252509%252522storybook-addon-react-router-v6%252522%25252C%25250A%252509%25255D%25252C%25250A%252509...%25250A%25257D%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520.storybook%2525252Fmain.js%2525250Amodule.exports%25252520%2525253D%25252520%2525257B%2525250A%25252509...%2525250A%25252520%25252520addons%2525253A%25252520%2525255B%2525250A%25252509%25252509...%2525252C%2525250A%25252509%25252509%25252522storybook-addon-react-router-v6%25252522%2525252C%2525250A%25252509%2525255D%2525252C%2525250A%25252509...%2525250A%2525257D%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/827894fbabe9ed42b3468ef755f22ec8/href">https://medium.com/media/827894fbabe9ed42b3468ef755f22ec8/href</a></iframe><h3>How to use it as a decorator</h3><p>To make it work, the easiest way is to add the <em>Addon</em> as a decorator to your .storybook/preview.js.</p><p>This was my initial configuration</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520.storybook%25252Fpreview.js%25250Aimport%252520MainTheme%252520from%252520%252522..%25252Fsrc%25252Fcomponents%25252Fstyles%25252FMainTheme%252522%25253B%25250Aimport%252520GlobalStyle%252520from%252520%252522..%25252Fsrc%25252Fcomponents%25252Fstyles%25252FGlobalStyle%252522%25253B%25250A%25250Aexport%252520const%252520parameters%252520%25253D%252520%25257B%25250A%252520%252520actions%25253A%252520%25257B%252520argTypesRegex%25253A%252520%252522%25255Eon%25255BA-Z%25255D.%252A%252522%252520%25257D%25252C%25250A%252520%252520controls%25253A%252520%25257B%25250A%252520%252520%252520%252520matchers%25253A%252520%25257B%25250A%252520%252520%252520%252520%252520%252520color%25253A%252520%25252F%2528background%25257Ccolor%2529%252524%25252Fi%25252C%25250A%252520%252520%252520%252520%252520%252520date%25253A%252520%25252FDate%252524%25252F%25252C%25250A%252520%252520%252520%252520%25257D%25252C%25250A%252520%252520%25257D%25252C%25250A%25257D%25253B%25250A%25250Aexport%252520const%252520decorators%252520%25253D%252520%25255B%25250A%252520%252520%2528Story%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%252520%252520%25253CMainTheme%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CGlobalStyle%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CStory%252520%25252F%25253E%25250A%252520%252520%252520%252520%25253C%25252FMainTheme%25253E%25250A%252520%252520%2529%25252C%25250A%25255D%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520.storybook%2525252Fpreview.js%2525250Aimport%25252520MainTheme%25252520from%25252520%25252522..%2525252Fsrc%2525252Fcomponents%2525252Fstyles%2525252FMainTheme%25252522%2525253B%2525250Aimport%25252520GlobalStyle%25252520from%25252520%25252522..%2525252Fsrc%2525252Fcomponents%2525252Fstyles%2525252FGlobalStyle%25252522%2525253B%2525250A%2525250Aexport%25252520const%25252520parameters%25252520%2525253D%25252520%2525257B%2525250A%25252520%25252520actions%2525253A%25252520%2525257B%25252520argTypesRegex%2525253A%25252520%25252522%2525255Eon%2525255BA-Z%2525255D.%25252A%25252522%25252520%2525257D%2525252C%2525250A%25252520%25252520controls%2525253A%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520matchers%2525253A%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520color%2525253A%25252520%2525252F%252528background%2525257Ccolor%252529%25252524%2525252Fi%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520date%2525253A%25252520%2525252FDate%25252524%2525252F%2525252C%2525250A%25252520%25252520%25252520%25252520%2525257D%2525252C%2525250A%25252520%25252520%2525257D%2525252C%2525250A%2525257D%2525253B%2525250A%2525250Aexport%25252520const%25252520decorators%25252520%2525253D%25252520%2525255B%2525250A%25252520%25252520%252528Story%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253CMainTheme%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CGlobalStyle%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CStory%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FMainTheme%2525253E%2525250A%25252520%25252520%252529%2525252C%2525250A%2525255D%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f6455ab5eba704fa3dd67f5a9aa5de/href">https://medium.com/media/24f6455ab5eba704fa3dd67f5a9aa5de/href</a></iframe><p>First, we load the <em>Addon</em> component withRouter, then we add it as a decorator</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520.storybook%25252Fpreview.js%25250A%25252F%25252F%252520Load%252520the%252520Addon%25250Aimport%252520%25257B%252520withRouter%252520%25257D%252520from%252520%2527storybook-addon-react-router-v6%2527%25253B%25250Aimport%252520MainTheme%252520from%252520%252522..%25252Fsrc%25252Fcomponents%25252Fstyles%25252FMainTheme%252522%25253B%25250Aimport%252520GlobalStyle%252520from%252520%252522..%25252Fsrc%25252Fcomponents%25252Fstyles%25252FGlobalStyle%252522%25253B%25250A%25250Aexport%252520const%252520parameters%252520%25253D%252520%25257B%25250A%252520%252520actions%25253A%252520%25257B%252520argTypesRegex%25253A%252520%252522%25255Eon%25255BA-Z%25255D.%252A%252522%252520%25257D%25252C%25250A%252520%252520controls%25253A%252520%25257B%25250A%252520%252520%252520%252520matchers%25253A%252520%25257B%25250A%252520%252520%252520%252520%252520%252520color%25253A%252520%25252F%2528background%25257Ccolor%2529%252524%25252Fi%25252C%25250A%252520%252520%252520%252520%252520%252520date%25253A%252520%25252FDate%252524%25252F%25252C%25250A%252520%252520%252520%252520%25257D%25252C%25250A%252520%252520%25257D%25252C%25250A%25257D%25253B%25250A%25250Aexport%252520const%252520decorators%252520%25253D%252520%25255B%25250A%252520%252520%25252F%25252F%252520Add%252520the%252520Addon%252520to%252520decorators%25250A%252520%252520withRouter%25252C%25250A%252520%252520%2528Story%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%252520%252520%25253CMainTheme%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cdiv%252520id%25253D%252522cgems-map-tool-app-main-container%252522%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CGlobalStyle%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CStory%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%25253C%25252FMainTheme%25253E%25250A%252520%252520%2529%25252C%25250A%25255D%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520.storybook%2525252Fpreview.js%2525250A%2525252F%2525252F%25252520Load%25252520the%25252520Addon%2525250Aimport%25252520%2525257B%25252520withRouter%25252520%2525257D%25252520from%25252520%252527storybook-addon-react-router-v6%252527%2525253B%2525250Aimport%25252520MainTheme%25252520from%25252520%25252522..%2525252Fsrc%2525252Fcomponents%2525252Fstyles%2525252FMainTheme%25252522%2525253B%2525250Aimport%25252520GlobalStyle%25252520from%25252520%25252522..%2525252Fsrc%2525252Fcomponents%2525252Fstyles%2525252FGlobalStyle%25252522%2525253B%2525250A%2525250Aexport%25252520const%25252520parameters%25252520%2525253D%25252520%2525257B%2525250A%25252520%25252520actions%2525253A%25252520%2525257B%25252520argTypesRegex%2525253A%25252520%25252522%2525255Eon%2525255BA-Z%2525255D.%25252A%25252522%25252520%2525257D%2525252C%2525250A%25252520%25252520controls%2525253A%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520matchers%2525253A%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520color%2525253A%25252520%2525252F%252528background%2525257Ccolor%252529%25252524%2525252Fi%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520date%2525253A%25252520%2525252FDate%25252524%2525252F%2525252C%2525250A%25252520%25252520%25252520%25252520%2525257D%2525252C%2525250A%25252520%25252520%2525257D%2525252C%2525250A%2525257D%2525253B%2525250A%2525250Aexport%25252520const%25252520decorators%25252520%2525253D%25252520%2525255B%2525250A%25252520%25252520%2525252F%2525252F%25252520Add%25252520the%25252520Addon%25252520to%25252520decorators%2525250A%25252520%25252520withRouter%2525252C%2525250A%25252520%25252520%252528Story%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253CMainTheme%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cdiv%25252520id%2525253D%25252522cgems-map-tool-app-main-container%25252522%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CGlobalStyle%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CStory%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FMainTheme%2525253E%2525250A%25252520%25252520%252529%2525252C%2525250A%2525255D%2525253B&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e62e9fdfb7c8c4e8af3234f2cadb36/href">https://medium.com/media/e8e62e9fdfb7c8c4e8af3234f2cadb36/href</a></iframe><p>Make sure to restart your <em>Storybook</em> and we are done!</p><h3>Additional configuration</h3><p>The <em>Addon</em> allows for additional configurations that you can add as a global default on .storybook/preview.js</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D...%25250A%25250Aexport%252520const%252520parameters%252520%25253D%252520%25257B%25250A%252520%252520...%25252C%25250A%252509reactRouter%25253A%252520%25257B%25250A%252509%252509routePath%25253A%252520%2527%25252Fmyroute%2527%25252C%25250A%252520%252520%252520%252520...%25252C%25250A%252520%252520%25257D%25250A%25257D%25253B%25250A%25250A...&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D...%2525250A%2525250Aexport%25252520const%25252520parameters%25252520%2525253D%25252520%2525257B%2525250A%25252520%25252520...%2525252C%2525250A%25252509reactRouter%2525253A%25252520%2525257B%2525250A%25252509%25252509routePath%2525253A%25252520%252527%2525252Fmyroute%252527%2525252C%2525250A%25252520%25252520%25252520%25252520...%2525252C%2525250A%25252520%25252520%2525257D%2525250A%2525257D%2525253B%2525250A%2525250A...&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/348e0f16d87affe7c49d98f48fe71863/href">https://medium.com/media/348e0f16d87affe7c49d98f48fe71863/href</a></iframe><h3>Related links</h3><ul><li><a href="https://storybook.js.org/addons/storybook-addon-react-router-v6">https://storybook.js.org/addons/storybook-addon-react-router-v6</a></li><li><a href="https://chestozo.medium.com/how-to-mock-location-inside-storybook-stories-76a7c0705354">https://chestozo.medium.com/how-to-mock-location-inside-storybook-stories-76a7c0705354</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc035ea703f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/soulweb-academy/how-to-use-react-router-v6-with-storybook-bc035ea703f">How to use React Router v6 with Storybook</a> was originally published in <a href="https://medium.com/soulweb-academy">Soulweb Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily build and publish a React / Typescript component library package to Npm using Storybook and…]]></title>
            <link>https://medium.com/soulweb-academy/easily-build-and-publish-a-react-typescript-component-library-package-to-npm-using-storybook-and-4836d4f700b6?source=rss-2324d5a399d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4836d4f700b6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Marco Martino]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 17:52:23 GMT</pubDate>
            <atom:updated>2022-07-11T14:29:22.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv21oy_8DWvA4xPI-RmRrQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kseegars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kadarius Seegars</a> on <a href="https://unsplash.com/s/photos/boxes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Easily build and publish a React / Typescript component library package to Npm using Storybook and Rollup.</h3><h4>If you have a collection of components that you would like to share and re-use in several projects, it’s very convenient to build your own library using <a href="https://storybook.js.org/">Storybook</a> and have it published on the <a href="https://docs.npmjs.com/about-npm">npm package registry</a>.</h4><p>In this guide you’ll learn the steps required to have a React/Typescript component library ready and published!</p><h3>Summary</h3><ol><li><a href="#029b">Requirements</a></li><li><a href="#ab00">Setup project with Storybook</a></li><li><a href="#1a43">Setup dependencies</a></li><li><a href="#d79c">Build Button component</a></li><li><a href="#5df9">Build Map component</a></li><li><a href="#fc85">Setup peer dependencies</a></li><li><a href="#9689">Setup library packaging with Rollup</a></li><li><a href="#e4a4">Publish the package</a></li><li><a href="#eb6f">Consume the library</a></li></ol><h3>Requirements</h3><ul><li><a href="https://nodejs.org/it/download/">Node &gt;= 14</a></li><li><a href="https://www.npmjs.com/package/create-react-app">Create React App</a></li></ul><h3>Setup project with Storybook</h3><p>Let’s init the project with create-react-app:</p><pre>npx create-react-app my-library --template typescript</pre><p>We can already install storybook:</p><pre># enter your project folder<br>cd my-library</pre><pre># install storybook<br>npx storybook init</pre><p>You can now run npm run storybook and that should boot up Storybook for you with the examples they created for you.</p><p>Once you are done playing with the example, you can go ahead and safely delete the stories folder content:</p><pre>rm -rf src/stories/*</pre><p>Finally, let’s create the components folder:</p><pre>mkdir src/components</pre><h3>Setup dependencies</h3><p>Since we are building a component library, all of the dependencies must live in dev. Open the package.json and move all dependencies in devDependencies, so that it looks like below:</p><pre>{<br>  &quot;name&quot;: &quot;my-library&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;react-scripts build&quot;,<br>    &quot;test&quot;: &quot;react-scripts test&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;,<br>    &quot;storybook&quot;: &quot;start-storybook -p 6006 -s public&quot;,<br>    &quot;build-storybook&quot;: &quot;build-storybook -s public&quot;<br>  },<br>  &quot;eslintConfig&quot;: {<br>    &quot;extends&quot;: [<br>      &quot;react-app&quot;,<br>      &quot;react-app/jest&quot;<br>    ],<br>    &quot;overrides&quot;: [<br>      {<br>        &quot;files&quot;: [<br>          &quot;**/*.stories.*&quot;<br>        ],<br>        &quot;rules&quot;: {<br>          &quot;import/no-anonymous-default-export&quot;: &quot;off&quot;<br>        }<br>      }<br>    ]<br>  },<br>  &quot;browserslist&quot;: {<br>    &quot;production&quot;: [<br>      &quot;&gt;0.2%&quot;,<br>      &quot;not dead&quot;,<br>      &quot;not op_mini all&quot;<br>    ],<br>    &quot;development&quot;: [<br>      &quot;last 1 chrome version&quot;,<br>      &quot;last 1 firefox version&quot;,<br>      &quot;last 1 safari version&quot;<br>    ]<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@storybook/addon-actions&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/addon-essentials&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/addon-interactions&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/addon-links&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/builder-webpack5&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/manager-webpack5&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/node-logger&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/preset-create-react-app&quot;: &quot;^4.1.2&quot;,<br>    &quot;@storybook/react&quot;: &quot;^6.5.9&quot;,<br>    &quot;@storybook/testing-library&quot;: &quot;^0.0.13&quot;,<br>    &quot;babel-plugin-named-exports-order&quot;: &quot;^0.0.2&quot;,<br>    &quot;prop-types&quot;: &quot;^15.8.1&quot;,<br>    &quot;webpack&quot;: &quot;^5.73.0&quot;,<br>    &quot;@testing-library/jest-dom&quot;: &quot;^5.16.4&quot;,<br>    &quot;@testing-library/react&quot;: &quot;^13.3.0&quot;,<br>    &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;,<br>    &quot;@types/jest&quot;: &quot;^27.5.2&quot;,<br>    &quot;@types/node&quot;: &quot;^16.11.43&quot;,<br>    &quot;@types/react&quot;: &quot;^18.0.14&quot;,<br>    &quot;@types/react-dom&quot;: &quot;^18.0.5&quot;,<br>    &quot;react&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-scripts&quot;: &quot;5.0.1&quot;,<br>    &quot;typescript&quot;: &quot;^4.7.4&quot;,<br>    &quot;web-vitals&quot;: &quot;^2.1.4&quot;<br>  }<br>}</pre><p>Let’s update our packages:</p><pre>npm install</pre><h3>Build Button component</h3><p>We can now start to build our library components withButton. Create the file src/components/Button.tsx:</p><pre>import * as React from &quot;react&quot;;</pre><pre>type ButtonStyle = {<br>  [property: string]: string;<br>}</pre><pre>export interface ButtonProps {<br>  label: string;<br>  style: ButtonStyle;<br>  onClick: () =&gt; void;<br>}</pre><pre>const Button: React.FunctionComponent&lt;ButtonProps&gt; = ({ label, style, onClick }) =&gt; {<br>  return (<br>    &lt;button style={style} onClick={onClick}&gt;{label}&lt;/button&gt;<br>  );<br>};</pre><pre>export default Button;</pre><p>To finish, we can build our first story for Button. Create the file src/stories/Button.stories.tsx:</p><pre>import { ComponentMeta, ComponentStory } from &#39;@storybook/react&#39;;</pre><pre>import Button from &quot;../components/Button&quot;;</pre><pre>export default {<br>  title: &quot;Example/Button&quot;,<br>  component: Button,<br>} as ComponentMeta&lt;typeof Button&gt;;</pre><pre>const Template: ComponentStory&lt;typeof Button&gt; = (args) =&gt; &lt;Button {...args} /&gt;;</pre><pre>export const Default = Template.bind({});<br>Default.args = {<br>  label: &quot;Default button&quot;,<br>  style: {<br>    padding: &quot;20px&quot;,<br>    width: &quot;20em&quot;,<br>    margin: &quot;10px&quot;,<br>    color: &quot;white&quot;,<br>    fontSize: &quot;19px&quot;,<br>    cursor: &quot;pointer&quot;,<br>    border: &quot;2px solid #fecd43&quot;,<br>    background: &quot;#fecd43&quot;,<br>  },<br>  onClick: () =&gt; {<br>    console.log(&quot;You clicked the Default button&quot;);<br>  },<br>};</pre><pre>export const White = Template.bind({});<br>White.args = {<br>  label: &quot;White button&quot;,<br>  style: {<br>    ...Default.args.style,<br>    color: &quot;black&quot;,<br>    background: &quot;white&quot;,<br>    border: &quot;2px solid black&quot;,<br>  },<br>  onClick: () =&gt; {<br>    console.log(&quot;You clicked the White button&quot;);<br>  },<br>};</pre><pre>export const Small = Template.bind({});<br>Small.args = {<br>  label: &quot;Small button&quot;,<br>  style: {<br>    ...Default.args.style,<br>    padding: &quot;3px&quot;,<br>    width: &quot;10em&quot;,<br>    margin: &quot;2px&quot;,<br>    color: &quot;white&quot;,<br>    fontSize: &quot;14px&quot;,<br>  },<br>  onClick: () =&gt; {<br>    console.log(&quot;You clicked the Small button&quot;);<br>  },<br>};</pre><h3>Build Map component</h3><p>To build the Map component we need to install <a href="https://styled-components.com/">styled-components</a> and <a href="https://react-leaflet.js.org/">react-leaflet</a>. To install them:</p><pre>npm install --save-dev leaflet @types/leaflet react-leaflet @types/react-leaflet</pre><p>Create the file src/components/Map.tsx:</p><pre>import * as React from &quot;react&quot;;<br>import styled from &quot;styled-components&quot;;<br>import { MapContainer, MapContainerProps } from &quot;react-leaflet&quot;;</pre><pre>import &quot;leaflet/dist/leaflet.css&quot;;</pre><pre>interface MapWrapperProps {<br>  width?: string;<br>  height?: string;<br>  minWidth?: string;<br>  minHeight?: string;<br>}</pre><pre>const MapWrapper = styled(MapContainer)&lt;MapWrapperProps&gt;`<br>  width: ${(props) =&gt; (props.width ? props.width : &quot;100vw&quot;)};<br>  height: ${(props) =&gt; (props.height ? props.height : &quot;100vh&quot;)};<br>  min-width: ${(props) =&gt; (props.minWidth ? props.minWidth : &quot;400px&quot;)};<br>  min-height: ${(props) =&gt; (props.minHeight ? props.minHeight : &quot;400px&quot;)};<br>`;</pre><pre>interface MapElementProps {<br>  width?: string;<br>  height?: string;<br>  minWidth?: string;<br>  minHeight?: string;<br>}</pre><pre>const Map: React.FunctionComponent&lt;MapElementProps &amp; MapContainerProps&gt; = ({<br>  width,<br>  height,<br>  minWidth,<br>  minHeight,<br>  children,<br>  ...rest<br>}) =&gt; {<br>  return (<br>    &lt;MapWrapper<br>      width={width}<br>      height={height}<br>      minWidth={minWidth}<br>      minHeight={minHeight}<br>      {...rest}<br>    &gt;<br>      {children}<br>    &lt;/MapWrapper&gt;<br>  );<br>};</pre><pre>export default Map;</pre><p>A story is needed for Map too. Create src/stories/Map.stories.tsx:</p><pre>import { ComponentMeta, ComponentStory } from &#39;@storybook/react&#39;;<br>import { TileLayer } from &quot;react-leaflet&quot;;<br>import Map from &quot;../components/Map&quot;;</pre><pre>export default {<br>  title: &quot;Example/Map&quot;,<br>  component: Map,<br>} as ComponentMeta&lt;typeof Map&gt;;</pre><pre>const Template: ComponentStory&lt;typeof Map&gt; = (args) =&gt; &lt;Map {...args} /&gt;;</pre><pre>export const BasicMap = Template.bind({});<br>BasicMap.args = {<br>  width: &quot;80vw&quot;,<br>  height: &quot;80vh&quot;,<br>  bounds: [<br>    [42.5993718217880613, 1.5937492475355806],<br>    [45.9312500000000341, 7.6656250000000341]<br>  ],<br>  children: &lt;TileLayer url=&quot;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&quot; /&gt;<br>};</pre><p>You can now run again npm run storybook to boot up Storybook with the new components just created and play with it.</p><h3>Setup peer dependencies</h3><p>It’s time to add <a href="https://flaviocopes.com/npm-peer-dependencies/">peerDependencies</a> so that they can be satisfied by the client’s that they will consume our library. Let’s copy the following packaged from devDependencies to peerDependencies on package.json:</p><pre>{  <br>    ...<br>    &quot;peerDependencies&quot;: {<br>    &quot;@types/leaflet&quot;: &quot;^1.7.11&quot;,<br>    &quot;@types/react&quot;: &quot;^18.0.15&quot;,<br>    &quot;@types/react-dom&quot;: &quot;^18.0.6&quot;,<br>    &quot;@types/react-leaflet&quot;: &quot;^2.8.2&quot;,<br>    &quot;@types/styled-components&quot;: &quot;^5.1.25&quot;,<br>    &quot;leaflet&quot;: &quot;^1.8.0&quot;,<br>    &quot;react&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-leaflet&quot;: &quot;^4.0.1&quot;,<br>    &quot;styled-components&quot;: &quot;^5.3.5&quot;<br>  }<br>    ...<br>}</pre><h3>Setup library packaging with Rollup</h3><p>At this point our library is ready to be packaged and published. To compile it, we’ll make use of <a href="https://www.rollupjs.org/"><em>Rollup</em></a>.</p><blockquote>Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. This will eventually be possible natively everywhere, but Rollup lets you do it today.</blockquote><p>First, make sure your tsconfig.json looks like this:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;dist&quot;,<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;lib&quot;: [<br>      &quot;dom&quot;,<br>      &quot;dom.iterable&quot;,<br>      &quot;esnext&quot;<br>    ],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;allowSyntheticDefaultImports&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;noFallthroughCasesInSwitch&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;noEmit&quot;: false,<br>    &quot;jsx&quot;: &quot;react-jsx&quot;,<br>    &quot;declaration&quot;: true,<br>    &quot;declarationDir&quot;: &quot;dist&quot;<br>  },<br>  &quot;include&quot;: [&quot;src&quot;],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;src/stories&quot;<br>  ]<br>}</pre><p>Than we can install <em>Rollup</em>:</p><pre>npm install --save-dev rollup rollup-plugin-typescript2 @rollup/plugin-commonjs @rollup/plugin-node-resolve rollup-plugin-peer-deps-external rollup-plugin-postcss postcss</pre><p>To configure <em>Rollup</em> we need to create the rollup.config.js file:</p><pre>import peerDepsExternal from &quot;rollup-plugin-peer-deps-external&quot;;<br>import resolve from &quot;@rollup/plugin-node-resolve&quot;;<br>import commonjs from &quot;@rollup/plugin-commonjs&quot;;<br>import typescript from &quot;rollup-plugin-typescript2&quot;;<br>import postcss from &quot;rollup-plugin-postcss&quot;;</pre><pre>const packageJson = require(&quot;./package.json&quot;);</pre><pre>export default {<br>  input: &quot;src/index.tsx&quot;,<br>  output: [<br>    {<br>      file: packageJson.main,<br>      format: &quot;cjs&quot;,<br>      sourcemap: true<br>    },<br>    {<br>      file: packageJson.module,<br>      format: &quot;esm&quot;,<br>      sourcemap: true<br>    }<br>  ],<br>  plugins: [<br>    peerDepsExternal(),<br>    resolve(),<br>    commonjs(),<br>    typescript({ useTsconfigDeclarationDir: true }),<br>    postcss({<br>      extensions: [&#39;.css&#39;]<br>    })<br>  ]<br>};</pre><p>To be able to build our component library, let’s add rollup -c as build script on ourpackage.json:</p><pre>{<br>  ...<br>  &quot;scripts&quot;: {<br>    ...<br>    &quot;build&quot;: &quot;rollup -c&quot;,<br>  },<br>  ...<br>}</pre><p>Finally, let’s export all the components available on our library. Edit src/index.tsx to:</p><pre>import Button from &quot;./components/Button&quot;;<br>import Map from &quot;./components/Map&quot;;</pre><pre>export { Button, Map };</pre><p>We also need to define the files and the main entries for our library. So add the following to your package.json</p><pre>{ <br>  ...<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/index.esm.js&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;,<br>  &quot;files&quot;: [<br>    &quot;dist&quot;<br>  ],<br>    ...<br>}</pre><h3>Publish the package</h3><p>We need to make some change to our package.json. Open it, and set the following values:</p><pre>{<br>  // The name of your new package (eventually the @organisation where you wish to publish it)<br>  &quot;name&quot;: &quot;@soulweblab/my-library&quot;,<br>  // Initial version you’re going to launch<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  // Summary of what your package will do<br>  &quot;description&quot;: &quot;This library is made by a Button and a Map components.&quot;,<br>  // author: Your name, website, and (optionally) email<br>  &quot;author&quot;: &quot;Soulweb Lab&quot;,<br>  // private: We assume this is a public package<br>  &quot;private&quot;: false,<br>  ...<br>}</pre><p>Make sure you have an <a href="http://npmjs.com/">npm</a> account, than:</p><pre>npm login</pre><pre>npm publish --access public</pre><p>Remember that, having a good README, LICENSE, and any additional information, will help to promote your library. We’ll skip this for now!</p><h3>Consume the library</h3><p>It’s time to consume and test the library just published! It’s just a matter of installing and importing it.</p><p>Let’s assume we are starting a project from scratch:</p><pre># create the my-app project<br>npx create-react-app my-app --template typescript</pre><pre># enter my-app<br>cd my-app</pre><pre># install our library<br>npm install --save @soulweblab/my-library</pre><p>Edit App.tsx with the following code, to import and consume the library</p><pre>import { Button, Map } from &#39;@soulweblab/my-library&#39;;<br>import { TileLayer } from &#39;react-leaflet&#39;;<br>import type { LatLngBoundsExpression } from &#39;leaflet&#39;;</pre><pre>import &quot;leaflet/dist/leaflet.css&quot;;</pre><pre>const App = () =&gt; {<br>  const args = {<br>    label: &quot;Default button&quot;,<br>    style: {<br>      padding: &quot;20px&quot;,<br>      width: &quot;20em&quot;,<br>      margin: &quot;10px&quot;,<br>      color: &quot;lightblue&quot;,<br>      fontSize: &quot;19px&quot;,<br>      cursor: &quot;pointer&quot;,<br>      border: &quot;1px solid darkblue&quot;,<br>      background: &quot;darkblue&quot;,<br>    },<br>    onClick: () =&gt; {<br>      console.log(&quot;You clicked the Default button&quot;);<br>    },<br>  };</pre><pre>  const bounds: LatLngBoundsExpression = [<br>    [42.5993718217880613, 1.5937492475355806],<br>    [45.9312500000000341, 7.6656250000000341]<br>      ];</pre><pre>  return (<br>    &lt;div&gt;<br>        &lt;div&gt;<br>          &lt;Button label=&quot;My Library&quot; style={args.style} onClick={args.onClick} /&gt;<br>        &lt;/div&gt;</pre><pre>        &lt;div&gt;<br>          &lt;Map width=&quot;100vw&quot; bounds={bounds}&gt;<br>            &lt;TileLayer url=&quot;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&quot;/&gt;<br>          &lt;/Map&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>The very last thing is to start and test it!</p><pre>npm start</pre><p>Hopefully, everything works as aspected and you’ll see a screen with a button and a map, just like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCEeR_-LgBZyBAQW49pP3w.png" /></figure><h3>Conclusion</h3><p>Having your Storybook components published makes it easy to maintain and re-use your code.</p><p>I hope you enjoyed this guide!</p><p>You can find the complete code at <a href="https://github.com/soulweblab/build-component-library-example">https://github.com/soulweblab/build-component-library-example</a>.</p><p>The <em>npm</em> package is available at <a href="https://www.npmjs.com/package/@soulweblab/my-library">https://www.npmjs.com/package/@soulweblab/my-library</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4836d4f700b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/soulweb-academy/easily-build-and-publish-a-react-typescript-component-library-package-to-npm-using-storybook-and-4836d4f700b6">Easily build and publish a React / Typescript component library package to Npm using Storybook and…</a> was originally published in <a href="https://medium.com/soulweb-academy">Soulweb Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker local dev stack with Traefik + https + Dnsmasq + Locally-Trusted certificate for Ubuntu 20.04]]></title>
            <link>https://medium.com/soulweb-academy/docker-local-dev-stack-with-traefik-https-dnsmasq-locally-trusted-certificate-for-ubuntu-20-04-5f036c9af83d?source=rss-2324d5a399d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f036c9af83d</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[local-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Marco Martino]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 09:48:27 GMT</pubDate>
            <atom:updated>2021-03-30T11:57:25.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker local dev stack with Traefik + Https + Dnsmasq + Locally-Trusted certificate (Mkcert) for Ubuntu 20.04</h3><h4>Manage your local development containers like a pro!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cTSZkvXa-8IN14u2QuQzQ.jpeg" /><figcaption>Photo by: <a href="https://unsplash.com/@ant0ine">Antoine Petitteville</a></figcaption></figure><h3>Intro</h3><p>In this <em>tutorial</em> I want to share the Traefik configuration we use in <a href="https://soulweb.it/">our company</a> for local Docker development stacks.</p><blockquote>“We have built this configuration to have a proper local development environment to rely on, with https enabled on local custom domains through <em>locally-trusted</em> certificates.”</blockquote><p>It took us some time to actually have everything working together and in order, I hope this can make it easier for you! ;)</p><p>At the end of this tutorial you’ll find a link to the repository containing the whole configuration.</p><h3>What are we using</h3><ul><li><a href="https://traefik.io/">Traefik v2.0</a></li><li><a href="https://www.portainer.io/">Portainer</a></li><li><em>Whoami</em></li><li><a href="https://en.wikipedia.org/wiki/Dnsmasq">Dnsmasq</a></li><li><a href="https://github.com/FiloSottile/mkcert">Mkcert</a></li></ul><h3>Requirements</h3><ul><li><a href="https://docs.docker.com/engine/install/ubuntu/">Docker</a></li><li><a href="https://docs.docker.com/compose/install/">Docker Compose</a></li></ul><h3>What’s our mission</h3><p>At the end of this tutorial, we’ll hopefully have a running stack where to mount our Docker applications. The stack will run under the *.docker.localdev domain.</p><p>Traefik is going to be the proxy <em>server</em> for our applications, as well as our middleware to run those applications under https.</p><p>Portainer will help us to manage our Docker stacks.</p><p>Whoami prints out Docker <em>os</em> informations, in case we need them.</p><p>Dnsmasq is going to be in charge of routing all the request from *.docker.localdev to Traefik on localhost.</p><p>Mkcert will generate the <em>locally-trusted certificates</em> for our local <em>domain</em>.</p><h3>Setup</h3><p>In order to start our configuration, let’s create a new folder under which we can put the required files:</p><pre>$ mkdir docker</pre><h3>Traefik 2.0</h3><p>We are going to start with Traefik!</p><p>Under the new created folder, let’s create a new file called traefik.yml with the content:</p><pre>version: &#39;3&#39;</pre><pre>services:<br>  traefik:<br>    image: traefik:v2.0<br>    container_name: &quot;${DOCKER_NAME}_traefik&quot;<br>    command:<br>      - --providers.docker=true<br>      # Enable the API handler in insecure mode,<br>      # which means that the Traefik API will be available directly<br>      # on the entry point named traefik.<br>      - --api.insecure=true<br>      # Defines the path to the configuration file with the certificates list.<br>      - --providers.file.filename=/root/.config/ssl.toml<br>      # Define Traefik entry points to port [80] for http and port [443] for https.<br>      - --entrypoints.web.address=:80<br>      - --entrypoints.websecure.address=:443<br>    networks:<br>      # Define the network on which traefik is going to operate.<br>      - web<br>    ports:<br>      # Open traefik http [80] and https [443] ports.<br>      - &#39;80:80&#39;<br>      - &#39;443:443&#39;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      # Mount the configuration file with the certificates list.<br>      - ./traefik-ssl.toml:/root/.config/ssl.toml<br>      # Mount the folder containing the certificates for https.<br>      - ./certs/:/certs/<br>    labels:<br>      - &quot;traefik.enable=true&quot;<br>      # Enable Traefik API handler entrypoint on http.<br>      - &quot;traefik.http.routers.traefik-http.entrypoints=web&quot;<br>      # Define Traefik API handler http host.<br>      - &quot;traefik.http.routers.traefik-http.rule=Host(`${DOCKER_BASE_URL}`)&quot;<br>      # Define http middleware and redirection to https.<br>      - &quot;traefik.http.routers.traefik-http.middlewares=traefik-https&quot;<br>      - &quot;traefik.http.middlewares.traefik-https.redirectscheme.scheme=https&quot;<br>      # Enable Traefik API handler entrypoint on https.<br>      - &quot;traefik.http.routers.traefik.entrypoints=websecure&quot;<br>      # By default the Traefik API handler operates on the port [8080].<br>      # Define a load balancer to route the entry point to [8080].<br>      - &quot;traefik.http.services.traefik.loadbalancer.server.port=8080&quot;<br>      # Define Traefik API handler host.<br>      - &quot;traefik.http.routers.traefik.rule=Host(`${DOCKER_BASE_URL}`)&quot;<br>      # Instructs Traefik that the current router is dedicated to HTTPS requests only.<br>      - &quot;traefik.http.routers.traefik.tls=true&quot;</pre><pre>networks:<br>  web:<br>    external: true</pre><p>You can see that we are using a couple of <em>environment variables</em>, ${DOCKER_NAME} and ${DOCKER_BASE_URL}. To define those <em>variables</em>, let&#39;s create a new file called .env with the content:</p><pre>DOCKER_NAME=docker4localdev<br>DOCKER_BASE_URL=docker.localdev</pre><p>We also have to create the network <em>[web]</em> which Traefik is going to operate on:</p><pre>$ docker network create web</pre><p>To conclude this section, let’s create the needed file and folder, mounted in our Traefik <em>volumes</em> above, to later setup our <em>locally-signed</em> certificates:</p><pre>$ touch traefik-ssl.toml<br>$ mkdir certs</pre><h3>Portainer</h3><p>Now, let’s define the portainer configuration on the traefik.yml file, just after the traefik one:</p><pre>portainer:<br>    image: portainer/portainer<br>    container_name: &quot;${DOCKER_NAME}_portainer&quot;<br>    command: --no-auth -H unix:///var/run/docker.sock<br>    networks:<br>      - web<br>    volumes:<br>    - /var/run/docker.sock:/var/run/docker.sock<br>    labels:<br>      # Enable Portainer handler entrypoint on http.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer-http.entrypoints=web&quot;<br>      # Define Portainer handler http host.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer-http.rule=Host(`portainer.${DOCKER_BASE_URL}`)&quot;<br>      # Define http middleware and redirection to https.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer-http.middlewares=${DOCKER_NAME}_portainer-https&quot;<br>      - &quot;traefik.http.middlewares.${DOCKER_NAME}_portainer-https.redirectscheme.scheme=https&quot;<br>      # Enable Portainer handler entrypoint on https.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer.entrypoints=websecure&quot;<br>      # Define Portainer handler host.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer.rule=Host(`portainer.${DOCKER_BASE_URL}`)&quot;<br>      # Instructs Traefik that the current router is dedicated to HTTPS requests only.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_portainer.tls=true&quot;<br>      # Define on which network Traefik is operating.<br>      - &quot;traefik.docker.network=web&quot;</pre><h3>Whoami</h3><p>Last step, on our traefik.yml configuration, is to add the whoami configuration:</p><pre>whoami:<br>    image: containous/whoami<br>    container_name: &quot;${DOCKER_NAME}_whoami&quot;<br>    networks:<br>      - web<br>    labels:<br>      # Enable Whoami handler entrypoint on http.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami-http.entrypoints=web&quot;<br>      # Define Whoami handler http host.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami-http.rule=Host(`whoami.${DOCKER_BASE_URL}`)&quot;<br>      # Define http middleware and redirection to https.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami-http.middlewares=${DOCKER_NAME}_whoami-https&quot;<br>      - &quot;traefik.http.middlewares.${DOCKER_NAME}_whoami-https.redirectscheme.scheme=https&quot;<br>      # Enable Whoami handler entrypoint on https.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami.entrypoints=websecure&quot;<br>      # Define Whoami handler host.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami.rule=Host(`whoami.${DOCKER_BASE_URL}`)&quot;<br>      # Instructs Whoami that the current router is dedicated to HTTPS requests only.<br>      - &quot;traefik.http.routers.${DOCKER_NAME}_whoami.tls=true&quot;<br>      # Define on which network Traefik is operating.<br>      - &quot;traefik.docker.network=web&quot;</pre><h3>Dnsmasq</h3><p>We can now install and setup Dnsmasq. You are probably used to setup your local domains in the hosts file, one by one. Dnsmasq is going to make this process easier.</p><h4>Install</h4><p>Ubuntu comes with systemd-resolve, which you need to disable since it binds to port <em>[53]</em>, which will conflict with Dnsmasq port.</p><p>Run the following commands to disable the service:</p><pre>$ sudo systemctl disable systemd-resolved<br>$ sudo systemctl stop systemd-resolved</pre><p>Remove the symlinked resolv.conf file:</p><pre>$ ls -lh /etc/resolv.conf<br>$ sudo rm /etc/resolv.conf</pre><p>Create new resolv.conf file:</p><pre>$ sudo bash -c &#39;echo &quot;nameserver 127.0.0.1&quot; &gt; /etc/resolv.conf&#39;<br>$ sudo bash -c &#39;echo &quot;nameserver 1.1.1.1&quot; &gt;&gt; /etc/resolv.conf&#39;</pre><p>Install Dnsmasq:</p><pre>$ sudo apt install dnsmasq</pre><h4>Setup</h4><p>Let’s add .localdev to the dnsmasq config file:</p><pre>$ sudo bash -c &#39;echo &quot;address=/.localdev/127.0.0.1&quot; &gt;&gt; /etc/dnsmasq.conf&#39;</pre><p>Create the resolver for the added address:</p><pre>$ sudo mkdir -v /etc/resolver &amp;&amp; sudo bash -c &#39;echo &quot;nameserver 127.0.0.1&quot; &gt; /etc/resolver/localdev&#39;</pre><p>Restart Dnsmasq and network manager service:</p><pre>$ sudo systemctl restart dnsmasq</pre><h3>Locally-trusted certificates (with Mkcert)</h3><p>Mkcert is a simple tool for making locally-trusted development certificates.</p><h4>Install</h4><p>As a prerequisite, you are required to install certutil, a command-line utility that can create and modify certificate and key databases before you can install mkcert utility:</p><pre>$ sudo apt install libnss3-tools -y</pre><p>Then you can install mkcert:</p><pre>$ wget https://github.com/FiloSottile/mkcert/releases/download/v1.4.3/mkcert-v1.4.3-linux-amd64<br>$ sudo mv mkcert-v1.4.3-linux-amd64 /usr/local/bin/mkcert &amp;&amp; chmod +x /usr/local/bin/mkcert</pre><h4>Generate certificate</h4><p>First, generate a local Certificate-Authority:</p><pre>$ mkcert -install</pre><p>Then, you are ready to generate your <em>locally-trusted</em> certificate:</p><pre>$ mkcert -key-file ./certs/key.pem -cert-file ./certs/cert.pem localdev &#39;docker.localdev&#39; &#39;*.docker.localdev&#39;</pre><p>We can now add the generated certificate to the traefik-ssl.toml file:</p><pre>[tls]</pre><pre>[tls.stores]</pre><pre>[tls.stores.default]</pre><pre>[tls.stores.default.defaultCertificate]<br>certFile = &quot;/certs/cert.pem&quot;<br>keyFile = &quot;/certs/key.pem&quot;</pre><h3>Time to Build!</h3><p>Finally, we are ready to build and test our stack:</p><pre>docker-compose -f traefik.yml up -d</pre><h3>Available domains</h3><p>If everything is well done we should be able to access our stack:</p><ul><li>Traefik <em>Dashboard</em>: <a href="https://docker.localdev/">https://docker.localdev</a></li><li>Portainer: <a href="https://portainer.docker.localdev/">https://portainer.docker.localdev</a></li><li>Whoami: <a href="https://whoami.docker.localdev/">https://whoami.docker.localdev</a></li></ul><h3>Repository</h3><p>You can find the whole configuration on <a href="https://github.com/soulweblab/docker4localdev">this repository</a>.</p><p>The repository contains also a small example of a Python<em> app </em>with <a href="https://flask.palletsprojects.com/">Flask</a>, under the folder myapp, where you can find a docker-compose configuration to see how to attach your applications to the Traefik stack we just built!</p><p>Among the many combinations available to manage local webapps with custom domains, we find this as one of the most flexible and straightforward. Once you set it up, you can just add other apps to the stack and start to work on it.</p><p>Now you can look at those times when you used to add that line manually to your /etc/hosts file or skip the complaints of your browser about your fake certificate, like if you&#39;re looking at an old picture of childhood 😜.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f036c9af83d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/soulweb-academy/docker-local-dev-stack-with-traefik-https-dnsmasq-locally-trusted-certificate-for-ubuntu-20-04-5f036c9af83d">Docker local dev stack with Traefik + https + Dnsmasq + Locally-Trusted certificate for Ubuntu 20.04</a> was originally published in <a href="https://medium.com/soulweb-academy">Soulweb Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drupal and React/TypeScript components]]></title>
            <link>https://medium.com/soulweb-academy/drupal-and-react-typescript-components-577850546c4?source=rss-2324d5a399d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/577850546c4</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[drupal-8]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marco Martino]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 19:44:53 GMT</pubDate>
            <atom:updated>2021-03-13T09:38:15.763Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to easily integrate a React/TypeScript component in Drupal 8.</h4><p>Drupalwith React/TypeScript components is a great combination, and it&#39;s not so hard to make these guys work together.</p><figure><img alt="Drupal and React/TypeScript" src="https://cdn-images-1.medium.com/max/1024/1*Jl9U4i2jTmY-dJo6GjEfeA.png" /><figcaption>Drupal and React/TypeScript</figcaption></figure><p>In this article we’ll go a step further: we are going to see how to build a <a href="https://dri.es/how-to-decouple-drupal-in-2019">fully-decoupled</a> component integrated in Drupal, with React and TypeScript.</p><p>We will use some other tools along the way, one of them being Webpack, that will compile our code for the React component into a single .js file, to be easily attached to Drupal as a library. No panic, we&#39;ll talk about each of them at the right moment ;).</p><p>There are several ways to integrate them together, in this case scenario we are going to build a custom module that will host a custom field formatter with a React component interface.</p><h3>Summary</h3><ol><li><a href="#330b">Create a custom module</a></li><li><a href="#013d">Build a Drupal library</a></li><li><a href="#bbc7">Create a field formatter</a></li><li><a href="#5559">Build the React component</a></li><li><a href="#db55">Install and enjoy</a></li><li><a href="#1071">One last thing</a></li></ol><h3>Create a custom module</h3><p>First things first: We need a custom Drupal module to host all our work. You can go the old-fashioned way of <a href="https://www.drupal.org/docs/creating-custom-modules">creating a new module</a> from scratch or take the shortcut and generate the skeleton with <a href="https://drupalconsole.com/docs/es/commands/generate-module">Drupal Console</a>:</p><pre>$ drupal generate:module  --module &quot;Drupal and React&quot; --machine-name=&quot;drupal_and_react&quot;</pre><p>Choose whatever option you prefer.</p><h3>Build a Drupal library</h3><p>At this point we are ready to create a Drupal library to load the .js file of the React component that we&#39;ll build later.</p><p>To achieve this, we need to add the Drupal <a href="https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_library_info_build/8.9.x">hook</a> hook_library_info_build() to the generated drupal_and_react.module file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04efbdf4256fcb516d4b20162bbf9a9c/href">https://medium.com/media/04efbdf4256fcb516d4b20162bbf9a9c/href</a></iframe><p>Let’s have a closer look at it.</p><p>As you can see, we are defining two versions of our component, one for development and another one for production. This is useful so we can have different configurations for both environments and optimize each one for its purpose.</p><pre>$js_dev = &#39;assets/js/dist/app.bundle.js&#39;;<br>$js_prod = &#39;assets/js/build/app.bundle.js&#39;;</pre><p>We will rely on the environment variable APP_ENV to load one or the other version.</p><pre>$js_src = ( isset($_ENV[&#39;APP_ENV&#39;]) &amp;&amp; $_ENV[&#39;APP_ENV&#39;] === &#39;production&#39; ) ? $js_prod : $js_dev;<br>$js_src = file_exists($module_path . &#39;/&#39; . $js_src) ? $js_src : $js_prod;</pre><p>In the next fragment of the code, we set the options for our library and generate our library called app_bundle.</p><pre>$js = [];<br>if ( file_exists($module_path . &#39;/&#39; . $js_src) ) {<br>  $js[$js_src] = [<br>    &#39;minified&#39; =&gt; TRUE,<br>    &#39;preprocess&#39; =&gt; FALSE,<br>  ];</pre><pre>  $libraries = [<br>    &#39;app_bundle&#39; =&gt; [<br>      &#39;version&#39; =&gt; &#39;VERSION&#39;,<br>      &#39;js&#39; =&gt; $js,<br>    ],<br>  ];<br>}<br>else {<br>  throw new FileNotFoundException(<br>    $module_path . &#39;/&#39; . $js_src<br>  );<br>}</pre><pre>return $libraries;</pre><p>Note the FileNotFoundException exception at the end to cover the case that the app has never been built, neither in dev nor prod version.</p><p>Once done this, Drupal knows how to load our JS app as a library. We don’t have our app bundle file yet — we’ll work on it in a while — but first we need a way to attach our library to some Drupal content, and for this we are going to use a custom field formatter.</p><h3>Create a field formatter</h3><p>Using a field formatter to attach the library is — maybe — a little more complex than using a block or a controller, but it has the advantage to be a more flexible solution to get our React app running. Anyway, the process for any other Drupal component (block/controller/field/etc.) is the same, you need to attach the component library to the render array (as shown below).</p><p>Again, we can generate the skeleton for our field formatter with <a href="https://drupalconsole.com/docs/en/commands/generate-plugin-fieldformatter">drupal-console</a>. Set the required information as you like, we will use string as field type for this example, being it enough for our purpose.</p><pre>$ drupal generate:plugin:fieldformatter</pre><p>Now we are going to work on the viewElements() method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc80af1200bc6f8644312652ae9b52c/href">https://medium.com/media/4cc80af1200bc6f8644312652ae9b52c/href</a></iframe><p>Again, let’s dig into it.</p><p>We get some info from the entity and the field to generate a unique id for our div. This is to avoid the case that more components from different fields on the same page try to apply to the same DOM element.</p><pre>$id = $items-&gt;getEntity()-&gt;id();<br>$field_name = $this-&gt;fieldDefinition-&gt;getItemDefinition()-&gt;getFieldDefinition()-&gt;getName();<br>$wrapper_id = &#39;drupal-and-react-app-&#39; . $field_name .&#39;-&#39;. $id;</pre><pre>$build = [<br>  &#39;#markup&#39; =&gt; &#39;&lt;div id=&quot;&#39; . $wrapper_id . &#39;&quot;&gt;&lt;/div&gt;&#39;,<br>];</pre><p>Now, we can attach the library to the render array of our field formatter:</p><pre>$build[&#39;#attached&#39;][&#39;library&#39;] = [<br>  &#39;drupal_and_react/app_bundle&#39;,<br>];</pre><p>And finally we can pass the required data to our React component via Drupal settings.</p><pre>$build[&#39;#attached&#39;][&#39;drupalSettings&#39;][&#39;drupal_and_react_app&#39;][$id] = [<br>  &#39;id&#39; =&gt; $id,<br>  &#39;wrapper&#39; =&gt; $wrapper_id,<br>  &#39;content&#39; =&gt; $elements,<br>];</pre><pre>return $build;</pre><p>Our job is pretty done on the Drupal side. Yeah! 🎉 Let’s switch to our React component and play with it!</p><h3>Build the React component</h3><p><em>Make sure to have </em><a href="https://www.npmjs.com/get-npm"><em>npm</em></a><em> installed.</em></p><p>The first step will be set up the environment for our app.</p><p>In the files structure of our module, add the directory assets/js like this:</p><pre>_your_drupal_root_dir_/modules/custom/drupal_and_react/assets/js</pre><p>From inside this new created directory, run $ npm init to generate the package.json file.</p><p>There’s a bunch of dependencies we have to add now to it to be able to create our component.</p><p>React of course:</p><pre>$ npm i react react-dom</pre><p>It’s time for TypeScript support, we install the typescript package together with the types for the two React related packages we just called in:</p><pre>$ npm i --save-dev typescript @types/react @types/react-dom</pre><p>Next step is to add some configuration for TypeScript in its dedicated file called tsconfig.json that has to live in the root directory of our app.</p><p><strong>tsconfig.json</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./dist/&quot;,<br>    &quot;sourceMap&quot;: true,<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;target&quot;: &quot;ES6&quot;,<br>    &quot;jsx&quot;: &quot;react&quot;,<br>    &quot;typeRoots&quot;: [&quot;./src/@types&quot;, &quot;./node_modules/@types&quot;]<br>  },<br>  &quot;include&quot;: [<br>    &quot;./src/**/*&quot;<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;<br>  ]<br>}</pre><p>As we said, we will use Webpack - and some loaders - to convert our code to a single .js file, so let&#39;s do it now.</p><pre>$ npm i --save-dev webpack webpack-cli css-loader file-loader style-loader source-map-loader ts-loader</pre><p>And add a configuration file for it, webpack.config.js where we will specify the behavior we want.</p><p><strong>webpack.config.js</strong></p><pre>const path = require(&quot;path&quot;);<br>const isDevMode = process.env.APP_ENV !== &quot;production&quot;;</pre><pre>const config = {<br>  entry: {<br>    main: [&quot;./src/index.tsx&quot;]<br>  },<br>  devtool: isDevMode ? false : &quot;source-map&quot;,<br>  mode: isDevMode ? &quot;development&quot; : &quot;production&quot;,<br>  output: {<br>    path: isDevMode<br>      ? path.resolve(__dirname, &quot;dist&quot;)<br>      : path.resolve(__dirname, &quot;build&quot;),<br>    filename: &quot;app.bundle.js&quot;<br>  },<br>  resolve: {<br>    extensions: [&quot;.ts&quot;, &quot;.tsx&quot;, &quot;.js&quot;, &quot;.jsx&quot;]<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.(t|j)sx?$/,<br>        enforce: &quot;pre&quot;,<br>        use: [<br>          {<br>            loader: &quot;ts-loader&quot;<br>          }<br>        ],<br>        exclude: /node_modules/<br>      },<br>      {<br>        enforce: &quot;pre&quot;,<br>        test: /\.js$/,<br>        exclude: /node_modules/,<br>        loader: &quot;source-map-loader&quot;<br>      },<br>      {<br>        test: /\.css$/i,<br>        use: [&#39;style-loader&#39;, &#39;css-loader&#39;],<br>      },<br>      {<br>        test: /\.(png|svg|jpg|gif)$/,<br>        loader: &#39;file-loader&#39;,<br>        options: {<br>          outputPath: &#39;images&#39;,<br>          publicPath: (url, resourcePath, context) =&gt; {<br>            const modulePath = context.substr(context.indexOf(&#39;/modules/&#39;, -1));</pre><pre>            const relativePath = isDevMode<br>              ? path.join(modulePath, &quot;dist&quot;)<br>              : path.join(modulePath, &quot;build&quot;);</pre><pre>            return path.join(relativePath, &#39;images&#39;, url);<br>          },<br>        },<br>      },<br>    ]<br>  }<br>};</pre><pre>module.exports = config;</pre><p>This contains the settings about the output file and the extensions it will use.</p><p>Again we refer to APP_ENV to switch between the development and the production builds and, as you can see, it defaults to development mode until we set it specifically as &quot;production&quot;.</p><p>Everything is (almost) ready now. But before proceeding to code on our app, we still need to add the instructions to run Webpack into our package.json file.</p><pre>...<br>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>  &quot;build&quot;: &quot;APP_ENV=production webpack&quot;,<br>  &quot;build:dev&quot;: &quot;webpack&quot;,<br>  &quot;start&quot;: &quot;webpack --watch --progress&quot;<br>}<br>...</pre><p>With this new lines added to the scripts section, we define how to build the component for production and development mode, but also - and it&#39;s our best friend for development - how to start a live watching process that will re-build the package everytime we save some change on our files.</p><p>OK, time to create our component!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4592f3aaa469a16f12e1095ce248a75/href">https://medium.com/media/c4592f3aaa469a16f12e1095ce248a75/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d2a297af05d484b0d716bba103fd3e/href">https://medium.com/media/68d2a297af05d484b0d716bba103fd3e/href</a></iframe><p>If you are familiar with React and Typescript development there&#39;s not so much to comment here...</p><p>…but it’s worth notice how, as you can see, we get the data from Drupal in drupalSettings so we are ready to format and display them as we like.</p><pre>const drupalAndReactApp: Settings =<br>  window.drupalSettings.drupal_and_react_app || {};</pre><p>If everything is correct, we should be able to launch our watcher and generate our first build.</p><pre>$ npm start</pre><h3>Install and enjoy</h3><p>It’s time to install our module in Drupal now and see the result of our work.</p><p>You can find and enable it in the list of available modules at http://YOUR_WEBSITE_DOMAIN/admin/modules or enable it with drush:</p><pre>$ drush en drupal_and_react</pre><p>After that, we need to apply our field formatter to some text field. We created a dedicated one just for the purpose.</p><figure><img alt="Change the field formatter in Display options" src="https://cdn-images-1.medium.com/max/1024/1*8TwA2fEvRSCKDdzuJR83dA.png" /><figcaption>Change the field formatter in Display options</figcaption></figure><p>Now to test it, let’s add some text in our text field.</p><figure><img alt="Text field to be rendered by React app" src="https://cdn-images-1.medium.com/max/1024/1*OmA4Hpg0rCzbAOet98-seQ.png" /><figcaption>Text field to be rendered by React app</figcaption></figure><p>And finally, we are done! 🎉🎉🎉🎉</p><p>As you can see the entered text “<em>React will render this text</em>” is contained in a div that has the ID that we defined in our formatter, and the element has the class &#39;react-text&#39;, so we are sure that it&#39;s coming from our component.</p><figure><img alt="Text rendered by React app" src="https://cdn-images-1.medium.com/max/1024/1*O314xsylHc25g1y3aGQLjA.png" /><figcaption>Text rendered by React app</figcaption></figure><h3>One last thing</h3><p>Our <strong>package.json </strong>contains the following <strong>scripts </strong>to build our components.</p><pre>...<br>  &quot;build&quot;: &quot;APP_ENV=production webpack&quot;,<br>  &quot;build:dev&quot;: &quot;webpack&quot;,<br>  &quot;start&quot;: &quot;webpack --watch --progress&quot;<br>...</pre><p>We have already seen <strong>npm start</strong>. Run <strong>npm run build:dev</strong> to just build the development component. Run <strong>npm run build</strong> to build the production component.</p><p>The scope of this article is mostly to show how to integrate your React component into Drupal in the easiest way.</p><p>But we have more advanced material to share (<em>e.g. </em><em>Drupal + React + GraphQL, </em><em>Drupal + React + EsLint + Prettier</em>) in other stories to come. We really hope you could find this story useful and please, <a href="https://medium.com/soulweb-academy">follow us</a> to get the next updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577850546c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/soulweb-academy/drupal-and-react-typescript-components-577850546c4">Drupal and React/TypeScript components</a> was originally published in <a href="https://medium.com/soulweb-academy">Soulweb Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>