<?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 Afif Alfiano on Medium]]></title>
        <description><![CDATA[Stories by Afif Alfiano on Medium]]></description>
        <link>https://medium.com/@afifalfiano?source=rss-a40d2d6ac40b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*R9e6W50zXKrFZrpkl4_USg.jpeg</url>
            <title>Stories by Afif Alfiano on Medium</title>
            <link>https://medium.com/@afifalfiano?source=rss-a40d2d6ac40b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:20:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afifalfiano/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[This One File Lets My Angular Widget Run in React, Vue — Even WordPress]]></title>
            <link>https://afifalfiano.medium.com/this-one-file-lets-my-angular-widget-run-in-react-vue-even-wordpress-eb16b2dd961a?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb16b2dd961a</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 10:39:10 GMT</pubDate>
            <atom:updated>2026-07-11T10:39:10.518Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>No module federation. No shared bundler config. Just Angular 21 and a trick that’s been hiding in your browser all along.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PEUyxjh8hGXQjAK8oJ-_A.png" /><figcaption>Hero Image of Micro Frontend</figcaption></figure><p>Here’s a problem almost every growing product hits sooner or later. You build a nice UI widget — a checkout card, a chat bubble, a booking form — and suddenly other teams want it too. One team runs React. Another runs Vue. Marketing has a WordPress site. Do you really rewrite the same widget three times?</p><p>This is the problem <strong>micro frontends</strong> try to solve: split the UI into pieces that separate teams can build, deploy, and own independently. If you’ve researched the topic, you’ve probably run into module federation — a bundler feature that lets separately-built apps share code at runtime. It works, but it’s heavy machinery: every team needs compatible bundler setups, framework versions have to stay in sync, and the configuration alone has eaten more than one of my weekends.</p><p>So this weekend I tried the other path: compile an Angular component into a <strong>native web component</strong> — a custom HTML tag the browser itself understands, no framework needed on the host page. Any site — React, Vue, WordPress, a plain HTML file from 2009 — can consume it like a regular DOM element.</p><p>And Angular 21 turned out to be the best version yet for this. Zoneless change detection is now the default, which means the thing that always made Angular Elements feel heavy — shipping zone.js and its monkey-patched world into someone else’s page — is just… gone. Here’s the whole build, start to finish. Every snippet below is from a project I actually ran, and the final widget is <strong>one deployable JavaScript file</strong>.</p><h3>Why web components for micro frontends?</h3><p>Quick alignment before code. Whatever tool you pick, the hard part of micro frontends is always the seam — the boundary where the host app loads your widget and talks to it. Module federation puts that seam inside the bundler, which is why everyone has to agree on tooling.</p><p>Web components put the seam at the browser level instead. The seam is the DOM itself — the one API every website already shares:</p><ul><li>The host writes — just HTML.</li><li>Data goes in through attributes and properties.</li><li>Data comes out through CustomEvents.</li><li>The host doesn’t know or care that Angular is inside</li></ul><p>The trade-off is real too — each widget ships its own copy of the framework runtime. We’ll get to that at the end, with numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xS12bLinKy1waorGAgEgHw.png" /><figcaption>Architecture of Micro Frontend</figcaption></figure><p>Architecture: the widget team builds an Angular 21 component into a single main.js on a CDN; host pages in any framework consume it through the DOM seam — attributes in, CustomEvents out.</p><p>The whole architecture in one picture: the widget team owns everything on the left, hosts own everything on the right, and the only thing they share is the DOM.</p><h3>Why Angular 21 changes the math</h3><p>Two things landed in v21 that matter here:</p><p><strong>Zoneless is the default</strong>. New Angular 21 projects don’t include zone.js at all. For a normal app that’s a nice-to-have. For a web component it’s huge, because zone.js patches global browser APIs — setTimeout, Promise, event listeners. Injecting that into a host page you don’t own was always the sketchiest part of Angular Elements. Now your widget only rerenders when a signal it depends on changes. No global patching, no 30 kB tax.</p><p><strong>Signals are the whole story now</strong>. If you’re newer to Angular: a signal is just a reactive value — you read it by calling it (<strong>price()</strong>), you change it with <strong>.set()</strong> or <strong>.update()</strong>, and anything that depends on it updates automatically. With <strong>input(), output(), and computed()</strong>, the whole component model works this way now — and it lines up neatly with how custom elements work: attribute changes flow into signal inputs, and change detection just follows the graph.</p><h4>Step 1: Scaffold</h4><pre>npx @angular/cli@21 new checkout-widget --style=css --ssr=false<br>cd checkout-widget<br>npm install @angular/elements</pre><p>No flags needed for zoneless — in v21 it’s the default. (If you ever want zone.js back, you have to opt in with provideZoneChangeDetection(). Feels good that the arrow points that way now.)</p><p>The widget we’re building is a tiny checkout card: product name and price come in from the host, quantity is internal state, and clicking “Checkout” fires an event back out. Small, but it exercises every part of the seam — data in, state inside, events out.</p><h4>Step 2: The component</h4><p>src/app/checkout-widget.ts:</p><pre>import { Component, computed, input, output, signal } from &#39;@angular/core&#39;;<br><br>export interface CheckoutPayload {<br> product: string;<br> quantity: number;<br> total: number;<br>}<br><br>@Component({<br> // No selector — this component only ever lives as a custom element,<br> // and the tag name comes from customElements.define() instead.<br> template: `<br> &lt;div class=&quot;card&quot;&gt;<br> &lt;h3&gt;{{ product() }}&lt;/h3&gt;<br> &lt;p class=&quot;price&quot;&gt;{{ price() }} {{ currency() }}&lt;/p&gt;<br> &lt;div class=&quot;qty&quot;&gt;<br> &lt;button (click)=&quot;decrease()&quot; [disabled]=&quot;quantity() === 1&quot;&gt;−&lt;/button&gt;<br> &lt;span&gt;{{ quantity() }}&lt;/span&gt;<br> &lt;button (click)=&quot;increase()&quot;&gt;+&lt;/button&gt;<br> &lt;/div&gt;<br> &lt;button class=&quot;checkout&quot; (click)=&quot;checkout()&quot;&gt;<br> Checkout — {{ total() }} {{ currency() }}<br> &lt;/button&gt;<br> &lt;/div&gt;<br> `,<br>})<br>export class CheckoutWidget {<br> // Attributes coming from the host page (always strings in HTML!)<br> product = input(&#39;Unknown product&#39;);<br> price = input(0, { transform: Number });<br> currency = input(&#39;USD&#39;) <br> <br> // Internal state<br> quantity = signal(1);<br> total = computed(() =&gt; this.quantity() * this.price());<br><br> // Becomes a native CustomEvent on the web component<br> checkedOut = output&lt;CheckoutPayload&gt;();<br><br> increase() {<br> this.quantity.update((q) =&gt; q + 1);<br> }<br><br> decrease() {<br> this.quantity.update((q) =&gt; Math.max(1, q - 1));<br> }<br><br> checkout() {<br> this.checkedOut.emit({<br> product: this.product(),<br> quantity: this.quantity(),<br> total: this.total(),<br> });<br> }<br><br>}</pre><p>(I stripped the styles for readability — put whatever you want in styles.)</p><p>Two details here that will save you a debugging session:</p><p><strong>transform: Number on the price input</strong>. HTML attributes are always strings. Without the transform, price=”89&quot; arrives as “89”, and quantity() * price() does JavaScript stringmath chaos. With signal inputs, the fix is one option instead of a getter/setter dance. This alone is a reason to like the new API for Elements work.</p><p><strong>output() becomes a real CustomEvent</strong>. When Angular Elements wraps this component, checkedOut isn’t an RxJS thing the host needs to understand — it’s dispatched as a native CustomEvent named checkedOut, with your payload in event.detail. The host just uses addEventListener. That’s the entire contract.</p><h4>Step 3: Register it as a custom element</h4><pre>This is where it stops being an app. Replace src/main.ts entirely:<br>import { createApplication } from &#39;@angular/platform-browser&#39;;<br>import { createCustomElement } from &#39;@angular/elements&#39;;<br>import { CheckoutWidget } from &#39;./app/checkout-widget&#39;;<br>(async () =&gt; {<br> // No bootstrapApplication here — we are not booting an app,<br> // we are registering a web component.<br> const app = await createApplication({<br> providers: [],<br> });<br><br> const checkoutElement = createCustomElement(CheckoutWidget, {<br> injector: app.injector,<br> });<br><br> customElements.define(&#39;pip-checkout&#39;, checkoutElement);<br>})();</pre><p>The mental model shift: bootstrapApplication says “Angular owns this page.” createApplication says “give me an Angular environment, I’ll decide what to do with it.” We use it to mint a custom element class and hand it to the browser’s own registry.</p><p>You can register multiple widgets from one bundle — call createCustomElement + customElements.define once per component, sharing the same injector.</p><p>One rule from the custom elements spec: the tag name <strong>must contain a dash.</strong> pip-checkout works, checkout will throw. Prefix with your team or product name; that’s your namespace.</p><h4>Step 4: Build it</h4><pre>ng build — output-hashing=none</pre><p>— output-hashing=none gives you a stable main.js instead of main.C3PO4R2D2.js, so host pages can reference a fixed URL. Here’s my actual build output:</p><pre>Initial chunk files | Names | Raw size | Estimated transfer size main.js | main | 111.79 kB | 33.30 kB </pre><p>Application bundle generation complete. [3.570 seconds]</p><p>For this small widget, that’s <strong>33 kB over the wire</strong> — a fully reactive Angular component, no zone.js anywhere. Your number will grow with the features you build in (forms, HTTP, animations all add weight), but for context, that baseline is smaller than most hero images. I remember when an Angular Elements bundle started as a 200 kB+ conversation with your tech lead. Zoneless by default plus years of tree-shaking work ended that argument.</p><p>Ship dist/checkout-widget/browser/main.js to any static host or CDN. That file is your micro frontend. Versioning, deployment, rollback — all just static file management, owned by your team alone.</p><h4>Step 5: Use it anywhere</h4><p>This is the part I keep showing people. A plain HTML page — no Angular, no build step:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;body&gt;<br> &lt;h1&gt;I&#39;m a plain HTML page 👋&lt;/h1&gt;<br> &lt;pip-checkout<br> product=&quot;Mechanical Keyboard&quot;<br> price=&quot;89&quot;<br> currency=&quot;USD&quot;&gt;<br> &lt;/pip-checkout&gt;<br> &lt;script src=&quot;https://cdn.your-team.dev/checkout-widget/main.js&quot;&gt;&lt;/script&gt;<br> &lt;script&gt;<br> document<br> .querySelector(&#39;pip-checkout&#39;)<br> .addEventListener(&#39;checkedOut&#39;, (event) =&gt; {<br> console.log(&#39;Host received:&#39;, event.detail);<br> // { product: &quot;Mechanical Keyboard&quot;, quantity: 2, total: 178 }<br> });<br> &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>That’s it. The host page speaks HTML and DOM events — two of the most stable APIs on the web. The same tag works inside React (&lt;pip-checkout product={name} /&gt; plus a ref for the event listener), Vue, Svelte, or a server-rendered template from any backend.</p><p>I verified the whole loop before writing this: element registers, attributes flow in as signals, clicking + bumps the internal quantity signal, and checkedOut fires with { quantity: 2, total: 178 }. Data in through attributes, state inside through signals, data out through events. Clean seam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReSAf_TAemrLHnP52SQHNg.png" /><figcaption>Use MFE on Plain HTML</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuphEvPMmaMwtEC4xbduyg.png" /><figcaption>Console Log</figcaption></figure><h3>Wrapping up</h3><p>The whole thing — scaffold to working cross-framework widget — was maybe an hour, and most of that was me reading release notes. Module federation still earns its complexity when many large apps share heavy dependencies under one org’s discipline. But for “my team ships a widget, your team embeds it” — which is what most micro frontend problems actually are — web components are the boring, durable answer. And boring seams are the best seams.</p><p>If you build something with this, I’d love to hear how it goes — especially if you hit a gotcha I missed. Find me at pipdev.net.</p><h3>References</h3><ul><li><a href="http://createCustomElement API reference • Announcing Angular v21 — Angular Blog • What’s new in Angular 21? — Manfred Steyer, ANGULARarchitects • Micro Frontends with Modern Angular, Part 2: Angular Elements and Web Components — ANGULARarchitects • Using custom elements — MDN">Angular Elements overview</a> — the official guide, including the attribute/property mapping rules and the selector warning</li><li><a href="https://angular.dev/api/elements/createCustomElement">createCustomElement</a> API reference</li><li><a href="https://blog.angular.dev/announcing-angular-v21-57946c34f14b">Announcing Angular v21</a> — Angular Blog</li><li><a href="https://www.angulararchitects.io/en/blog/whats-new-in-angular-21-signal-forms-zone-less-vitest-angular-aria-cli-with-mcp-server/">What’s new in Angular 21?</a> — Manfred Steyer,</li><li>ANGULARarchitects</li><li><a href="https://www.angulararchitects.io/en/blog/micro-frontends-with-modern-angular-part-2-multi-version-and-multi-framework-solutions-with-angular-elements-and-web-components/">Micro Frontends with Modern Angular, Part 2: Angular Elements and Web Components </a>— ANGULARarchitects</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements">Using custom elements</a> — MDN</li></ul><blockquote><strong><em>This article was written in “vibe blogging” mode meaning I built the thing first, wrote about it second, and used AI assistance to help structure and articulate the write-up. The technical details reflect my actual setup. If something doesn’t work exactly as described, open an issue or ping me.</em></strong></blockquote><p>#MicroFrontend #Angular #WebComponent</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb16b2dd961a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Chat. Zero Code. A Finance Bot That Built Itself]]></title>
            <link>https://afifalfiano.medium.com/one-chat-zero-code-a-finance-bot-that-built-itself-cc62a0a4b03f?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc62a0a4b03f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[openclaw]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 06:42:23 GMT</pubDate>
            <atom:updated>2026-03-28T07:17:44.640Z</atom:updated>
            <content:encoded><![CDATA[<p>No IDE. No repo. No framework. Just a Telegram chat, a cheap VPS, and a few dollars in API costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bEaY0kNeob4wvF08qtV7w.png" /><figcaption>AI Generated</figcaption></figure><p>In this article, I’m going to show you how I built a personal finance assistant that literally configures itself. We’ll start by setting up a <strong>VPS</strong> and installing <strong>OpenClaw</strong>, then walk through creating a <strong>Telegram bot</strong> that can write its own <strong>Google Sheets integrations</strong> and handle <strong>receipt photo uploads. </strong>All through a simple chat interface.</p><h3>Table of Contents</h3><ol><li>Why I Built This</li><li>System Architecture</li><li>Step 1 — Set Up Your VPS</li><li>Step 2 — Install OpenClaw</li><li>Step 3 — Create the Telegram Bot</li><li>Step 4 — Run Openclaw onboard</li><li>Step 5 — Connect Google Sheets (via chat)</li><li>Step 6 — Add Receipt Photo Support (via chat)</li><li>Customizing Caca: Editing the Workspace Files</li><li>Demo</li><li>Final Thoughts</li></ol><h3>Why I Built This</h3><p>I’ve tried every budgeting app. Every single one has the same problem: you open it with enthusiasm, log three transactions, forget about it for two weeks, and uninstall. The friction is too high.</p><p>What I actually wanted was simple: send a message in natural language, and have my spending recorded automatically. No UI, no drop-down, no sign-in flow. Just send <em>“Lunch 35k”</em> and it’s logged.</p><p>That’s how <strong>Caca</strong> was born. But here’s the part that surprised even me: I didn’t write the Google Sheets integration. I didn’t write the receipt upload pipeline either. <strong>The bot wrote them itself</strong>, during a conversation over Telegram.</p><p>In this article I’ll walk through how that happened and how you can replicate it on your own VPS.</p><blockquote>OpenClaw is an open-source AI agent runtime for deploying Claude-powered bots via a single binary. It gives AI agent to access to your filesystem, can execute scripts, and persists state across conversations, making it genuinely agentic, not just a chatbot wrapper.</blockquote><h3>System Architecture</h3><p>Here’s what the final system looks like after Caca finishes configuring itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UEPUUVTLVs82mqGSWB-dQ.png" /></figure><p>The unusual part of this setup is that OpenClaw gives AI Agent access to your filesystem and the ability to write and execute scripts. So instead of you writing the Google Sheets integration, you just <em>ask</em> Caca to build it and she does.</p><h3>1. Set Up Your VPS</h3><p>I’m running Ubuntu 24.04 LTS on a small VPS at my server. SSH in and do the basic hardening:</p><pre>$ sudo apt update &amp;&amp; sudo apt upgrade -y<br>$ sudo apt install -y ufw curl python3-pip<br> <br># Firewall -- allow SSH and outbound HTTPS only<br>$ sudo ufw allow 22/tcp<br>$ sudo ufw allow out 443/tcp<br>$ sudo ufw enable<br> <br># Install Python deps Caca will need later<br>$ pip3 install google-auth google-auth-httplib2 google-api-python-client pillow --break-system-packages</pre><p>We use Telegram’s long-polling mode, so no inbound ports beyond SSH are needed.</p><h3>2. Install OpenClaw</h3><p>OpenClaw is available as an npm package. Make sure Node.js is installed, then:</p><pre>$ npm install -g openclaw@latest<br> <br>$ openclaw --version<br>2026.3.2</pre><h3>3. Create the Telegram Bot</h3><p>Open Telegram and message <strong>@BotFather</strong>. Run /newbot, give it a display name and a username (must end in bot). For my personal AI, I used the display name <em>&quot;Caca AI&quot;</em> and the username @kang_catet_bot. Copy the token BotFather returns.</p><figure><img alt="Bot Father" src="https://cdn-images-1.medium.com/max/1024/1*BNU_dk10CK1azTJIWWFvKA.png" /><figcaption>Bot Father</figcaption></figure><blockquote>Keep your bot token private. Treat it like a password, anyone who has it can control your bot. Never commit it to a public repository or share it in screenshots.</blockquote><p>You also need your personal <strong>Telegram chat ID. </strong>OpenClaw uses this as an allowlist so only you can interact with the bot. The easiest way to get it is to message <strong>@userinfobot</strong> on Telegram. Send /start and it will reply with your numeric ID, something like 316312057. Copy that number and you&#39;ll need it during openclaw onboard.</p><figure><img alt="Account Information" src="https://cdn-images-1.medium.com/max/1024/1*qcst0DzPnXNTdeM6gGks0A.png" /><figcaption>Account Information</figcaption></figure><h3>4. Run Openclaw onboard</h3><p>There is a simple command, please run openclaw onboard and the wizard covers model auth, Telegram setup, and workspace initialization in one go:</p><pre>$ openclaw onboard<br> <br>? Select auth method: Anthropic API key<br>? Enter your Anthropic API key: sk-ant-api03-••••••••</pre><p>After the wizard completes, open ~/.openclaw/openclaw.json and manually add your Telegram config under channels. This is also where you set dmPolicy: &quot;allowlist&quot; and allowFrom with your chat ID to lock the bot to only respond to you:</p><p>~/.openclaw/openclaw.json — channels section</p><pre>{<br>  &quot;channels&quot;: {<br>    &quot;telegram&quot;: {<br>      &quot;enabled&quot;: true,<br>      &quot;dmPolicy&quot;: &quot;allowlist&quot;,<br>      &quot;botToken&quot;: &quot;YOUR_BOT_TOKEN&quot;,<br>      &quot;allowFrom&quot;: [&quot;YOUR_CHAT_ID&quot;],<br>      &quot;groupPolicy&quot;: &quot;allowlist&quot;,<br>      &quot;streaming&quot;: &quot;partial&quot;<br>    }<br>  }<br>}</pre><blockquote><em>dmPolicy allowlist vs pairing: Setting </em><em>dmPolicy: &quot;allowlist&quot; with your chat ID in </em><em>allowFrom means only you can DM the bot, anyone else gets silently ignored. The alternative </em><em>&quot;pairing&quot; mode requires users to pair their account first. For a personal finance bot, </em><em>allowlist is the right choice.</em></blockquote><p>Check gateway status after editing the config:</p><pre>$ openclaw gateway status<br>🦞 OpenClaw 2026.3.2 (85377a2) -- Self-hosted, self-updating, self-aware (just kidding... unless?).<br> <br>Service: systemd (enabled)<br>File logs: /tmp/openclaw/openclaw-2026-03-28.log<br>Command: /usr/bin/node /usr/lib/node_modules/openclaw/dist/index.js gateway --port 18789<br>Service file: ~/.config/systemd/user/openclaw-gateway.service<br>Service env: OPENCLAW_GATEWAY_PORT=18789<br> <br>Config (cli): ~/.openclaw/openclaw.json<br>Config (service): ~/.openclaw/openclaw.json<br> <br>Gateway: bind=loopback (127.0.0.1), port=18789 (service args)<br>Probe target: ws://127.0.0.1:18789<br>Dashboard: http://127.0.0.1:18789/<br>Probe note: Loopback-only gateway; only local clients can connect.<br> <br>Runtime: running (pid 349695, state active, sub running, last exit 0, reason 0)<br>RPC probe: ok<br> <br>Listening: 127.0.0.1:18789</pre><p><strong>One critical config to check: tools profile</strong></p><p>Open ~/.openclaw/openclaw.json and make sure the agent&#39;s tools config allows full access. Without this, Caca can&#39;t write files, execute scripts, or do anything agentic, she&#39;d just be a regular chatbot. The config you used:</p><p><em>~/.openclaw/openclaw.json</em> and search for tools section</p><pre>{<br>  &quot;tools&quot;: {<br>    &quot;profile&quot;: &quot;full&quot;,<br>    &quot;deny&quot;: [<br>      &quot;browser&quot;<br>    ]<br>  }<br>}</pre><blockquote>⚠️ Security &amp; cost: understand what profile: &quot;full&quot; means before going live.</blockquote><blockquote>This config gives Claude unrestricted filesystem access and the ability to execute arbitrary shell commands on your VPS, it can read, write, and delete any file your user account has access to. We deny the browser tool to keep Caca&#39;s scope tight (no accidental token-expensive web crawls), but she still gets filesystem read/write, bash execution, and Python execution. For a dedicated VPS running only Caca, this is acceptable. But never run this on a machine with sensitive data, SSH keys to production servers, or shared infrastructure.</blockquote><blockquote>Precautions worth taking:</blockquote><blockquote>• Run OpenClaw under a dedicated non-root user with limited permissions<br>• Use allowFrom in your Telegram config so only your chat ID can interact with the bot<br>• Keep your Telegram bot token private — anyone who has it can send commands<br>• Consider using profile: &quot;workspace&quot; instead of &quot;full&quot; if you only need Caca to access ~/.openclaw/<br>• Set a spending limit on your <a href="https://console.anthropic.com/">Anthropic dashboard</a> (Billing → Usage limits). OpenClaw responds to every message and context accumulates across turns without a cap, a long session or misconfigured agent loop could burn through credits unexpectedly. For personal use like Caca, $10–15/month is more than enough.</blockquote><h3>5. Connect Google Sheets — via chat</h3><p>Here’s the part I didn’t expect when I started. Instead of writing the Google Sheets integration myself, I just described what I wanted to Caca over Telegram — and she built it.</p><h4>5.1 Prepare your Google credentials</h4><p>You still need to create a Service Account manually in <a href="https://console.cloud.google.com/">Google Cloud Console</a>:</p><ol><li>Create a new project (e.g. caca-finance)</li><li>Enable the <strong>Google Sheets API</strong></li><li>IAM &amp; Admin → Service Accounts → Create → name it caca-bot</li><li>Keys → Add Key → JSON → download credentials.json</li><li>Copy it to the VPS: scp credentials.json user@vps:~/.openclaw/google-credentials.json</li></ol><p>Also create a new Google Spreadsheet and share it with the service account email (found in &quot;client_email&quot; inside the JSON). When sharing, make sure to set the role to <strong>Editor, </strong>not Viewer or otherwise the bot won&#39;t be able to write rows to the sheet. Copy the spreadsheet ID from the URL.</p><figure><img alt="Service Account → Keys tab — click “Add key” → Create new key → JSON to download your credentials file." src="https://cdn-images-1.medium.com/max/1024/1*bVCHC3wM2fZtjVqBOIgSUg.png" /><figcaption><em>Service Account → Keys tab — click “Add key” → Create new key → JSON to download your credentials file.</em></figcaption></figure><figure><img alt="Permissions tab → Manage access → assign the Editor role so the service account can write to your spreadsheet." src="https://cdn-images-1.medium.com/max/1024/1*j_RWw3TI3Ihtu60zym-ZNg.png" /><figcaption><em>Permissions tab → Manage access → assign the </em><strong><em>Editor</em></strong><em> role so the service account can write to your spreadsheet.</em></figcaption></figure><h4>5.2 Ask Caca to build the integration</h4><p>Now open Telegram and tell Caca what you need. Here’s roughly how that conversation went:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DrdAhRyk2AaEFUQfbox5Q.png" /></figure><p>Caca generated the full script including all CRUD operations, date parsing, and error handling and saved it to ~/.openclaw/sheets_api.py. Here&#39;s what that script looks like:</p><p><em>~/.openclaw/sheets_api.py</em></p><pre>#!/usr/bin/env python3<br>import sys, json<br>from datetime import datetime<br>from google.oauth2 import service_account<br>from googleapiclient.discovery import build<br><br>SPREADSHEET_ID = &quot;&lt;your-spreadsheet-id&gt;&quot;<br>RANGE = &quot;Sheet1&quot;<br>CREDENTIALS_FILE = &quot;/home/&lt;your-username&gt;/.openclaw/google-credentials.json&quot;<br><br>creds = service_account.Credentials.from_service_account_file(<br>    CREDENTIALS_FILE,<br>    scopes=[&quot;https://www.googleapis.com/auth/spreadsheets&quot;]<br>)<br>service = build(&quot;sheets&quot;, &quot;v4&quot;, credentials=creds)<br>sheet = service.spreadsheets()<br><br>def create(tanggal, kategori, keterangan, nominal, tipe,<br>           jam=&quot;&quot;, metode=&quot;&quot;, catatan=&quot;&quot;, link_bukti=&quot;&quot;, tag=&quot;&quot;):<br>    # Mandatory field validation<br>    if not jam: return &quot;❌ Jam wajib diisi (format HH:MM)&quot;<br>    if not metode: return &quot;❌ Metode wajib diisi (Tunai/Kartu/e-wallet/QRIS)&quot;<br>    if not tag: return &quot;❌ Tag wajib diisi (planned/spontan/recurring)&quot;<br><br>    values = [[tanggal, kategori, keterangan, str(nominal),<br>               tipe, jam, metode, catatan, link_bukti, tag]]<br>    sheet.values().append(<br>        spreadsheetId=SPREADSHEET_ID,<br>        range=f&quot;{RANGE}!A:J&quot;,<br>        valueInputOption=&quot;USER_ENTERED&quot;,<br>        body={&quot;values&quot;: values}<br>    ).execute()<br>    return f&quot;✅ Berhasil catat: {keterangan} - Rp {nominal:,} | {jam} | {metode} | {tag}&quot;<br><br># + read(), update(), delete(), update_link(),<br>#   update_kategori(), update_jam(), update_metode(), update_tag()<br># Full script: github.com/afifalfiano<br><br>if __name__ == &quot;__main__&quot;:<br>    data = json.loads(sys.argv[1])<br>    action = data.get(&quot;action&quot;)<br>    # routes to appropriate function based on action field</pre><p>The script accepts a JSON payload as its first argument, which is exactly how OpenClaw invokes it when routing Claude’s structured responses. The spreadsheet schema it generated looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkiGlKLCNEZel7tW6yv-OQ.png" /><figcaption>Document Schema</figcaption></figure><h3>6. Add Receipt Photo Support — via chat</h3><p>A few days after setting up the basic logging, I wanted to attach photo evidence of transactions such as a struk belanja, QRIS screenshots, that kind of thing. Instead of writing a script, I just asked Caca to figure it out.</p><figure><img alt="Image Handler" src="https://cdn-images-1.medium.com/max/1024/1*yzUJ7_GBXJeVnMl7But8pg.png" /><figcaption>Image Handler</figcaption></figure><p>What’s interesting here is that Caca didn’t write a standalone Python script for this. Instead, she updated her own AGENTS.md with a step-by-step bash procedure, which she now follows every time a photo is involved. The relevant section she added looks like this:</p><p><em>~/.openclaw/workspace/AGENTS.md</em> — bukti upload procedure</p><pre>### 📷 Upload Bukti (Foto/File)<br><br>Full Prosedur (Step-by-Step):<br><br>1. Check direktori bukti sesuai tanggal<br>   ls ~/.openclaw/workspace/keuangan/bukti/$TANGGAL 2&gt;/dev/null<br><br>2. Buat direktori jika belum ada<br>   mkdir -p ~/.openclaw/workspace/keuangan/bukti/$TANGGAL<br><br>3. Copy file dari inbound ke lokasi bukti<br>   cp ~/.openclaw/media/inbound/FILE.jpg \<br>      ~/.openclaw/workspace/keuangan/bukti/$TANGGAL/NAMA.jpg<br><br>4. Sync ke server (CRITICAL)<br>   bash ~/.openclaw/workspace/sync_bukti.sh<br><br>5. Entry ke Sheets dengan full URL<br>   python3 ~/.openclaw/sheets_api.py &#39;{&quot;action&quot;:&quot;create&quot;,<br>     &quot;link_bukti&quot;:&quot;https://your-website/bukti/YYYY-MM-DD/NAMA.jpg&quot;,...}&#39;</pre><blockquote>Why bash steps instead of a Python script? Because it’s cheaper. Each Claude API call costs tokens. A self-contained bash procedure that Caca reads from AGENTS.md and executes directly is more token-efficient than maintaining a separate Python file that needs to be read, parsed, and called. Caca is deliberately scoped, financial tracking and her own infrastructure only pecifically to keep API usage minimal.</blockquote><p>One thing worth noting about sync_bukti.sh: it&#39;s a simple local rsync, no SSH, no remote server. OpenClaw and Nginx run on the same VPS, so syncing is just copying files from the workspace folder to the web-accessible directory:</p><pre>#!/bin/bash<br># Sync bukti dari workspace ke /var/www/bukti<br>SRC=&quot;$HOME/.openclaw/workspace/keuangan/bukti&quot;<br>DEST=&quot;/var/www/bukti&quot;<br><br>rsync -av &quot;$SRC/&quot; &quot;$DEST/&quot; --delete<br><br>if [ $? -eq 0 ]; then<br>    echo &quot;✅ Sync bukti ke server selesai!&quot;<br>else<br>    echo &quot;❌ Sync gagal. Pastikan punya akses ke $DEST&quot;<br>    exit 1<br>fi</pre><p><strong>One manual step: Nginx config for public /bukti access</strong></p><p>Because everything runs on the same machine, the only thing needed to make receipt URLs publicly accessible is an Nginx location block pointing at /var/www/bukti/. This is the one piece Caca can&#39;t set up herself. it requires sudo. Add this to your existing Nginx server block for your domain:</p><p><em>/etc/nginx/sites-available/default</em> (add inside your server block)</p><pre>location /bukti/ {<br>    alias      /var/www/bukti/;<br>    autoindex  off;<br><br>    # Only serve image files, block everything else<br>    location ~* \.(jpg|jpeg|png|webp)$ {<br>        expires    30d;<br>        add_header Cache-Control &quot;public, immutable&quot;;<br>        add_header X-Content-Type-Options nosniff;<br>    }<br><br>    location ~ [^/]$ {<br>        if ($uri !~ \.(jpg|jpeg|png|webp)$) {<br>            return 403;<br>        }<br>    }<br>}</pre><p>Then create the directory and reload:</p><pre># Create the public directory, writable by your user<br>$ sudo mkdir -p /var/www/bukti<br>$ sudo chown -R $USER:www-data /var/www/bukti<br>$ sudo chmod -R 755 /var/www/bukti<br> <br># Test config and reload Nginx<br>$ sudo nginx -t<br>nginx: configuration file /etc/nginx/nginx.conf test is successful<br>$ sudo systemctl reload nginx<br> <br># Verify a file is reachable<br>$ curl -I https://your-website/bukti/2026-03-28/test.jpg<br>HTTP/2 200</pre><p>The final workspace structure, reflecting everything Caca set up across these conversations:</p><pre>~/.openclaw/<br>├── openclaw.json ← openclaw onboard<br>├── google-credentials.json ← copied manually<br>├── sheets_api.py ← written by Caca via chat<br>└── workspace/<br>├── AGENTS.md ← tools, scope, procedures ← edit this<br>├── SOUL.md ← persona &amp; tone ← edit this<br>├── MEMORY.md ← persistent memory across sessions<br>├── USER.md ← your preferences<br>├── USER-CACA.md ← Caca-specific relationship context<br>├── TOOLS.md ← tool registry<br>├── KEUANGAN_USAGE.md ← finance usage patterns<br>├── BOOTSTRAP.md ← initialization logic<br>├── sync_bukti.sh ← local rsync: workspace → /var/www/bukti<br>├── memory/ ← granular memory fragments<br>└── keuangan/bukti/ ← receipt photos by date</pre><h3>Customizing Caca: Editing the Workspace Files</h3><p>This is one of the most underrated parts of OpenClaw. Because Caca’s entire behavior is driven by markdown files in ~/.openclaw/workspace/, you can change how she works at any time and just edit the file and she&#39;ll pick it up on the next message. No redeployment, no restart.</p><h4>AGENTS.md — scope, tools, and procedures</h4><p>This is the most important file. It defines what Caca can and can’t do, what bash commands she runs for each operation, and what she should decline.</p><blockquote>What goes in AGENTS.md? This file defines the bot’s operational boundaries — what tasks it should handle (e.g., financial tracking, financial advice, self-maintenance), what it should decline (off-topic requests), and the exact bash commands or API calls it runs for each operation. Think of it as the bot’s job description and standard operating procedures combined.</blockquote><p>This tight scope is intentional — every off-topic message that Caca answers consumes API tokens. By hard-limiting her to financial tracking and her own infrastructure maintenance, the monthly API cost stays well under $0.10.</p><p>If you want to add a new operation — say, a new update command or a different sheet — just add a new section to AGENTS.md describing the bash command. Caca will start using it immediately.</p><h4>SOUL.md — persona and tone</h4><p>This file defines who Caca is — her personality, expertise, communication style, and how she handles ambiguity. For my use case, I shaped her into someone with deep finance knowledge and solid coding chops.</p><blockquote>What goes in SOUL.md? This file shapes the bot’s personality and expertise — its communication style (casual, formal, bilingual), domain knowledge (finance, coding, etc.), how it handles ambiguity, and behavioral traits like proactively flagging spending patterns or auto-converting currencies. The more precise the persona, the more consistent the behavior across sessions.</blockquote><p>The result is a bot that doesn’t just log transactions mechanically — she notices patterns, flags outliers, converts currencies on the fly, and can debug her own tools when something breaks. You can tune this as specifically as you want. The more precise the persona, the more consistent the behavior across sessions.</p><h4>MEMORY.md and memory/ — persistent context</h4><p>OpenClaw writes to MEMORY.md across conversations to maintain context, things like your most frequent spending categories, your preferred payment methods, patterns it has noticed. The memory/ folder holds more granular fragments. You can read and edit these directly, or just let Caca maintain them herself.</p><blockquote>The key insight: In most agent frameworks, changing behavior means changing code. In OpenClaw, changing behavior means editing a markdown file. This makes Caca genuinely maintainable by anyone — you don’t need to be a developer to tweak how she works.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnTPz9ZC4ln3-sLRHrGJYw.png" /><figcaption>AI Persona</figcaption></figure><h3>Demo</h3><p>Once everything is running, the daily usage is exactly as frictionless as I wanted:</p><figure><img alt="Ask AI to write and upload data" src="https://cdn-images-1.medium.com/max/1024/1*PVl3r25XWoX-gcAslMhW9A.png" /><figcaption>Ask AI to write and upload data</figcaption></figure><figure><img alt="Ask the report" src="https://cdn-images-1.medium.com/max/1024/1*0FFa81gWH4eWxPU734gPaw.png" /><figcaption>Ask the report</figcaption></figure><figure><img alt="The Resuts" src="https://cdn-images-1.medium.com/max/1024/1*3yYGpK2-IcfNgt7xEZuAmQ.png" /><figcaption>The Resuts</figcaption></figure><h3>Final Thoughts</h3><p>What surprised me most about this project wasn’t the end result — it was the process. I expected to spend a weekend writing Python scripts and debugging API calls. Instead, I ran one command, described what I wanted in plain language, and had a working system in under an hour.</p><p>The script and procedures inside ~/.openclaw/ which issheets_api.py handling all Sheets CRUD operations, sync_bukti.sh syncing receipt photos to the web server, and the upload procedure in AGENTS.md weren&#39;t written by me. They were generated by Claude during Telegram conversations, saved to the filesystem, and immediately usable. That&#39;s a genuinely different kind of workflow.</p><p>To be clear: “zero code” doesn’t mean zero effort. You still need to set up the VPS, configure Google credentials, wire up Telegram, and handle Nginx manually. What you skip is the application logic — the scripts, the API integrations, the data pipeline. That’s the part the bot writes for you.</p><p>Total monthly cost: ~$8 USD for the VPS, and approximately $10–20 in Anthropic API usage. Total lines of application code I wrote manually: zero.</p><h3>References</h3><h4>OpenClaw</h4><ul><li>Official Website: <a href="https://openclaw.ai/">https://openclaw.ai</a></li><li>Documentation: <a href="https://docs.openclaw.ai/">https://docs.openclaw.ai</a></li><li>GitHub Repository: <a href="https://github.com/openclaw/openclaw">https://github.com/openclaw/openclaw</a></li></ul><h4>Google Sheets API v4</h4><ul><li>API Overview: <a href="https://developers.google.com/workspace/sheets/api/guides/concepts">https://developers.google.com/workspace/sheets/api/guides/concepts</a></li><li>REST Reference: <a href="https://developers.google.com/workspace/sheets/api/reference/rest">https://developers.google.com/workspace/sheets/api/reference/rest</a></li></ul><h4>Telegram Bot API</h4><ul><li>Documentation: <a href="https://core.telegram.org/bots/api">https://core.telegram.org/bots/api</a></li></ul><h4>Anthropic / Claude API</h4><ul><li>Documentation: <a href="https://docs.anthropic.com/">https://docs.anthropic.com</a></li></ul><h4>Infrastructure</h4><ul><li>Google Cloud Console (Service Account / OAuth): <a href="https://console.cloud.google.com/">https://console.cloud.google.com</a></li></ul><blockquote><strong>This article was written in “vibe blogging” mode meaning I built the thing first, wrote about it second, and used AI assistance to help structure and articulate the write-up. The technical details reflect my actual setup. If something doesn’t work exactly as described, open an issue or ping me.</strong></blockquote><p>#OpenClaw #AIAssistant #VibeBlogging #Automation #Finance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc62a0a4b03f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Import in Angular: Load What You Need, When You Need It]]></title>
            <link>https://afifalfiano.medium.com/dynamic-import-in-angular-load-what-you-need-when-you-need-it-8d5c91d977c3?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d5c91d977c3</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 12:11:29 GMT</pubDate>
            <atom:updated>2026-03-23T12:24:20.261Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to understanding how dynamic import() works in Angular to boost your app performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YubiVLCf3L5o_8PrVzxG9g.png" /></figure><p>Hi guys, I think it’s been a while since the last time I posted about Angular stuff. So, today we’re gonna talk about <strong>dynamic import</strong> in Angular. Have you ever thought about what happens when your Angular app is getting bigger and bigger? Like, you have a lot of features such as dashboard, settings, admin panel, reports, and etc. But the user only visits the dashboard page. The question is, why should the browser download ALL the code for every feature at the first load?</p><p>If you ever faced this problem on your project, don’t worry because I had to. And the answer is <strong>dynamic import</strong>. So, let’s dive into it.</p><h3><strong>What is Dynamic Import?</strong></h3><p>Before we jump into the Angular implementation, let’s understand the basic concept first. In JavaScript (and TypeScript), we have two ways to import a module.</p><h4><strong>Static Import</strong></h4><pre>import { MyService } from &#39;./my-service&#39;;</pre><p>This is the common way that we always use. The module is loaded at <strong>compile time</strong>, which means the bundler will include this module in the main bundle. So, the browser has to download everything at the beginning.</p><h4><strong>Dynamic Import</strong></h4><pre>const module = await import(&#39;./my-service&#39;);</pre><p>This one is different. Dynamic import uses the `import()` function that returns a <strong>Promise</strong>. The module will be loaded only when this code is executed and not at the first load. The bundler (Webpack or esbuild on Angular 17+) will automatically split this module into a <strong>separate chunk</strong>.</p><h4><strong>Simple Analogy</strong></h4><p>Let’s imagine you have a big library with 1000 books. Static import is like <strong>bringing all 1000 books to your home</strong> at once. But dynamic import is like <strong>borrowing one book at a time only when you need it</strong>. Which one is more efficient? I think you already know the answer.</p><p>Here is a visual comparison to make it clearer:</p><figure><img alt="Static Import vs Dynamic Import" src="https://cdn-images-1.medium.com/max/1024/1*42Nbh1TT7D8OmlXa-YPFZw.png" /><figcaption>Static Import vs Dynamic Import</figcaption></figure><p><em>Left: all modules bundled in one heavy file. Right: small core with lazy chunks loaded on demand.</em></p><h3><strong>How to Use Dynamic Import in Angular</strong></h3><p>In this section, we will explore several ways to implement dynamic import in Angular. Let’s take a look one by one.</p><h4><strong>1. Lazy Loading Route (The Most Common Way)</strong></h4><p>Angular Router has supported lazy loading for a long time. We can use <strong>loadChildren</strong> or <strong>loadComponent</strong> to achieve this.</p><p><strong>NgModule-based approach:</strong></p><pre>const routes: Routes = [<br>  {<br>    path: &#39;dashboard&#39;,<br>    loadChildren: () =&gt;<br>    import(&#39;./dashboard/dashboard.module&#39;).then(m =&gt; m.DashboardModule),<br>  },<br>];</pre><p><strong>Standalone Component approach (Angular 14+):</strong></p><pre>const routes: Routes = [<br>  {<br>    path: &#39;dashboard&#39;,<br>    loadComponent: () =&gt;<br>    import(&#39;./dashboard/dashboard.component&#39;).then(c =&gt; c.DashboardComponent),<br>  },<br>];</pre><p>If you are using Angular 14+ with standalone components, I recommend you to use <strong>loadComponent</strong> because it’s simpler and you don’t need to create a separate module just for lazy loading.</p><h4><strong>2. Lazy Loading Component Manually</strong></h4><p>Not all lazy loading has to go through the router. Sometimes, we want to load a component dynamically based on user action like clicking a button. We can use <strong>ViewContainerRef</strong> to do this.</p><pre>const routes : Routes = [<br>  {<br>    path : &#39;dashboard&#39;,<br>    loadComponent : () = &gt; import(&#39;./dashboard/dashboard.component&#39;).then(c = &gt; c.DashboardComponent),<br>  },<br>];</pre><p>This is very useful when you have a heavy component like a chart or a rich text editor that doesn’t need to be loaded at the first render. The user can interact with other parts of the page first, and then when they click the button and boom, the component is loaded.</p><h4><strong>3. Lazy Loading a Third-Party Library</strong></h4><p>Have you ever imported a heavy library like <strong>pdfmake</strong> or <strong>xlsx</strong> and then your bundle size is getting huge? We can solve this with dynamic import too.</p><pre>async generatePdf() {<br>  const pdfMake = await import(&#39;pdfmake/build/pdfmake&#39;);<br>  const pdfFonts = await import(&#39;pdfmake/build/vfs_fonts&#39;);<br>  pdfMake.default.vfs = pdfFonts.default.pdfMake.vfs;<br>  const docDefinition = {content : [&#39;Hello, PDF!&#39;]};<br>  pdfMake.default.createPdf(docDefinition).open();<br>}</pre><p>So, <strong>pdfmake</strong> will only be downloaded when the user actually clicks the “Generate PDF” button. Not at the first load. This approach can reduce your initial bundle size significantly.</p><h3><strong>How It Works Under the Hood</strong></h3><p>Maybe you are curious about what happens behind the scenes when we use <strong>import()</strong>. Let me explain a little bit. I also created a diagram below to make it easier to understand.</p><figure><img alt="How Dynamic Import Works in Angular — Build Time and Runtime Flow]" src="https://cdn-images-1.medium.com/max/1024/1*xeNPGHoP4rTWHjeVh36H3g.png" /><figcaption>How Dynamic Import Works in Angular — Build Time and Runtime Flow]</figcaption></figure><p>The process is divided into two phases:</p><h4><strong>Build Time</strong></h4><p>When Angular CLI builds the application, every <strong>import()</strong> expression is detected by the bundler (Webpack or esbuild). The bundler then:</p><p>1. <strong>Identifies</strong> the module that is dynamically imported.</p><p>2. <strong>Splits</strong> that module into a separate chunk file (e.g., chunk-DASHBOARD-abc123.js).</p><p>So, instead of one massive <strong>main.js</strong>, you get a small <strong>main.js</strong> (only core and eager modules) plus individual chunks like <strong>chunk-DASHBOARD.js</strong> for each lazy-loaded module.</p><h4><strong>Runtime</strong></h4><p>When the user navigates to a lazy route (e.g., <strong>/dashboard</strong>):</p><p>1. <strong>Router matches</strong> the lazy route configuration.</p><p>2. <strong>import() is executed</strong> and returns a Promise.</p><p>3. <strong>Browser fetches</strong> the chunk file via network request (GET chunk-DASHBOARD.js).</p><p>4. <strong>Component is rendered</strong> after the chunk is loaded.</p><p>The cool thing is, on the <strong>second visit</strong>, the browser already has the chunk in its cache. So there’s no extra network request. You can see all of this happening in the <strong>Network tab</strong> of your browser DevTools every time you navigate to a lazy-loaded route, a new chunk request will appear.</p><h3><strong>Pitfalls and Best Practices</strong></h3><p>As a developer, we should have a mindset to not only know how to use a feature but also understand the pitfalls. Let me share some common mistakes and best practices.</p><h4><strong>Pitfalls You Should Avoid</strong></h4><p><strong>1. Over Lazy Loading Everything</strong></p><p>Don’t lazy load everything. Features that the user always accesses like the navbar, sidebar, or main layout should remain eager-loaded. If you over-split, it will add overhead because of too many network requests.</p><p><strong>2. Forgetting to Handle Loading State</strong></p><p>The user doesn’t know that a module is being downloaded. Always show a loading indicator so the user experience is not bad.</p><pre>@Component({<br>  template : ` &lt;div *ngIf = &quot;isLoading&quot; class = &quot;spinner&quot;&gt;<br>      Loading…&lt;/ div&gt;&lt;ng - container #outlet&gt;&lt;/ ng - container&gt;<br>`,<br>}) export class HostComponent {<br>  isLoading = false;<br>  async loadFeature() {<br>    this.isLoading = true;<br>    const {FeatureComponent} = await import(&#39;./feature/feature.component&#39;);<br>    this.container.createComponent(FeatureComponent);<br>    this.isLoading = false;<br>  }<br>}</pre><p><strong>3. Not Handling Errors</strong></p><p>The network can fail at any time. Always use try-catch to handle the error gracefully.</p><pre>async loadModule() {<br>  try {<br>    const module = await import(&#39;./heavy-module&#39;);<br>    // use the module<br>  } catch (error) {<br>    console.error(&#39;Failed to load module:&#39;, error);<br>    // show error message to user<br>  }<br>}</pre><h4><strong>Best Practices</strong></h4><ul><li><strong>Use Preloading Strategy: </strong>Angular provides <strong>PreloadAllModules</strong> or you can create a custom preloading strategy to load lazy modules in the background after the initial load is completed. This way, the first load is still fast, but the lazy chunks are already ready when the user navigates to them.</li><li><strong>Analyze Your Bundle: </strong>Use tools like <strong>source-map-explorer</strong> or <strong>webpack-bundle-analyzer </strong>to monitor the size of your chunks. This is very important to make sure your optimization is on the right track.</li><li><strong>Watch Out for Shared Dependencies: </strong>If two lazy modules both import the same library (like <strong>lodash</strong> or <strong>moment</strong>), the bundler might duplicate that library into both chunks. You can solve this by moving the shared dependency into the main bundle or creating a shared chunk. Always check the bundle analyzer to catch this.</li><li><strong>Give Your Chunks a Name: </strong>Use magic comments (Webpack) to make chunk names readable in DevTools:</li></ul><pre>loadChildren : () = &gt; import(/* webpackChunkName: &quot;dashboard&quot; */<br>                             &#39;./dashboard/dashboard.module&#39;)<br>                          .then(m = &gt; m.DashboardModule)</pre><h3><strong>Real-World Example: E-Commerce App</strong></h3><p>Let me give you a real-world scenario so you can understand when and where to use dynamic import.</p><p>Imagine we have an e-commerce application with these features:</p><ul><li><strong>Homepage</strong> (eager): Always displayed to the user, this is the landing page so it should load immediately.</li><li><strong>Product Detail</strong> (lazy): only loaded when user clicks a product. Most users browse the homepage first, so there’s no need to load this upfront.</li><li><strong>Checkout</strong> (lazy): only loaded when user proceeds to checkout. Not every visitor will buy something, so why load the checkout module for everyone?</li><li><strong>Admin Panel</strong> (lazy): only loaded for admin users. Regular users will never access this, so it makes no sense to include it in the main bundle.</li></ul><p>With this configuration, the initial bundle only contains <strong>HomeComponent</strong> and the Angular core maybe around <strong>300–400KB</strong>. The product detail page might add another <strong>80KB</strong> when the user clicks a product. The checkout adds <strong>120KB</strong> only when the user decides to buy. And the admin panel — which could be <strong>500KB+</strong> because of tables, charts, and forms is never downloaded for regular users at all.</p><p>If you check the Network tab, you will see the chunk files being loaded one by one as the user navigates through the app. The user experience feels fast because they only wait for the code they actually need.</p><p>Here is a diagram to visualize the architecture:</p><figure><img alt="E-Commerce Lazy Loading Architecture" src="https://cdn-images-1.medium.com/max/1024/1*rXb_rDSZVF1Rrs0n41FMkg.png" /><figcaption>E-Commerce Lazy Loading Architecture</figcaption></figure><p><em>E-commerce app architecture — the eager core at top, lazy routes in the middle, and the actual chunk files at the bottom. Regular users only download 600KB instead of the full 1.1MB.</em></p><h3><strong>Real-World Example: White Label Project</strong></h3><p>Now, let me share another use case that I think is very interesting and maybe some of you have faced this on your project. Have you ever worked on a <strong>white label</strong> application? White label means you have one single codebase, but the application can serve multiple brands or tenants which each with their own theme, logo, features, and configuration.</p><p>For example, let’s say you are building a SaaS product for multiple companies. Company A wants a blue theme with a reporting dashboard. Company B wants a green theme with an analytics dashboard. Company C wants a red theme with a custom payment flow. Without dynamic import, you would have to bundle ALL themes and ALL features for every company into one giant bundle. <strong>That’s not efficient at all</strong>.</p><p>With dynamic import, each brand gets its own <strong>lazy chunk, </strong>the bundler splits them into separate files automatically. A config service detects which tenant is using the app (from the subdomain, environment variable, or JWT token), and then dynamic import loads only the correct brand module. The other brands are never downloaded. You can have 10, 20, or even 50 tenants and the user only gets the code they need.</p><p>The key takeaway is: <strong>dynamic import is not just for lazy loading routes, it can be the foundation of your entire multi-brand architecture.</strong> I have seen many companies use this approach for their multi-tenant SaaS products, and <strong>it works really well</strong>.</p><p>Here is a diagram to visualize the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2yWHeFo929qrUCz3ci3Kg.png" /><figcaption>White label architecture</figcaption></figure><h3><strong>Conclusion</strong></h3><p>Yeah, I think that’s all about dynamic import in Angular. Let me summarize what we have learned today:</p><ul><li>Dynamic import allows us to load modules <strong>on-demand</strong> instead of at the first load.</li><li>It can reduce the <strong>initial bundle size</strong> significantly.</li><li>Angular supports dynamic import through <strong>lazy loading routes</strong>, <strong>manual component loading</strong>, and <strong>lazy third-party libraries</strong>.</li><li>For <strong>white label / multi-tenant</strong> projects, dynamic import can be the foundation to load brand-specific modules per tenant.</li><li>Always handle <strong>loading state</strong> and <strong>errors</strong> when using dynamic import.</li><li>Don’t over lazy load, find the right balance between eager and lazy loading.</li></ul><p>As a developer, we should have a mindset to always optimize our applications. Dynamic import is one of the powerful tools to achieve that. Start from route-level lazy loading, and then explore the more advanced use cases.</p><h3><strong>References</strong></h3><ul><li><a href="https://angular.dev/guide/routing/lazy-loading">Home * Angular</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">import() - JavaScript | MDN</a></li><li><a href="https://web.dev/articles/reduce-javascript-payloads-with-code-splitting">Reduce JavaScript payloads with code splitting | Articles | web.dev</a></li><li><a href="https://blog.angular.dev/">Angular Blog</a></li></ul><h3><strong>Closing</strong></h3><p>I hope this article is useful and make an impact on your knowledge about dynamic import in Angular. I really appreciate yourself because you want to spend your time to read my article. Feel free to give me feedback to make it better and better for my next posts.</p><p>If you enjoyed this article, don’t forget to give a <strong>clap</strong> and <strong>follow</strong> me for more Angular and web development tutorials. Thank you for reading!</p><blockquote><strong>Note:</strong> This article was created using <strong>vibe blogging</strong> which mean AI-assisted content creation with human direction, curation, and editorial judgment.</blockquote><p>#Angular #JavaScript #TypeScript #Performance #LazyLoading #Web Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d5c91d977c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Be Careful with Observable Data]]></title>
            <link>https://afifalfiano.medium.com/angular-be-aware-with-observable-data-3ee2e7d57f1b?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee2e7d57f1b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 08:18:27 GMT</pubDate>
            <atom:updated>2025-03-09T01:21:41.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Izfc_R6IftaGYLKF8WBUA.jpeg" /><figcaption>Photo by Lukas: <a href="https://www.pexels.com/photo/laptop-computer-showing-c-application-574069/">https://www.pexels.com/photo/laptop-computer-showing-c-application-574069/</a></figcaption></figure><p>Have you ever wanted to monitor the observable data on Angular? How are they running in the background? Have they stopped or are they still running? How can we find out all these things?</p><p>Here, I will provide an alternative solution. Based on my concerns about this, I created a simple library that we can use in our project, no matter which version of Angular we use.</p><blockquote>Basically, the concept of this library is simple. First, it will capture observable data every time we subscribe to it. Furthermore, this tool can also destroy or unsubscribe the observable data with the global services that I also provide in that library.</blockquote><p>So, let’s get into this project.</p><h4>Init Project</h4><p>Let’s create a new project, in this tutorial I am using angular v<strong>18.2.0</strong></p><figure><img alt="Init Project Angluar" src="https://cdn-images-1.medium.com/max/1024/1*dnk7sZwv7H6TXcDGdpOxqQ.png" /></figure><h4>Install Library</h4><p>The advantages of this tool are very helpful when we do development, maintenance or debug features. I recommend you install as a development dependency. Let’s run the command.</p><pre>npm i monitor-subscription --save-dev</pre><h4>How to Use</h4><p>So, in this case I will create a scenario with an observable interval and a subscription, and we will monitor it.<br>We need to import services, custom rxjs and components:</p><pre>import {<br>activeSubs, <br>DestroySubscriptionService, <br>LoggerService, <br>ResultsComponent<br>} from &#39;monitor-subscription&#39;;</pre><p>After that, import <strong>ResulltsComponent </strong>inisde of the class AppComponent.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [ResultsComponent],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.scss&#39;<br>})</pre><p>Let’s use the custom rxjs along with services to create a log.</p><pre>export class AppComponent implements OnInit {<br>  title = &#39;test-library&#39;;<br>  loggerService = inject(LoggerService);<br>  destroyService = inject(DestroySubscriptionService);<br>  <br>  ngOnInit(): void {<br>      const name = this.constructor.name.toLowerCase();<br>      interval(1000).pipe(<br>        takeUntil(this.destroyService.getDestroy$(name + &quot;_1&quot;)),<br>        map(item =&gt; item * 2),<br>        activeSubs(name + &quot;_1&quot;, this.loggerService)<br>      ).subscribe();<br>}</pre><p>Here is how we use the library to monitor observable data.</p><ul><li><strong>activeSubs </strong>is a specialized rxj for collecting observables data along with the logger service.</li><li><strong>getDestory$</strong> is a function to store a subject with a unique id in the temporary data.</li></ul><p>Since we want to destroy observables from any current location. Make sure to use <strong>takeUntil </strong>before using other operators to prevent observables that are still subscribed after the destroy event occurs.</p><p>Remember, we have imported ResultsComponent, let’s use it in app.component.html.</p><pre>&lt;p&gt;App Component!&lt;/p&gt;<br>&lt;app-results/&gt;</pre><h4>Test Library</h4><p>Let’s run the project.</p><pre>npm run start</pre><p>Once the build completed, you will see the UI like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihjcHeBiaNvxKJzDpx55yA.gif" /><figcaption>First use case</figcaption></figure><h4>Test Worst Case</h4><p>Let’s try it with multiple subscriptions and maybe some API calls, I’ll update app.component.ts like this.</p><p>Don’t forget to update app.config.ts to use http client.</p><pre>import { ApplicationConfig, provideZoneChangeDetection } from &#39;@angular/core&#39;;<br>import { provideRouter } from &#39;@angular/router&#39;;<br><br>import { routes } from &#39;./app.routes&#39;;<br>import { provideHttpClient } from &#39;@angular/common/http&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient()]<br>};</pre><p>Then, it’s time to update app.component.ts</p><pre>import { JsonPipe } from &#39;@angular/common&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Component, inject, OnInit } from &#39;@angular/core&#39;;<br>import {activeSubs, DestroySubscriptionService, LoggerService, ResultsComponent} from &#39;monitor-subscription&#39;;<br>import { interval, map, switchMap, takeUntil } from &#39;rxjs&#39;;<br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [ResultsComponent],<br>  providers: [LoggerService, DestroySubscriptionService],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.scss&#39;<br>})<br>export class AppComponent implements OnInit {<br>  title = &#39;test-library&#39;;<br>  httpClient = inject(HttpClient)<br>  loggerService = inject(LoggerService);<br>  destroyService = inject(DestroySubscriptionService);<br>  name = this.constructor.name.toLowerCase();<br><br>  ngOnInit(): void {<br>      setTimeout(() =&gt; {<br>        for (let index = 0; index &lt; 5; index++) {<br>          this.getInterval(index);        <br>        }<br><br>        this.getData(&#39;users&#39;);<br>        this.getData(&#39;photos&#39;);<br>        this.getData(&#39;albums&#39;);<br>        this.getData(&#39;comments&#39;);<br>        this.getData(&#39;posts&#39;);<br>        this.getData(&#39;todos&#39;);<br>      }, 3000)<br><br>      }<br><br>      getInterval(count: number): void {<br>        interval(1000).pipe(<br>          takeUntil(this.destroyService.getDestroy$(`$${this.name}_interval_${count}`)),<br>          map(item =&gt; item * 2),<br>          activeSubs(`${this.name}_interval_${count}`, this.loggerService)<br>        ).subscribe();<br>      }<br>    <br>      getData(title: string): void {<br>        const id = `${this.constructor.name.toLowerCase()}_get_${title}`<br>        const url = &#39;https://jsonplaceholder.typicode.com/&#39; + title;<br>        interval(2000).pipe(<br>          switchMap(() =&gt; this.httpClient.get(url)),<br>        ).pipe(<br>          takeUntil(this.destroyService.getDestroy$(id)),<br>          activeSubs(id, this.loggerService),<br>        ).subscribe();<br>      }<br>}</pre><p>So, after 3 seconds, it will make 5 observables at intervals and emit data every 1 second. I also added a new worst case by hitting 6 APIs for every 2 seconds. I will subscribe to all of them.</p><p>Now, let’s see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8Ob9K4Z49vD2rLOubKjYA.gif" /><figcaption>Test Worst Case</figcaption></figure><p>I paused the app for 1 minute and you will see the CPU usage will increase too high. That is because we have a lot of subscriptions. Once we click unsubscribe all, then all the subscriptions will be stopped and the reduction in CPU usage will be very significant and that is good for the application.</p><p>You can check the project in this repository:</p><p><a href="https://github.com/afifalfiano/test-library">afifalfiano/test-library: Test Library Monitor Subscription</a></p><h4>Conclusion</h4><p>As an Angular Developer, we have to be conscious and careful about performance especially when we use subscription or observable data. I hope, this article and tools are useful for you to improve your application.</p><blockquote>Keep in mind, only use this library in development mode. Thank you for reading this article.</blockquote><h4>References</h4><p><a href="https://www.npmjs.com/package/monitor-subscription">monitor-subscription — npm</a></p><p><a href="https://github.com/afifalfiano/test-library">afifalfiano/test-library: Test Library Monitor Subscription</a></p><p>#Angular #Performance #RxJs #Monitor #Subscription #Observable</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee2e7d57f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJs: Expose functions/variables children to parent component with useImperativeHandle]]></title>
            <link>https://afifalfiano.medium.com/expose-function-variable-children-to-parent-with-useimperativehandle-on-reactjs-41f1190d663e?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f1190d663e</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[useimperativehandle]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 05:25:19 GMT</pubDate>
            <atom:updated>2025-03-08T08:03:38.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Photo by Pavel Danilyuk from Pexels: https://www.pexels.com/photo/a-person-holding-a-pencil-8640082/" src="https://cdn-images-1.medium.com/max/600/1*nnUkPG06ATnIb9pTrq2Mlg.jpeg" /><figcaption>Photo by Pavel Danilyuk from Pexels: <a href="https://www.pexels.com/photo/a-person-holding-a-pencil-8640082/">https://www.pexels.com/photo/a-person-holding-a-pencil-8640082/</a></figcaption></figure><p>Hi everyone, I think it’s been a while ya when the last time I have posted the tutorials. Now, I’m a bit missed to share my journey or story on the tech stuff.</p><p>So, to save our time, I’m going to create tutorial about reactjs on particulary is feature of <strong>useImperativeHandle.</strong> But, before we dive into the tutorial, have you ever heard about this thing?</p><p>or have you ever faced some causes on your project that you want to accessing function/variable on the children from the parent component.</p><p>Let’s take a look on this image, how did you do to resolve this problem?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*AOG8GZuWaehSnTdUe_WRWQ.png" /><figcaption>Simple Case</figcaption></figure><h3>Without useImperativeHandle</h3><p>I think, most of us are familiar with the approach to drill down props and state from parent to child or otherwise from child to parent with the same way. Basically, I usually do this one before I know about useImperativeHandle.</p><pre>import { forwardRef, useImperativeHandle, useRef, useState } from &#39;react&#39;;<br><br>const Parent = () =&gt; {<br>const [stateParent, setStateParent] = useState(&#39;State Parent&#39;);<br>const [isClicked, setIsClicked] = useState(false);<br>const [stateFromChildren, setStateFromChildren] = useState(&#39;&#39;);<br><br>const getValueFromChild = (data: any) =&gt; {<br>    console.log(data, &#39;data&#39;);<br>    // will be received value of stateA<br>    setStateFromChildren(data);<br>  };<br>  const checkValue = () =&gt; {<br>    setIsClicked((prev) =&gt; !prev);<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        type=&quot;button&quot;<br>        onClick={checkValue}<br>        style={{ border: &#39;1px solid black&#39; }}<br>      &gt;<br>        Check Data From Parent<br>      &lt;/button&gt;<br>      {isClicked &amp;&amp; &lt;p&gt;This is value from children: {stateFromChildren}&lt;/p&gt;}<br>      &lt;Children stateParent={stateParent} drillUpShowA={getValueFromChild} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>const Children = (props: any) =&gt; {<br>  const [stateA, setStateA] = useState(&#39;A&#39;);<br>  const sendValueShowA = () =&gt; {<br>    props?.drillUpShowA &amp;&amp; props?.drillUpShowA(stateA);<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;br /&gt;<br>      &lt;button<br>        type=&quot;button&quot;<br>        onClick={sendValueShowA}<br>        style={{ border: &#39;1px solid black&#39; }}<br>      &gt;<br>        Send Value Show A<br>      &lt;/button&gt;<br>      &lt;p&gt;This is state on children: {stateA}&lt;/p&gt;<br>      &lt;p&gt;This is state parent on children: {props?.stateParent} &lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default Parent;</pre><p>Are you familiar with that approach? I guess yes, you’re familiar with that.</p><p>Here the completed project of the above codes.</p><p><a href="https://stackblitz.com/edit/vitejs-vite-nye89m2r?file=src%2FApp.tsx&amp;terminal=dev">Demo — not used useImperativeHandle (forked) — StackBlitz</a></p><h3>With useImperativeHandle</h3><p>Allright guys, I think we can use another approach to make our code getting better and better. This’s a feature from ReactJs itself, yap we can use useImperativeHandle hooks.</p><p>Actually, we are not only using useImperativeHandle hooks but also useRef hooks. So, let’s refactor that code to be a better way.</p><pre>import { forwardRef, useImperativeHandle, useRef, useState } from &#39;react&#39;;<br><br>const Parent = () =&gt; {<br>  const [stateParent, setStateParent] = useState(&#39;State Parent&#39;);<br>  const [stateFromChildren, setStateFromChildren] = useState(&#39;&#39;);<br>  const [isClicked, setIsClicked] = useState(false);<br>  const ref = useRef&lt;any&gt;(null);<br>  const getValueFromChild = () =&gt; {<br>    if (ref.current) {<br>      const valueStateA = ref.current.getValueStateA();<br>      console.log(valueStateA);<br>      // will be received value of stateA from ref<br>      setStateFromChildren(valueStateA);<br>      setIsClicked((prev) =&gt; !prev);<br>    }<br>  };<br>  const ChildrenProps = {<br>    stateParent,<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        style={{ border: &#39;1px solid black&#39; }}<br>        type=&quot;button&quot;<br>        onClick={getValueFromChild}<br>      &gt;<br>        Check Data<br>      &lt;/button&gt;<br>      {isClicked &amp;&amp; (<br>        &lt;p&gt;<br>          This is value from children and render on parent component:<br>          {stateFromChildren}<br>        &lt;/p&gt;<br>      )}<br>      &lt;Children ref={ref} {...ChildrenProps} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>type ChildrenRefProps = {<br>  getValueStateA: () =&gt; void;<br>};<br>type ChildrenProps = {<br>  stateParent: string;<br>};<br>const Children = forwardRef&lt;ChildrenRefProps, ChildrenProps&gt;(<br>  (props: any, ref) =&gt; {<br>    const [stateA, setStateA] = useState(&#39;A&#39;);<br>    useImperativeHandle(<br>      ref,<br>      () =&gt; {<br>        return {<br>          getValueStateA: () =&gt; {<br>            return stateA;<br>          },<br>        };<br>      },<br>      []<br>    );<br>    return (<br>      &lt;div&gt;<br>        &lt;p&gt;This is value of StateA: {stateA}&lt;/p&gt;<br>        &lt;p&gt;This is value of StateParent: {props?.stateParent}&lt;/p&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>);<br>export default Parent;</pre><p>So, that’s simple example of how to combine useImperativeHandle and useRef on the ReactJs. So, basically, with useImperativeHandle we can expose all functions or variables on the children to parent, but I guess it also can implement with siblings component ya, but you need more effort to wrap it and make it shareable, rather than use that, I think we can use different approcah ya, for example using state management like context or state management like redux and etc.</p><p>So, by default to use useImperativeHandle we have to remember about this format</p><pre>useImperativeHandler(nameRef, () ⇒ {<br>	// expose functions/varaibles<br>	return {<br>         ....<br>        }<br>}, [dependencies])</pre><p>Here, several tips when the right time to use useImperativeHandle?</p><ul><li>When the parent component needs to interact with the child component’s methods or properties.</li><li>When the child component has complex internals that you don’t want to directly expose.</li><li>When creating reusable components with a controlled API for ref-based interactions.</li></ul><p>Also, please keep in mind, please don’t overusing this feature because it can lead to tightly coupled components, making them harder to manage or test. <strong>Use it sparingly and only when absolutely necessary.</strong></p><p>Oke, I think that’s all about tutorial how to use useImperativeHandle to expose functions/variables from children to parent.</p><p>I hope this tutorial is useful and make an impact of your knowledge of this feature. I really appreciate yourself because you want to spend your time to write my article. Feel free to give me feedback to make it better and better for my posts.</p><p>Here for the completed code with useImperativeHandle.</p><p><a href="https://stackblitz.com/edit/vitejs-vite-6abwb7px">https://stackblitz.com/edit/vitejs-vite-6abwb7px</a></p><h3>References:</h3><p><a href="https://react.dev/reference/react/useImperativeHandle">https://react.dev/reference/react/useImperativeHandle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f1190d663e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intersection Observer API: Lazy Load Scroll Data on Angular.]]></title>
            <link>https://afifalfiano.medium.com/intersection-observer-api-lazy-load-scroll-data-on-angular-59f5cc13b789?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f5cc13b789</guid>
            <category><![CDATA[intersection-observer]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Mon, 27 May 2024 00:49:43 GMT</pubDate>
            <atom:updated>2024-12-13T13:32:27.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvZx-T7JI-KRlDGQjYtpLA.jpeg" /><figcaption>Intersection Observer API</figcaption></figure><p>Have you ever thought about what looks like the mechanism of libraries for an infinite scroll? They will load or request the data once the scroll indicator until to the bottom of the bar. How can it be?</p><p>So, today I’m gonna share a bit of tutorial about how to create a simple infinite scroll using intersection observer. So, we can create it with the <strong>Intersection Observer API</strong>, and no need to install a third library. It can reduce the bundle size of the project.</p><p>As a developer, we should have a mindset to not always install third-party libraries to cover up the feature if the feature can built from scratch. it’s a good mindset for developers and will improve your skills.</p><h4>Intro</h4><p>What is an Intersection Observer? Based on the developer.mozilla.org the definition of that thing is:</p><blockquote>The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/Viewport">viewport</a>.</blockquote><p>Simply, we can use an intersection observer to support lazy load when loading data on scrolling.</p><h4>Setup</h4><p>I would like to use angular for this tutorial and you can initialize the project or maybe clone it from this repository. <a href="https://github.com/afifalfiano/angular-tutorial-blogs">https://github.com/afifalfiano/angular-tutorial-blogs</a></p><h4>Run Project</h4><p>After that, you can run the project to ensure there is no error on the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*672-fBf6DnqAH9YfLgLP-g.png" /><figcaption>First init run the project</figcaption></figure><p>Great, the project is running well. So, we can jump into the next step.</p><h4>API</h4><p>Here, we’re gonna use the API from <a href="https://randomuser.me/documentation#pagination">https://randomuser.me/documentation#pagination</a> and use the pagination as well.</p><h4>Consume API</h4><p>The next step is to consume API as usual on Angular. We need to import HTTPClientModule to use httpClient.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br><br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { HttpClientModule } from  &#39;@angular/common/http&#39;;<br><br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    HttpClientModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>Next, update app.component.ts to consume API and render the data.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { RandomUserService } from &#39;./services/random-user.service&#39;;<br>import { Payload } from &#39;./interfaces/requests/payload&#39;;<br>import { HttpErrorResponse } from &#39;@angular/common/http&#39;;<br>import { User } from &#39;./interfaces/responses/user&#39;;<br>import { Info } from &#39;./interfaces/responses/results&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit {<br>  title = &#39;angular-tutorial-blogs&#39;;<br>  userList: User[] = [];<br>  info?: Info;<br>  constructor(<br>    private randomUserService: RandomUserService<br>  ) {}<br><br>  ngOnInit(): void {<br>    this.getRandomUser();<br>  }<br><br>  getRandomUser(): void {<br>    const payload: Payload = {<br>      results: 10,<br>      page: 1<br>    };<br>    this.randomUserService.getRandomUser(payload).subscribe({<br>      next: ({info, results}) =&gt; {<br>        this.info = info;<br>        this.userList = results;<br>        console.log(this.userList)<br>        console.log(this.info)<br>      },<br>      error: (err: HttpErrorResponse) =&gt; {<br>        throw new Error(err.message);<br>      }<br>    })<br>  }<br>}</pre><p>Update app.component.html to render variables from response hit API.</p><pre>&lt;h1&gt;Random User List&lt;/h1&gt;<br>&lt;div class=&quot;wrap-user&quot;&gt;<br>  &lt;p&gt;Current Meta: &lt;/p&gt;<br>  &lt;span&gt;Total: {{info?.results}}&lt;/span&gt; |<br>  &lt;span&gt;Page: {{info?.page}}&lt;/span&gt;<br>  &lt;ul style=&quot;overflow-y: scroll; max-height: 100px;&quot;&gt;<br>    &lt;li *ngFor=&quot;let user of userList;&quot;&gt;<br>      {{user.email}}<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>So, the user interface will be like this. Just a simple UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcxBNKbfDQyvqY8aqI09bQ.png" /><figcaption>How to consume API on Angular</figcaption></figure><p>Finish, we have already successfully hit API and rendered the response on the HTML.</p><p><strong>I want to add a feature for infinite scroll to hit API. Once the user scrolls until the bottom of the maximum height element (bar), it will automatically hit API for the next pages with the same limit. It is time to use an intersection observer.</strong></p><h4>Infinite Scroll</h4><p>I will give you a simple demo of this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*a5NXrFgOLV0LhYoLos3mlg.gif" /><figcaption>Intersection Observer</figcaption></figure><p>Interesting, isn’t it?</p><p>Okee, Let’s jump to the next step.</p><p>First, update the app.component.html</p><pre>&lt;h1&gt;Random User List&lt;/h1&gt;<br>&lt;div class=&quot;wrap-user&quot;&gt;<br>  &lt;p&gt;Current Meta: &lt;/p&gt;<br>  &lt;span&gt;Limit: {{info?.results}}&lt;/span&gt; |<br>  &lt;span&gt;Page: {{info?.page}}&lt;/span&gt; |<br>  &lt;span&gt;Total: {{userList.length}}&lt;/span&gt;<br>  &lt;ul style=&quot;overflow-y: scroll; max-height: 100px; height: 100px;&quot;&gt;<br>    &lt;ng-container *ngFor=&quot;let user of userList; let i = index; let first = first; let last = last&quot;&gt;<br>      &lt;li *ngIf=&quot;!last&quot;&gt;<br>        {{user.email}}<br>      &lt;/li&gt;<br>      &lt;li *ngIf=&quot;last&quot; #targetObserver [id]=&quot;&#39;last-list&#39;&quot;&gt;<br>        {{user.email}}<br>      &lt;/li&gt;<br>    &lt;/ng-container&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>We need to separate the last element that needs to be attached intersection observer and a normal element. So, I use the <strong>last </strong>feature from ngFor itself, and on the element list I put template reference targetObserver with the id name is last-list.</p><p>Next, update the app.component.ts</p><pre>  @ViewChild(&#39;targetObserver&#39;) targetObserver?: ElementRef;<br>  options = { rootMargin: &#39;0px&#39;, threshold: 0.5, root: null }<br>  observer: IntersectionObserver = new IntersectionObserver(this.handleObserver.bind(this), this.options);<br>  MAXIMUM_DATA = 100;</pre><p>We need to control the element list that has template references. We can use <strong>ViewChild </strong>decorator.</p><p>Next, we need to define the configuration for the default intersection observer on the variable <strong>options</strong>.</p><p>Then, define variable observer with an instance of class <strong>IntersectionObserver </strong>with two parameters, the first one is for <strong>callback </strong>and the rest for <strong>options</strong>.</p><p>After that, let’s create the function handleObserver. I use bind on the function handleObserver cause the inside of the function needs to access the data outside of the function, if you don’t use bind it only can access the data inside of the class IntersectionObserver.</p><pre>  handleObserver(entries: any[]) {<br>    entries.forEach(entry =&gt; {<br>      const {<br>      boundingClientRect,<br>      intersectionRatio,<br>      intersectionRect,<br>      isIntersecting,<br>      rootBounds,<br>      target,<br>      time<br>      } = entry;<br>      console.log(entry)<br>      if (isIntersecting) {<br>        if (this.userList.length &lt; this.MAXIMUM_DATA) {<br>          this.info = {<br>            ...this.info,<br>            page: (this.info?.page || 0) + 1<br>          }<br>          this.getRandomUser();<br>        }<br>      }<br>    })<br><br>  };</pre><p>So, on the function handleObserver, we need to get the first array cause the response of the callback intersection observer on the array. Then I get the key <strong>isIntersecting </strong>which means the user interacts until the bottom of the bar. Then, I added some logic if the <strong>total number of users is less than the maximum data,</strong> in this case, I hard coded to 100 data. So, it will update the parameters of the page or pagination and call the API to get random users. Then, it will re-fetch the API with a new payload.</p><p>Finally, update the function <strong>getRandomUser</strong>. I just updated the payload. Previously, I hardcoded the payload, but currently, I want to more dynamically, So I use the data from <strong>info </strong>which is the metadata of API like <strong>total, results, page, </strong>etc.</p><p>Also, don’t forget to update the user list, I use the function <strong>spread </strong>on the array. So, I copy the old data and then merge it with new data.</p><pre>  getRandomUser(): void {<br>    const payload: Payload = {<br>      results: this.info?.results || 10,<br>      page: this.info?.page || 1<br>    };<br>    this.randomUserService.getRandomUser(payload).subscribe({<br>      next: ({info, results}) =&gt; {<br>        this.info = info;<br>        this.userList = [...this.userList, ...results];<br>      },<br>      error: (err: HttpErrorResponse) =&gt; {<br>        throw new Error(err.message);<br>      }<br>    })<br>  }</pre><p>The results will be like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*a5NXrFgOLV0LhYoLos3mlg.gif" /><figcaption>Demo Intersection Observer</figcaption></figure><h4>Conclusion</h4><p>You can use an intersection observer to create your infinite scroll feature, or a lazy load of some element, that will be fine. The advantage of this feature is better performance. Also, you don’t need to install a third-party library if only want to create a simple infinite scroll pagination.</p><h3>References</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer API - Web APIs | MDN</a></li><li><a href="https://randomuser.me/documentation#pagination">Random User Generator</a></li></ul><p>#WebApi #IntersectionObserver #Angular #Frontend #Web #WebPerformance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f5cc13b789" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Workers API: A Way to Improve Web Performance]]></title>
            <link>https://afifalfiano.medium.com/web-workers-api-a-way-to-improve-web-performance-2e23642f1b3e?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e23642f1b3e</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Thu, 23 May 2024 04:28:32 GMT</pubDate>
            <atom:updated>2024-05-23T04:28:32.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWShKEg1NAKUVrVXDmNLoA.jpeg" /><figcaption>Web Worker</figcaption></figure><p>Hi Everyone,</p><p>It’s been a while since the last time I published an article last year. Today, we’re gonna talk about web workers. Have you used web workers on your web apps on the production level? You might be confused about why I need to implement it.</p><h4><strong>Intro</strong></h4><p>Let’s use a study case to make it easier to understand the web worker. I had bad experiences while developing web apps such as bad performance causing several things like nested iteration or complex logic that will affect your web performance. But, ya it was part of my journey. So, time by time I find a way to improve web performance and one of a bunch solutions that I have is using web workers.</p><p>But, in this tutorial, I just use a simple example like an iteration until 1K or maybe more, maybe you can image some feature like reading data file Excel from the client side that has data of more than 10K rows. If you only using the main thread, it will a longer until the processing data is completed. So, yeah that is a simple example. I don’t want to show how to read data on file Excel using web workers, but just a simple example.</p><p>Also, in this tutorial, I’m using Angular as a front-end framework.</p><h4><strong>Setup</strong></h4><p>First of all, please prepare your project or you can clone the project from this repository <a href="https://github.com/afifalfiano/angular-tutorial-blogs.git">https://github.com/afifalfiano/angular-tutorial-blogs.git</a></p><p>Next, when using angular we can use the command to generate a web worker. Run this command.</p><pre>ng generate web-worker app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*PmMCFU_yfuivZf9biwWmpg.png" /><figcaption>Generate Web Worker on Angular</figcaption></figure><p>Actually, you can generate web worker locations in any place. By default, the format command like this <strong>ng generate web-worker &lt;location&gt;</strong></p><p>Let’s try to use the worker with the default response. Once you generate a web worker, it will automatically generate a script on app.component.ts to debug the web worker like this.</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  title = &#39;angular-tutorial-blogs&#39;;<br>}<br><br>if (typeof Worker !== &#39;undefined&#39;) {<br>  // Create a new<br>  const worker = new Worker(new URL(&#39;./app.worker&#39;, import.meta.url));<br>  worker.onmessage = ({ data }) =&gt; {<br>    console.log(`page got message: ${data}`);<br>  };<br>  worker.postMessage(&#39;hello&#39;);<br>} else {<br>  // Web Workers are not supported in this environment.<br>  // You should add a fallback so that your program still executes correctly.<br>}</pre><p>Then, I have to change the code app.component.ts to fix an error.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit {<br>  title = &#39;angular-tutorial-blogs&#39;;<br><br><br>  ngOnInit(): void {<br>    this.initWebWorker();<br>  }<br><br>  initWebWorker(): void {<br>    if (typeof Worker !== &#39;undefined&#39;) {<br>      // Create a new<br>      const worker = new Worker(new URL(&#39;./app.worker&#39;, import.meta.url));<br>      worker.onmessage = ({ data }) =&gt; {<br>        console.log(`page got message: ${data}`);<br>      };<br>      worker.postMessage(&#39;hello&#39;);<br>    } else {<br>      // Web Workers are not supported in this environment.<br>      // You should add a fallback so that your program still executes correctly.<br>    }<br>  }<br>}</pre><p>Then, run the project.</p><pre>npm run start</pre><p>Yeah, you will get a response from the web worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm3rdMGkqNziYflSNNTw0Q.png" /><figcaption>First Init Use Web Worker</figcaption></figure><h4>Study Case</h4><p>After the web workers run well, let’s modify the code and make some logic to compare the logic that runs on the main thread and the worker thread.</p><p>I have created a simple UI, only button, and have even loaded data iteration. Once the user clicks this button it will generate and render data.</p><h4>Main Thread</h4><pre>loadData(): void {<br>    console.time(&#39;time execution&#39;);<br>    const maxNumber = 10_000;<br>    for (let i = 0; i &lt; maxNumber; i++) {<br>      this.data.push(i.toString());<br>    }<br>    console.timeLog(&#39;time execution&#39;);<br>  }</pre><p>So, this is the result if we run the logic on the main thread</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bx5ee5zU91p1A_1CndlH7w.png" /><figcaption>Time execution on the main thread</figcaption></figure><p>it takes 1.722900390625 ms. Not too long ya, but can you imagine for 1000K, it will be heavy on the client side, right?</p><h4>Worker Thread</h4><p>I updated the worker config like this.</p><pre>/// &lt;reference lib=&quot;webworker&quot; /&gt;<br><br>addEventListener(&#39;message&#39;, ({data}) =&gt; {<br>  const {method, response} = data;<br>  switch (method) {<br>    case &#39;greeting&#39;:<br>        const intro = `worker response to ${data.response}`;<br>        postMessage({<br>          method,<br>          result: intro<br>        });<br>      break;<br>    case &#39;logic&#39;:<br>      const {maxNumber} = response;<br>      const collect =  [];<br>      for (let i = 0; i &lt; maxNumber; i++) {<br>        collect.push(i.toString());<br>      }<br>      postMessage({<br>        method,<br>        result: collect<br>      });<br>    break;<br><br>    default:<br>      break;<br>  }<br>});</pre><p>Then, I also update app.component.ts to post messages on web worker.</p><pre>  import { Component, OnInit } from &#39;@angular/core&#39;;<br><br>  @Component({<br>    selector: &#39;app-root&#39;,<br>    templateUrl: &#39;./app.component.html&#39;,<br>    styleUrls: [&#39;./app.component.scss&#39;]<br>  })<br>  export class AppComponent implements OnInit {<br>    title = &#39;angular-tutorial-blogs&#39;;<br>    data: string[] = [];<br>    worker = new Worker(new URL(&#39;./app.worker&#39;, import.meta.url));<br>    ngOnInit(): void {<br>      this.initWebWorker();<br>    }<br><br>    initWebWorker(): void {<br>      if (typeof Worker !== &#39;undefined&#39;) {<br>        // Create a new<br>        const body = {<br>          method: &#39;greeting&#39;,<br>          response: &#39;hello&#39;<br>        };<br>        this.worker.postMessage(body);<br><br>        this.getResponseWorker();<br>      } else {<br>        // Web Workers are not supported in this environment.<br>        // You should add a fallback so that your program still executes correctly.<br>      }<br>    }<br><br><br>    getResponseWorker(): void {<br>      this.worker.onmessage = ({ data }) =&gt; {<br>        const {method, result} = data;<br>        switch (method) {<br>          case &#39;greeting&#39;:<br>            console.log(`page got message: ${result}`);<br>            break;<br>          case &#39;logic&#39;:<br>            this.data = [...result];<br>            break;<br><br>          default:<br>            break;<br>        }<br>      };<br>    }<br><br><br>    loadData(): void {<br>      console.time(&#39;time execution&#39;);<br>      const maxNumber = 10_000;<br>      // for (let i = 0; i &lt; maxNumber; i++) {<br>      //   this.data.push(i.toString());<br>      // }<br>      const body = {<br>        method: &#39;logic&#39;,<br>        response: {<br>          maxNumber<br>        }<br>      };<br>      this.worker.postMessage(body)<br>      console.timeLog(&#39;time execution&#39;);<br>    }<br>  }</pre><p>Cause I only have one config Worker.js, So I separate them with the config method. When the postMessage is logic it will run logic for 10K iteration.</p><p>Here is an explanation of the event worker.</p><ul><li><em>postMessage : The event worker to sends data on a worker thread.</em></li><li><em>onMessage: The event worker to listen real-time data after trigger using postMessage.</em></li><li><em>onError: The event worker to handle error data.</em></li></ul><p>For more details, you can go and visit this website <a href="https://medium.com/r?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FWeb_Workers_API%2FUsing_web_workers">https://medium.com/r?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FWeb_Workers_API%2FUsing_web_workers</a></p><p>So, the result will be like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKfJ0Bq3uQtHcNJShACmcQ.png" /><figcaption>Time execution on a worker thread</figcaption></figure><p>Awesome!. it takes only 0.22~ ms.</p><p>Also, you can check on the monitoring performance to check when the worker thread runs on dev tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUktS0MrOYClKwSEBiCqvw.png" /><figcaption>Debug Worker Thread</figcaption></figure><p>Yeah, I think that’s all for a simple introduction about web workers on angular. Maybe you don’t need it right now, and that’s fine. Nevertheless, I believe in the future this feature will help us a lot.</p><p>If you want to see all the codes, you can check in this repository <a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/web-worker">https://github.com/afifalfiano/angular-tutorial-blogs/tree/web-worke</a>r</p><p>Thank you for reading this tutorial, I hope it is useful and can improve your performance on web apps. Sharing is caring.</p><h3><strong>References</strong></h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using Web Workers - Web APIs | MDN</a></li><li><a href="https://angular.io/guide/web-worker">Angular</a></li></ul><p>#Angular #WebWorker #Performance #WebDev #Frontend</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e23642f1b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Generate & Validate Sitemap to Improve the new SEO.]]></title>
            <link>https://afifalfiano.medium.com/javascript-generate-validate-sitemap-to-improve-the-seo-7458e79505e5?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7458e79505e5</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 03:58:48 GMT</pubDate>
            <atom:updated>2023-09-24T11:54:00.014Z</atom:updated>
            <content:encoded><![CDATA[<p>Generate and validate sitemap.xml with javascript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qguZlyiAhYYMGCh4Yrc-Sg.jpeg" /><figcaption>Generate Sitemap</figcaption></figure><p>Hi everyone, Hopefully, you are healthy and well.</p><p>Long time no see yaa, In this article I want to share how to generate sitemap.xml for a website with javascript.</p><p>The sitemap.xml is very important for SEO because it will give your website a good score on SEO. Also, to make how your pages on your website show on the first-page search engine Google.</p><h3>Intro</h3><p>We will discuss sitemap.xml in the website that uses SPA (Single Page Applications) like angular, react, vue, etc. Maybe we know that a lot of websites can generate sitemaps for websites that are already hosted. Just copy the link and walaaa, the file sitemap.xml is already done. You just need to download that file and upload it on your hosting website.</p><p>But, what about if we have ourself API to generate every single page with dynamics like every book, song, and other thing?</p><p>Don’t worry, we can create our sitemap.xml with some script and just run it once, So, it will generate a file sitemap.xml with all of the link detail content like<em> name-of-website/link-detail-from-api .</em></p><p>Also, if you want to automatically run the script once a month you can create a cron-job to run the script on the server and the file sitemap.xml will update every month.</p><h3>Setup</h3><p>First, we need to install this library. To convert the JSON to XML or otherwise.</p><pre>npm i --save-dev xml-js</pre><p>Also, need to install fetch-node to run fetching data from node env.</p><pre>npm i --save-dev node-fetch@2.6.1</pre><p>The reason why we need a specific version is because we can still use require, but if we use the greater than version of that it will get an error <a href="https://stackoverflow.com/questions/70820079/error-err-require-esm-require-of-es-module-not-supported">Error [ERR_REQUIRE_ESM]: require()</a></p><p>Next, create file index.js and define this variable</p><pre>const fs = require(&#39;fs&#39;);<br>const convert = require(&#39;xml-js&#39;);<br>const fetch = require(&#39;node-fetch&#39;);<br>const hostBaseURL = &#39;http://website.com/detail&#39;;<br>const untrackedUrlsList = [];<br>const options = { compact: true, ignoreComment: true, spaces: 4 };<br>let totalData = 0;</pre><p>Information:</p><ul><li>fs is a library for read-and-write file system</li><li>convert is a library for converting JSON to XML or otherwise</li><li>fetch is a library for fetching data from node env</li><li>hostBaseURL is the address URL</li><li>untrackedUrlsList is a variable to save data from fetching data</li><li>options are default config to read or write files using xml-js</li><li>totalData is a variable that will be a parameter for using pagination when fetching Data.</li></ul><p>Then, we need to create a template file sitemap.xml like this.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;urlset xmlns=&quot;http://www.sitemaps.org/schemas/sitemap/0.9&quot;&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;http://website.com/&lt;/loc&gt;<br>        &lt;priority&gt;1.00&lt;/priority&gt;<br>    &lt;/url&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;http://website.com/detail/delectus-aut-autem?id=1&lt;/loc&gt;<br>        &lt;priority&gt;0.80&lt;/priority&gt;<br>    &lt;/url&gt;<br>&lt;/urlset&gt;</pre><p>In this article, We use open API from jsonplaceholder.</p><p><a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a></p><p>Let’s continue to write code in index.js</p><p>Create an async arrow function fetchData with parameter limit and start to call API with pagination.</p><pre>const fetchData = async (limit = 10, start= 0) =&gt; {<br>        try {<br>            const url = `https://jsonplaceholder.typicode.com/todos?_limit=${limit}&amp;_start=${start}`;<br>            const data = await fetch(url)<br>            return data.json();<br>        } catch (error) {<br>            console.log(error);<br>        }<br>}</pre><p>Next, create an arrow function generateSitemap like this</p><pre>const generateSitemap = async () =&gt; {<br>    try {<br>        const callAPI = [];<br>        const initAPI = await fetchData(10, 0);<br>        totalData = initAPI?.totalPage || 200;<br>        for (let index = 1; index &lt;= totalData; index++) {<br>            callAPI.push(fetchData(10, index));<br>        }<br>        const data = await Promise.all([...callAPI]);<br>        data.forEach(item =&gt; {<br>            collectSitemap(item);<br>        })<br>        filterUniqueURLs();<br>    } catch (error) {<br>        console.log(error);<br>    }<br>}</pre><p>We use try-catch to fetch data. Then, we need to call the API first to know how much total data the API has. Usually for the model API has a key totalPage but in this case, I just put 200, because the API doesn’t have totalPage, but has a limit of 200 data from the API itself.</p><p>After that, use for to iterate to collect all hit API from start 0 until 200. Then we save the URL promise hit API into variable callAPI.</p><p>Next, use await promise.all to retrieve all data from 0 until 200 with pagination data.</p><p>The response API is like this.</p><pre>https://jsonplaceholder.typicode.com/photos?_start=0&amp;_limit=5</pre><pre>Responses: <br>[{<br>        &quot;userId&quot;: 1,<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;delectus aut autem&quot;,<br>        &quot;completed&quot;: false<br>  },<br>  {<br>        &quot;userId&quot;: 1,<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;quis ut nam facilis et officia qui&quot;,<br>        &quot;completed&quot;: false<br>   },<br>...<br>]</pre><p>After that, we need to create the function collectSitemap.</p><pre>const collectSitemap = (data = []) =&gt; {<br>    if (data.length &gt; 0) {<br>        data.forEach(item =&gt; {<br>            const modifiedURL = item.title.replace(/[@\s!^\/\\#,+()$~%.&#39;&quot;:*?&lt;&gt;{}]/g, &#39;-&#39;).toLowerCase() + `?id=${item.id}`;<br>            const encodingURL = encodeURI(modifiedURL);<br>            untrackedUrlsList.push(`${hostBaseURL}/${encodingURL}`);<br>        });<br>    }<br>}</pre><p>That function is to create a dynamic URL with format <em>domain/detail?id=number. </em>Because the retrieve data from promise.all is an array, So, we need to iterate the item and then create a format URL and save it into the untrackedUrlsList.</p><p>The function of the regex is to remove all of the special characters like <em>[@\s!^\/\\#,+()$~%.’”:*?&lt;&gt;{}]</em> and likefrom the URL and to ensure the URL is valid we use encodeURI. The URL becomes like this <a href="http://website.com/detail/ipsa-repellendus-fugit-nisi?id=12"><em>http://website.com/detail/ipsa-repellendus-fugit-nisi?id=12</em></a></p><p>After executing the function collectSitemap inside of iteration, we need to create the function filterUniqueURLs</p><pre>const filterUniqueURLs = () =&gt; {<br>    const newDate = new Date();<br>    const date = [ newDate.getFullYear(), (&#39;0&#39; + (newDate.getMonth() + 1)).slice(-2), (&#39;0&#39; + newDate.getDate()).slice(-2)].join(&#39;-&#39;);<br>    fs.readFile(&#39;sitemap.xml&#39;, (err, data) =&gt; {<br>        if (data) {<br>            const existingSitemapList = JSON.parse(convert.xml2json(data, options));<br>            let existingSitemapURLStringList = [];<br>            if (existingSitemapList.urlset &amp;&amp; existingSitemapList.urlset.url &amp;&amp; existingSitemapList.urlset.url.length) {<br>                existingSitemapURLStringList = existingSitemapList.urlset.url.map(ele =&gt; ele.loc._text);<br>            }<br><br>            const removeDuplicate = [...new Set(untrackedUrlsList)];<br>            removeDuplicate.forEach((ele, i) =&gt; {<br>                if (existingSitemapURLStringList.indexOf(ele) == -1) {<br>                    existingSitemapList.urlset.url.push({<br>                        loc: {<br>                            _text: ele,<br>                        },<br>                        priority: {<br>                            _text: 0.8<br>                        },<br>                        changefreq: {<br>                            _text: &#39;monthly&#39;<br>                        },<br>                        lastmod: {<br>                            _text: date<br>                        }<br>                    });<br>                }<br>            });<br>            createAndSaveSitemapFile(existingSitemapList);<br>        }<br>    });<br>}</pre><p>The function is used to read the existing URL on file sitemap.xml, if the URL is existing, then skip it, but if there is a new URL, then collect it and save it with format loc and priority.</p><p>Actually, we can add multiple options on the sitemap.xml like a url, priority, changefreq, lastmode, etc.</p><p>As I said to read the file sitemap.xml we need to use xml-js and remove the duplicate URL using the function of new Set(array).</p><p>The format is like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*zSdKNIFVi10Dd9O9aXPR5Q.png" /><figcaption>existingSitemapList</figcaption></figure><p>The object is like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5CQTAx7ndXJBUnEWSTVag.png" /><figcaption>existingSitemapList.urlset.url</figcaption></figure><p>After that, we need to create the function createAndSaveSitemapFile</p><pre>const createAndSaveSitemapFile = (list) =&gt; {<br>    const finalXML = convert.json2xml(list, options);<br>    fs.writeFile(&#39;sitemap.xml&#39;, finalXML, (err) =&gt; {<br>        if (err) {<br>            return console.log(err);<br>        }<br><br>        console.log(&quot;Success generate sitemap.xml!&quot;);<br>    });<br>}</pre><p>Just convert the list of existingSitemapList to XML and update the file sitemap.xml</p><p>After we have generated a new sitemap.xml. Then, we want to validate is the URL valid or not with this function.</p><pre><br>const urlStatus = [];<br><br><br>function readFileSitemap() {<br>    fs.readFile(&#39;sitemap.xml&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>        if (err) {<br>            return console.log(err);<br>        }<br>        const { urlset: { url } } = JSON.parse(convert.xml2json(data, options));<br>        url.forEach((item, idx) =&gt; {<br>            const isValid = isValidUrl(item.loc._text);<br>            const splitUrl = item.loc._text.split(&#39;?id=&#39;);<br>            urlStatus.push({ <br>                url: item.loc._text,<br>                id: splitUrl[1],<br>                title: split[0].split(`${hostBaseURL}/`)[1],<br>                statusUrl: isValid <br>            })<br><br>        })<br><br>        writeLogSitemap()<br>    });<br>}<br><br>function writeLogSitemap() {<br>    let data = JSON.stringify(urlStatus, null, 2);<br><br>    fs.writeFile(&#39;log-sitemap.json&#39;, data, (err) =&gt; {<br>        if (err) throw err;<br>        console.log(&#39;Success create log&#39;);<br>    });<br>}<br><br>function isValidUrl(urlString) {<br>    var urlPattern = new RegExp(&#39;^(https?:\\/\\/)?&#39; + // validate protocol<br>        &#39;((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|&#39; + // validate domain name<br>        &#39;((\\d{1,3}\\.){3}\\d{1,3}))&#39; + // validate OR ip (v4) address<br>        &#39;(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*&#39; + // validate port and path<br>        &#39;(\\?[;&amp;a-z\\d%_.~+=-]*)?&#39; + // validate query string<br>        &#39;(\\#[-a-z\\d_]*)?$&#39;, &#39;i&#39;); // validate fragment locator<br>    return !!urlPattern.test(urlString);<br>}</pre><p>Information</p><ul><li>The function readFileSitemap is used to read data from the file sitemap.xml . Inside the function, we just get the URL. After that iterate it and check the URL with function isValidUrl.</li><li>The function isValidUrl is used to check the URL with regex if the URL is valid or not. If valid it will return true or otherwise.</li><li>Inside the iterate of the URL, we push on variable urlStatus with this format <em>{ url, id, title, isValid}. </em>After finishing the iterate we run the function to writeLogSitemap.</li><li>The function writeLogSitemap is used to write file log-sitemap.json from the data variable urlStatus.</li></ul><p>The last step is to execute the function generateSitemap and validate URL. Just add this code at the bottom of the code.</p><pre>generateSitemap();</pre><p>Don’t forget to call the function readFileSitemap() inside of the function createAndSaveSitemapFile like this</p><pre>const createAndSaveSitemapFile = (list) =&gt; {<br>    const finalXML = convert.json2xml(list, options);<br>    fs.writeFile(&#39;sitemap.xml&#39;, finalXML, (err) =&gt; {<br>        if (err) {<br>            return console.log(err);<br>        }<br><br>        console.log(&quot;Success generate sitemap.xml!&quot;);<br>        readFileSitemap();<br>    });<br>}</pre><h3>Result</h3><p>After the finished generated sitemap. The file sitemap.xml becomes like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-C3OnQytT5wv4mtNheJ-xw.png" /><figcaption>new sitemap.xml</figcaption></figure><p>And for the log-sitemap.json becomes like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I45inJN7udpJycWI_EAIUg.png" /><figcaption>log-sitemap.json</figcaption></figure><p>If you are curious about the code, here I put the link repository.</p><p><a href="https://github.com/afifalfiano/generate-validate-sitemap">GitHub - afifalfiano/generate-validate-sitemap: Tutorial</a></p><h3>Conclusions</h3><p>After we did this tutorial, we already know that it’s not too hard to create our own sitemap.xml, especially if we have API and need to improve the SEO.</p><p>Also, this is one of a lot of ways to improve the SEO, like we can improve the meta title, meta desc, meta image, and like that. Improve the image and alt and many other things.</p><p>Hopefully, this article is useful for you, thank you for reading this article.</p><h3>References</h3><ul><li><a href="https://pardeepjain.medium.com/how-to-create-dynamic-sitemap-xml-using-javascript-ee4d9ba7402a">How to create Dynamic Sitemap.xml using Javascript.</a></li><li><a href="https://www.freecodecamp.org/news/check-if-a-javascript-string-is-a-url/">How to Check if a JavaScript String is a Valid URL</a></li></ul><p>#javascript #SEO #sitemap #generate #validate</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7458e79505e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Optimization Bundle Size with Brotli]]></title>
            <link>https://afifalfiano.medium.com/angular-optimization-bundle-size-with-brotli-8222d753d6b2?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8222d753d6b2</guid>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 06:29:07 GMT</pubDate>
            <atom:updated>2023-06-17T06:29:32.448Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem: The bundle size is too large and makes website slower</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zvr0DMkhm-oAS86Sgp02Tw.jpeg" /><figcaption>Reduce Bundle Size</figcaption></figure><p>Hi everyone, in this section I want to share my experience about optimization bundle size, especially in Angular using Brotli. The main problem why am I using Brotli rather than Gzip is because the bundle size is too large to serve to the client. So, I need to do more research about how to optimize the application, and walaaa, I got the Brotli.</p><p>So, what is Brotli? In short, the main task of Brotli is to compress bundle size, which has an algorithm itself. The advantage of using Brotli (br) is to make the website load faster. If you have ever heard about Gzip, the Brotli is the same thing as that, and Brotli was developed by Google. For more information, you can visit this link down below.</p><p><a href="https://github.com/google/brotli">GitHub - google/brotli: Brotli compression format</a></p><p>Actually, I have a lot of questions about Brotli but one question that I want to highlight is, “is it Brotli does support a lot of versions of the browser?” Then I got the information and it was great.</p><figure><img alt="Supported Browser for Brotli" src="https://cdn-images-1.medium.com/max/1024/1*9ai17XpZEJZYeb696bGEgw.png" /><figcaption>Supported Browser for Brotli</figcaption></figure><p>The next is you should know the comparison of some methods with Brotli. The image below is a summary to compare Brotli with gzip, bzip2, and xz.</p><figure><img alt="A compression performance comparison between a number of different algorithms (Source: OpenCPU)." src="https://cdn-images-1.medium.com/max/1000/0*yd77eJkxtilafAiL.png" /><figcaption>A compression performance comparison between a number of different algorithms (Source: OpenCPU).</figcaption></figure><p>We know that the compression time of Brotli is higher than Gzip, but for decompression time Brotli is smaller than Gzip. This is the reason why the bundle size can be smaller and can improve the performance of applications.</p><p>I also recommended a blog about Brotli with more detailed information.</p><p><a href="https://devblogs.microsoft.com/dotnet/introducing-support-for-brotli-compression/">Introducing Support for Brotli Compression - .NET Blog</a></p><h3>Practice</h3><p>I think enough for the explanation, Let’s practice together. In this section, I’m using projects from previous blogs. You can clone or maybe create your own project.</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/communication-data-input-output">GitHub - afifalfiano/angular-tutorial-blogs at communication-data-input-output</a></p><p>Make sure you are in the branch <strong>communication-data-input-output </strong>and then create a new branch with run this command</p><pre>git checkout -b optimization-brotli</pre><p>Just try to run the project with this command</p><pre>npm run start</pre><p>If the project running well, that’s good</p><p>Next, we need to install an additional library to support the Brotli in Angular.</p><pre>npm install -D @angular-builders/custom-webpack compression-webpack-plugin brotli-webpack-plugin</pre><p>Then, update angular.json</p><p>Before updating angular.json</p><figure><img alt="Before updating angular.json" src="https://cdn-images-1.medium.com/max/843/1*7u6sZBQuUTuzuayc9oiKsg.png" /><figcaption>Before updating angular.json</figcaption></figure><p>After updating angular.json</p><figure><img alt="After updating angular.json" src="https://cdn-images-1.medium.com/max/908/1*dVGIvhq7n0CCMXE-pMWlVg.png" /><figcaption>After updating angular.json</figcaption></figure><p>Just updated the build lib and add customWebpackConfig on the options of build config.</p><p>Next, create the file webpack.config.js</p><pre>const CompressionPlugin = require(`compression-webpack-plugin`);<br>const BrotliPlugin = require(`brotli-webpack-plugin`);<br>module.exports = {<br>    plugins:[<br>        new BrotliPlugin({<br>            asset: &#39;[fileWithoutExt].[ext].br&#39;,<br>            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/<br>        }),<br>        new CompressionPlugin({<br>            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/,<br>            filename(info){<br>                let opFile= info?.filename?.split(&#39;.&#39;),<br>                opFileType =  opFile?.pop(),<br>                opFileName = opFile?.join(&#39;.&#39;);<br>                return `${opFileName}.${opFileType}.gzip`;<br>            }<br>        })<br>    ],<br>}</pre><p>The above script is to add plugin compression from Webpack (Gzip) and Brotli. For Brotli config we only apply on file js|css|html|svg|txt|eot|otf|ttf|gif .</p><p>After that, create a file brotli-compress.js</p><pre>const brotli = require(&#39;brotli&#39;)<br>const fs = require(&#39;fs&#39;)<br><br>const brotliSettings = {<br>  extension: &#39;br&#39;,<br>  mode: 0, // 0 = generic, 1 = text, 2 = font (WOFF2)<br>  quality: 11, // 0 - 11<br>  lgwin: 22 // window size<br>}<br><br>const path = &#39;dist/angular-tutorial-blogs&#39;;<br><br>fs.readdirSync(path).forEach(file =&gt; {<br>  if (file.endsWith(&#39;.js&#39;) || file.endsWith(&#39;.css&#39;) || file.endsWith(&#39;.html&#39;)) {<br>    const result = brotli.compress(fs.readFileSync(path + &#39;/&#39; + file), brotliSettings)<br>    if (result) {<br>      fs.writeFileSync(path + &#39;/&#39; + file + &#39;.br&#39;, result)<br>    }<br>  }<br>})</pre><p>The function file of brotli-compress is to compress the file with Brotli and write a file with extension .br</p><p>For the Brotli settings, you can check this link below</p><p><a href="https://www.npmjs.com/package/brotli">brotli</a></p><p>Then, we need a little adjustment on package.json</p><pre>{<br>  &quot;name&quot;: &quot;angular-tutorial-blogs&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;ng&quot;: &quot;ng&quot;,<br>    &quot;start&quot;: &quot;ng serve&quot;,<br>    &quot;build&quot;: &quot;ng build &amp;&amp; npm run postbuild&quot;,<br>    &quot;watch&quot;: &quot;ng build --watch --configuration development&quot;,<br>    &quot;test&quot;: &quot;ng test&quot;,<br>    &quot;postbuild&quot;: &quot;node brotli-compress.js&quot;<br>  },<br>...<br>}</pre><p>After that, try to build the project</p><pre>npm run build</pre><p>Finally, if your build is successful, there are files with extensions .js , .gzip, and .br</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*PwaitFPO9RblP6VvnTsFTw.png" /><figcaption>Compression File</figcaption></figure><p>Look at the size! That awesome.</p><p>After that just try to serve the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwuoSCUKnn_b5wTiLA0TJA.png" /><figcaption>Serve Project Client Side</figcaption></figure><p>But, we have a problem, the content that serves it is still .js</p><figure><img alt="Content-Encoding Brotli Not Working" src="https://cdn-images-1.medium.com/max/1024/1*fAuZF1n4eMCw2kTHrg7KHQ.gif" /><figcaption>Content-Encoding Brotli Not Working</figcaption></figure><p>Although we have several types files like .js , .gzip and .br . It’s still served in js if we serve the client side, the possible way to try the compression files is with server-side rendering or we create a server with express js.</p><p>To create a server, run this command.</p><pre>npm i express express-static-gzip</pre><p>After that, create a file server.js</p><pre><br>const path = require(&#39;path&#39;);<br>const express = require(&#39;express&#39;);<br>const expressStaticGzip = require(&#39;express-static-gzip&#39;);<br><br>const serverPort = 7000;<br>const server = express();<br><br>server.use(&quot;/&quot;, expressStaticGzip(path.join(__dirname + &#39;/dist/angular-tutorial-blogs&#39;), {<br>    enableBrotli: true<br>}));<br><br>server.get(/.*/, function (req, res, next) {<br>    if (req.headers[&#39;x-forwarded-proto&#39;] !== &#39;https&#39; &amp;&amp; process.env.NODE_ENV === &#39;production&#39;)<br>        res.redirect(&#39;https://&#39; + req.hostname + req.url);<br>    else<br>        res.sendFile(__dirname + &#39;/dist/angular-tutorial-blogs/index.html&#39;);<br>});<br><br>server.listen(process.env.PORT || serverPort, function () {<br>    console.log(&#39;Server. Port:%d&#39;, process.env.PORT || serverPort);<br>});</pre><p>Then, just run node server.js to run angular from server.</p><pre>node server.js</pre><p>To make it easier, just update the package.json</p><pre>  &quot;scripts&quot;: {<br>    &quot;ng&quot;: &quot;ng&quot;,<br>    &quot;start&quot;: &quot;ng serve&quot;,<br>    &quot;build&quot;: &quot;ng build &amp;&amp; npm run postbuild&quot;,<br>    &quot;watch&quot;: &quot;ng build --watch --configuration development&quot;,<br>    &quot;test&quot;: &quot;ng test&quot;,<br>    &quot;postbuild&quot;: &quot;node brotli-compress.js&quot;,<br>    &quot;ssr&quot;:&quot;npm run build &amp;&amp; npm run server&quot;,<br>    &quot;server&quot;: &quot;node server.js&quot;<br>  },</pre><p>This is an awesome result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qlx8b425GoRVpcELvDGbA.gif" /><figcaption>Content-Encoding Brotli</figcaption></figure><h3>Conclusion</h3><p>Finally, we have implemented Brotli compression in the angular project. There are several advantages to using brotli</p><ul><li>Reduce bundle size</li><li>Easy to implement</li><li>Improve web performance</li></ul><p>Last but not least, the image below is the compare load file with Brotli and without Brotli.</p><p>Compress with Brotli</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAlJjXxEpTb6SkbA_VVyrA.png" /><figcaption>Serve Content with Brotli</figcaption></figure><p>Compress without Brotli</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8O1HrmP3sEYYNQi5LKKJA.png" /><figcaption>Serve Content without Brotli</figcaption></figure><p>Thank you for your attention to reading this blog. You can check the repository for this project.</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/optimization-brotli">GitHub - afifalfiano/angular-tutorial-blogs at optimization-brotli</a></p><h3>References:</h3><ul><li><a href="https://devblogs.microsoft.com/dotnet/introducing-support-for-brotli-compression/">Introducing Support for Brotli Compression - .NET Blog</a></li><li><a href="https://github.com/google/brotli">GitHub - google/brotli: Brotli compression format</a></li><li><a href="https://en.wikipedia.org/wiki/Brotli">Brotli - Wikipedia</a></li><li><a href="https://kinsta.com/blog/brotli-compression/">Brotli Compression: A Fast Alternative to GZIP Compression</a></li></ul><p>#Angular #Express #Brotli #Optimization #BundleSize #Compression</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8222d753d6b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Publish Your Private Angular Library For Sharing Component Using Verdaccio]]></title>
            <link>https://afifalfiano.medium.com/angular-publish-your-private-angular-library-for-sharing-component-using-verdaccio-9a0856e5ded6?source=rss-a40d2d6ac40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0856e5ded6</guid>
            <category><![CDATA[private-library]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular-tutorial]]></category>
            <category><![CDATA[verdaccio]]></category>
            <dc:creator><![CDATA[Afif Alfiano]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 09:46:08 GMT</pubDate>
            <atom:updated>2023-03-05T09:47:40.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Sharing components with the private library in Angular</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaqmmxIrtMAixd5yoS4cGg.jpeg" /><figcaption>Verdaccio Angular</figcaption></figure><h3>Introduction</h3><p>Have you thought to share components in many projects? But you don’t want to copy and paste code in every project to avoid duplicate code. If the purpose is to share components, utility and etc. I think this article will help you to answer your question. Because I want to share about verdaccio.</p><h4>Verdaccio</h4><p>Verdaccio is a simple, zero-config-required local private NPM registry. No need for an entire database just to get started. Verdaccio comes out of the box with its own tiny database, and the ability to proxy other registries (eg. npmjs.org), which also introduces caching the downloaded modules along the way.</p><p><a href="https://verdaccio.org/">A lightweight Node.js private proxy registry | Verdaccio</a></p><h3>Project Graph</h3><p>In this tutorial, we will create a project like an image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kNj1eGXRc_zSIJwjdhtLA.png" /><figcaption>Project Graph</figcaption></figure><ul><li>We setup verdaccio and publish our private library for share component</li><li>Then, we install the private library in another project</li><li>Last, we try to use the share component from the private library in the current project.</li></ul><h3>Setup Verdaccio</h3><p>First of all, we need to install verdaccio</p><pre>npm i -g verdaccio</pre><p>After that, let’s run verdaccio and look at some configuration</p><pre>verdaccio</pre><p>Then, in the terminal will show like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaUzHpSB71ypQIEQc4AyNA.png" /><figcaption>Verdaccio CLI</figcaption></figure><p>Just open <a href="http://localhost:4873/">http://localhost:4873/</a> to show the default page verdaccio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tI3vz_Hv0F_PInwHCdDyyw.png" /><figcaption>Verdacio Page</figcaption></figure><p>Setup verdaccio on the local environment is already finished. Next, we will config a project that we want to publish.</p><h3>Publish Library</h3><p>I am using this project on a branch private library that gets from the main branch.</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/private-library">GitHub - afifalfiano/angular-tutorial-blogs at private-library</a></p><p>Then, I want to generate a shared module as a library.</p><pre>ng g library shared-library</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*FmpplgZmE2Xaerb7U95KDw.png" /><figcaption>Generate Library</figcaption></figure><p>Then, let’s create a simple component to share it. Make sure the generated component is assigned to the module shared-library.</p><pre>ng g c header --module=shared-library.module.ts</pre><p>Then, update the file header.component.html</p><pre>&lt;div class=&quot;header&quot;&gt;<br>  &lt;p&gt;{{title}}&lt;/p&gt;<br>  &lt;div class=&quot;menu&quot;&gt;<br>    &lt;ng-container *ngFor=&quot;let item of menuList&quot;&gt;<br>      &lt;a [href]=&quot;item.link&quot; rel=&quot;noreferrer noopener&quot;&gt;{{item.title}}&lt;/a&gt;<br>    &lt;/ng-container&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>After that, update for styling header.component.html</p><pre>.header {<br>  margin: 0;<br>  background: lightblue;<br>  border-radius: 5px;<br>  display: flex;<br>  justify-content: space-between;<br>  font-family: sans-serif;<br>  align-items: center;<br><br>  @media screen and (max-width: 475px) {<br>    flex-direction: column;<br>  }<br><br>  p {<br>    &amp;:first-child {<br>      padding: 10px;<br>      margin: 0;<br>      font-weight: 600;<br>      font-size: 18px;<br>    }<br>  }<br><br>  .menu {<br>    display: flex;<br><br>    @media screen and (max-width: 475px) {<br>      flex-direction: column;<br>      justify-content: center;<br>      align-items: center;<br>    }<br><br>    a {<br>      text-decoration: none;<br>      color: #000;<br>      padding: 10px;<br>      transition: .9s;<br><br>      &amp;:hover {<br>        transition: .9s;<br>        color: #fff;<br>        padding: 10px;<br>        background-color: rgb(0, 98, 245);<br>        border-radius: 5px;<br>      }<br>    }<br>  }<br>}</pre><p>Also, update the file typescript on header.component.ts</p><pre>import { Component, Input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-header&#39;,<br>  templateUrl: &#39;./header.component.html&#39;,<br>  styleUrls: [&#39;./header.component.scss&#39;]<br>})<br>export class HeaderComponent {<br>  @Input() title!: string;<br>  @Input() menuList: {link: string, title: string}[] = [];<br>}</pre><p>The result is like this, not a fancy design but only for showing the real component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQIq4f_DvDiAqAaMU8QyoA.png" /><figcaption>Component Header</figcaption></figure><p>Don’t forget to update shared-library.module.ts</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { SharedLibraryComponent } from &#39;./shared-library.component&#39;;<br>import { HeaderComponent } from &#39;./header/header.component&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br><br><br><br>@NgModule({<br>  declarations: [<br>    SharedLibraryComponent,<br>    HeaderComponent<br>  ],<br>  imports: [<br>    CommonModule<br>  ],<br>  exports: [<br>    HeaderComponent<br>  ]<br>})<br>export class SharedLibraryModule { }</pre><p>Also, update public-api.ts to become like this</p><pre>/*<br> * Public API Surface of shared<br> */<br><br>export * from &#39;./lib/shared-library.service&#39;;<br>export * from &#39;./lib/shared-library.component&#39;;<br>export * from &#39;./lib/shared-library.module&#39;;<br>export * from &#39;./lib/header/header.component&#39;;</pre><p>I already pushed the branch on github</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/private-library">GitHub - afifalfiano/angular-tutorial-blogs at private-library</a></p><p>Next, we register the private library into the verdaccio.</p><h4>Build project</h4><p>Run this command to build project</p><pre>ng build shared-library</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*uXHpKM1VrxzUKvUXqQXKDg.png" /><figcaption>Dist Shared Library</figcaption></figure><h4>NPM Add User</h4><p>After that, add the user on registry verdaccio</p><pre>npm adduser --registry http://localhost:4873</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8D5Bi3PbUrBUTX_XOOuvWQ.png" /></figure><h3>Publish Library</h3><p>After creating a user, let’s publish the private library by running this command, make sure when you run npm publish, you should be on folder dist/shared-library.</p><p>You can run this command to change the directory into dist/shared-library</p><pre>cd dist/shared-library</pre><p>Then, just publish the library</p><pre>npm publish --registry http://localhost:4873</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxGQu_0Mpb3LntH-2ltP6A.png" /><figcaption>Publish Library</figcaption></figure><p>For the version private library, you can change the version of package.json, and don’t forget to add a change log markdown to document the feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uwl5e7SQPqAKrizIVACz8Q.png" /><figcaption>Private Library Already Published</figcaption></figure><p>The private library has already been published. Next, we want to install it in another project&#39;s angular</p><h3>Install Private Library</h3><p>I am using this project with a branch using-private-library from the main branch.</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/using-private-library">GitHub - afifalfiano/angular-tutorial-blogs at using-private-library</a></p><p>If we direct to run this command, maybe we got some error or success but not our private library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*P2YDVr6wOt2jPot40npAgg.png" /><figcaption>Error Install Private Library</figcaption></figure><p>This error is because the npm install is referred to npmjs.</p><p>So, to solve this problem, we need to register our private library verdaccio. Create file .npmrc and add this script.</p><pre>registry=http://localhost:4873</pre><p>So, I install again my private library</p><pre>npm install shared-library</pre><p>If you still getting error on your project, try this solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1k_zQvHbBsAth_twanksAQ.png" /><figcaption>Setup Registry Verdaccio</figcaption></figure><p>We are successfully installed a private library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_sGbw5z9OM9s0MdFsL--w.png" /><figcaption>Install Private Library</figcaption></figure><p>The left side is showing request verdaccio and the right side is processing to install of the private library.</p><p>To make sure the private library has been installed. Just check the file package.json and hover on the library angular-tutorial-blogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aISnnp_2-09jpDKqv9YdFA.png" /><figcaption>Package.json</figcaption></figure><p>Then, we need to try the component header that we have created on the private library.</p><p>Then open app.module.ts and import the module shared library.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { SharedLibraryModule } from &#39;shared-library&#39;;<br><br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    SharedLibraryModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>After that, let’s try to call the reusable component from a shared library. Open the file app.component.html and update it.</p><pre>&lt;app-header [title]=&quot;&#39;Hello&#39;&quot; [menuList]=&quot;[{link: &#39;/&#39;, title: &#39;Home&#39;}, {link: &#39;/product&#39;, title: &#39;Product&#39;}]&quot;&gt;&lt;/app-header&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>The result of shared component is like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuoEr8xCs-Vq5lJTtFc9fw.png" /><figcaption>Success Use Component From Private Library</figcaption></figure><p>We just finished this tutorial about angular and verdaccio.</p><p>The branch has already been pushed to my GitHub repository.</p><p><a href="https://github.com/afifalfiano/angular-tutorial-blogs/tree/using-private-library">GitHub - afifalfiano/angular-tutorial-blogs at using-private-library</a></p><h3>Conclusion</h3><p>We can get some benefits from this library to publishing our private library, for example, some companies have design systems and we need to build a private library because the design system only uses by internal companies.</p><p>Another benefit is we can avoid duplicate code if we have several projects with the same user interface, theme, or function.</p><p>Hopefully, this article is useful for you, and thank you. If any feedback or suggestion for me, just reply to this article or email afifalfiano2@gmail.com</p><h3>References</h3><ul><li><a href="https://blog.profanis.me/blog/publishing-a-private-angular-library-using-verdaccio">Publishing a Private Angular Library using Verdaccio</a></li><li><a href="https://verdaccio.org/">A lightweight Node.js private proxy registry | Verdaccio</a></li><li><a href="https://www.geekstrick.com/lesson/publish-angular-library-to-local-npm/">05 - Publish Angular Library To Local npm - Geekstrick</a></li></ul><p>#Angular #Verdaccio #SharedLibary #PrivatePackage #TutorialAngular</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0856e5ded6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>