2024-10-10

Building a Simple interactive CLI Counter with Deno v2 and Ink

Deno v2 has been released! 🎉

The promo video is a must-watch: "Deno - Programming should be simple" on Youtube

No wonder, I immediately wanted to try out Deno's new support for npm packages. I decided to create a simple counter component using Ink, a React-like library for building CLI apps.

Here's the code (main**.jsx**):

// main.jsx
import React, { useEffect, useState } from "npm:react";
import { render, Text } from "npm:ink";

const Counter = () => {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCounter((previousCounter) => previousCounter + 1);
    }, 100);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return <Text color="green">{counter} tests passed</Text>;
};

render(<Counter />);

Run the code using deno@v2.x (Ctrl+C to stop it 😅):

# Run the code (the first time to check permissions)
$ deno run main.jsx

# if you're fine with the permissions needed, run it again and again
$ deno run --allow-read --allow-env --allow-run main.jsx

# or compile it even 🤷‍♂️
# deno packs its runtime and the dependencies into a single executable
$ deno compile --allow-read --allow-env --allow-run main.jsx

Super sweet! 🍬🦕


← Previous Post | Next Post →