RSSAmplifier

Blog

Code with Hugo

Recent content on Code with Hugo

codewithhugo.comRSS feed ↗141 posts

Latest posts

Clear Module Cache/Force Import in Node.js with CommonJS and with ES Modules (ESM)

Node.js supports two primary module systems: CommonJS and ES Modules (ESM). Both systems cache imported modules, ensuring that a module’s code runs only once, even if it’s imported multiple times. When writing tests it can be useful to bypass caching for example if the code being tested is executed at the module scope (outside of exported functions). While most test frameworks handle…

Taming Timezones: Replacing moment.parseZone with @date-fns/tz and Vanilla JS Date

Taming Timezones: Replacing moment.parseZone with @date-fns/tz and Vanilla JS Date How we preserved timezone-aware parsing when migrating from moment.js to date-fns and JS Date. One of the last pieces of work I completed at my last workplace was to migrate a core system from moment to date-fns , vanilla Date manipulation & formatting.

TypeScript in the Trenches: Utility types and type manipulation patterns for application development

7 advanced types and patterns that I’ve used as part of TypeScript application development. These patterns help unlock new levels of type safety and maintainability in TypeScript.

Configure Timezone for Jest/Node.js with the `TZ` env var

In order to test code that involves date and time manipulation and parsing. It can be useful to set the timezone under which the Jest tests run. Thankfully Node.js supports the TZ environment variable: “The TZ environment variable is used to specify the timezone configuration.” ( Node.js docs ).

Nock on Node 18/20/22 Fails to Intercept isomorphic-unfetch/fetch Request

On Node versions 18, 20 and 22, users may encounter an issue where Nock fails to intercept requests made via isomorphic-unfetch. What follows is a sample error you may see (timeout is reached because the request is not intercepted). returns a valid response thrown: 'Exceeded timeout of 5000 ms for a test. Add a timeout value to this test to increase the timeout, if this is a long-running test. See…

`dotenv` not required: load `.env` and parse env vars natively in modern Node.js

dotenv is a 39 million download a week package allows Node.js apps to load environment variables from .env files and other utilities around environment variables. It’s very useful for building 12-factor apps for which a principle is to read configuration from environment variables instead of config or code files. As of Node 20.6 (and all Node 22.x versions), env files can be loaded via the…

Mocking/stubbing the current Date in Jest tests

There are situations where new Date() or Date.now is used in application code. That code needs to be tested, and it’s always a struggle to remember how to mock/stub or spy on Date.now / new Date with Jest. This post goes through multiple approaches to mocking, stubbing and spying on the date constructor using Jest. There’s a full examples repository at…

Docsify Mermaid 10

Using Docsify and Mermaid 10 can be tricky since Mermaid 10 renders asynchronously ( mermaid.render returns a Promise). This post shows how to work around the mismatch between Docsify’s markdown.renderer.code and Mermaid’s render function on Mermaid v9 and v10.

Mocking/stubbing the Date and timers (setTimeout) in Node.js tests with built-in `node:test` MockTimers

MockTimers is an experimental class in the node:test module which concerns itself with allowing mocking of timers ( setTimeout , setInterval , setImmediate ) and the Date built-ins.

Direnv setup for multiple git/GitHub, npm and AWS accounts/credentials

In this post, we’ll look at how to configure direnv to manage multiple git, GitHub, npm and AWS accounts and credentials on a single machine.

Test Native `fetch` in Node.js with Undici interception and mock utils

Node.js 18+ has a built-in fetch available, where prior versions had to use libraries such a node-fetch , axios , got or other to get such functionality. The “native fetch” was implemented in userland first as the undici package . This post goes through how to use undici ’s mock utilities ( MockAgent , MockPool , setGlobalDispatcher ) to intercept “native fetch ”…

Node Test Runner: skip a test if an environment variable is missing/empty

The node:test module is a built-in test runner and orchestrator in Node.js. It’s available as experimental since Node 18 but has stabilised in Node 20 and some features are still experimental at the time of writing, in Node 21. node:test supports test skipping throught multiple approaches but the two we’ll focus on here are the “programmatic skips”, where at runtime we can…

Lerna publish with no git commit, tag or push

To lerna publish without a git commit or attempting to git push , use --no-push --no-git-tag-version , like so: lerna publish --no-push --no-git-tag-version For official documentation on these options see the lerna version docs . To understand the specifics of --no-push , --no-git-tag and why these options are documented in lerna version , read on.

What is Jest and why should I use it?

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. jestjs.io Jest is a batteries-included framework. Due to its fully-featured nature and large surface area, we can compare it to test runners (Mocha), assertion libraries (Chai, ShouldJS, power-assert, expect.js), integrated test-runner + assertion libraries (QUnit, Protractor, Tape, AVA, Jasmine), stubbing libraries…

Concurrent/Parallel HTTP Requests in Go

A common source of high latency in all types of applications (scripts, HTTP servers, CLI tools), is to run HTTP requests in sequence that could be run in parallel. We’ll be looking at how to achieve this in Go. Examples for concurrency in the Go ecosystem tend to be more abstract or low-level than a close to real-world example of integrating a third party HTTP API.

Markdown escape backticks in inline code and fenced code blocks

When writing technical documentation, blog posts or conducting code reviews, it can be useful to render backticks in Markdown inline code, code blocks or fenced code blocks. Since backticks are part of the Markdown syntax for inline code and code fences, this post looks at how to render them without clashing with the syntax.

git diff by word

The default diffing algorithm for git diff is by lines. There are scenarios where it’s more interesting to diff by word, for example: long lines. In that case it’s useful to use --word-diff=color .

git/GitHub CLI set editor to vim or VSCode

The GitHub CLI ( gh binary), defaults to nano as its editor. Developers may want to set it to vim or VSCode to keep it in line with the git CLI’s behaviour.

Node.js Native Test Runner

If anyone missed it, Node.js 18 includes a test runner/test definition module ( node --test and node:test respectively). node:test exports a test function and you can run the Node CLI with a --test flag which does some basic search/matching for test files. Full Documentation: nodejs.org/api/test.html Documentation for node:test Documentation for node --test Curated set of examples:…

Tips for real-world Alpine.js

Alpine Day 2021 Talk: tackling Alpine FAQs, common issues & web patterns with Alpine.js

Why doesn't React.useEffect run on React server-side renders (SSR)?

Why doesn’t React.useEffect run during a server-side render (SSR) for example when using it inside a Next.js application? The obvious spots in the docs for information like this are the React docs on useEffect and the React docs on string/static rendering neither of which mention any particular behaviour of useEffect during server-side rendering (SSR).

Cypress Scroll Position Assertions

This post goes through approaches to asserting on the scroll position. First we’ll see how to assert that we’re at the top of the page. Next we’ll look at 2 approaches to assert that we’ve scrolled to an element. The examples for this post are available at github.com/HugoDF/cypress-scroll-position-assertions/ .

What is the "?." JavaScript/TypeScript operator

In JavaScript and TypeScript, the “?.” operator is called optional chaining. It works in a similar fashion to the . (chaining) operator, except that it short-circuits instead of causing an error when a value is null or undefined . That means const obj = {}; console.log(obj.hello?.world); will log undefined (the value of obj.hello ) instead of throwing a TypeError: obj.hello is…

Convert images to data URLs at the command line (Mac OS)

Converting images to data URLs using the Mac OS command line is a fun demonstration of the command line’s capabilities. To convert an image file to a data URL, we can use the following shell function: function img-data () { TYPE = $( file --mime-type -b $1 ) ENC = $( base64 $1 ) echo 'data: $TYPE ;base64, $ENC ' } What follows is a walkthrough of what data URLs are, why they’re useful…

The Future of PHP: Is It a Dead Programming Language?

There’s an opinion that PHP is dead today, but is this true? Should we believe in this or only people who don’t like PHP are sharing this news? Why do people hate PHP ? Let’s take a closer look at PHP and try to predict its future.

Tips For Students Choosing Their First Programming Language

More and more colleges offer their students the opportunity to try their hand in coding. With technologies continuing making massive inroads people’s our everyday lives, such professions as a computer programmer, web developer, software engineer, mobile app developer , and others ranks among the best paying and on-demand. No wonder, so many students, even those who initially chose completely…

Disable a HTML <a> link/anchor tag

Here are 2 ways to disable a HTML <a> link/anchor element using CSS or by using inline JavaScript.

An accessible Alpine.js menu toggle

The &ldquo;Hello World&rdquo; of JavaScript frameworks and libraries seems to have become the todo app. In the case of Alpine.js a todo app is almost too large to showcase Alpine&rsquo;s core benefits and use case. Another issue with a lot of JavaScript examples is that they forego accessibility. Therefore we won&rsquo;t be building a todo app but an accessible navigation menu. Our menu is as…

Alpine.js in-depth: listen to JavaScript events using x-on

The core Alpine.js functionality beyond toggling visibility, displaying data in HTML textContent and binding HTML attributes to data is listening for events using Alpine.js. Listening to events with x-on is usually coupled with state updates, for example we can create the following &ldquo;counter&rdquo; using x-data , x-on and x-text . < div x-data = '{ count: 0 }' > < button x-on:click =…

Alpine.js in-depth: reactive HTML attribute binding with x-bind

We&rsquo;ve seen how to print out values using x-text and toggle visibility of elements based on them with x-show . We&rsquo;ll now see how to set the value of HTML attributes using x-bind . In this example we&rsquo;ll display and image based on data that&rsquo;s in our Alpine.js initial state (as defined in x-data ), in this case caption , src and width . Which, respectively, represent the…

Show/hide in Alpine.js with x-show

In Alpine.js the directive used to toggle visibility of an element is x-show . Per the Alpine.js README , &ldquo; x-show toggles the display: none; style on the element depending if the expression resolves to true or false &rdquo;.

Github Pull Request Review: reset viewed files

GitHub Pull Request Review workflow is great. What I particularly like is the &ldquo;file viewed&rdquo; toggle, which mean that I&rsquo;m not tempted to re-review the whole Pull Request when a single file has changed and I&rsquo;ve already checked the rest of them. However there are instances where I want to re-review the PR as a whole instead of just the changes since my last review. For example…

Alpine.js In-Depth: x-data "state" & x-text "echo"

The simplest Alpine.js application is the following HTML file. It loads Alpine.js version 2+ from the JSDelivr CDN using a script tag and has an Alpine.js component with x-data="{ msg: 'Hello Alpine.js' }" and a p element with x-text="msg" .

Alpine.js `x-for` a number of iterations (n times)

Alpine.js falls back to JavaScript to allow you to iterate a set number of times. For example if I want to create 4 lines on a page I can use the following. < div x-data > < template x-for = '_ in Array.from({ length: 4 })' > < hr > </ template > </ div > You can see all the examples at Alpine.js Playground - x-for n times .

Alpine.js `x-for` with objects: 4 ways to iterate/loop through JavaScript objects

One of the missing features of Alpine.js is the ability to iterate through objects with x-for . Alpine.js is heavily inspired by Vue.js but it&rsquo;s designed to be lean and rugged instead of incrementally adoptable. Therefore x-for only supports arrays/iterables. The reason there&rsquo;s no first-class support for iterating through objects with Alpine.js&rsquo; x-for is that converting a…

How to get type-checking and generate TypeScript Typing declaration (types.d.ts) from JSDoc annotations

How to achieve TypeScript-like behaviour in Vanilla JavaScript using JSDoc and @ts-check in VSCode: that&rsquo;s the purpose of this post. TypeScript is a JavaScript superset with types. It solves one of the big problems with JavaScript, which is &ldquo;what parameters does this function expect?&rdquo; TypeScript is great for the JavaScript ecosystem, code written in TypeScript (or with a type…

Sync Alpine.js x-data to localStorage/sessionStorage

Alpine.js is great for writing widgets. localStorage / sessionStorage are Web APIs that enable JavaScript application to store data beyond the life of the current JavaScript process. This is useful for example if we wanted to persist our todos when the user closes the tab and comes back to it later. If you want to skip to the examples, they&rsquo;re in this CodePen collection or at the following:…

How to Access Alpine.js Magic Properties from inline handlers and function/component methods

Alpine.js magic properties are crucial to leveraging its best features. When using Alpine.js in a &ldquo;mainly markup&rdquo; configuration (no script tags), the magic properties tend to be accessible seamlessly. Alpine.js magic properties are as follows: $el : the element to which an Alpine.js component is bound (also called the root element) $refs : references to DOM Nodes as defined in the…

Access Alpine.js component data/state from outside its scope

Warning this uses Alpine.js v2 internals, there isn&rsquo;t currently a public-facing API to do this. As an active Alpine.js and Alpine.js Devtools contributor, I&rsquo;ve had the pleasure of explaining how to access Alpine.js component data from outside the component and of using my suggestion as part of work I did on the community-maintained Alpine.js Devtools .

A guide to Alpine.js component communication

Learn how to share information between Alpine.js components with the $dispatch magic property and the window/document as an event bus. This post will show how to trigger and listen to global/window/document events with Alpine.js in order to use it as an event bus to communicate between sibling components (which is the only type of component composition that Alpine.js supports) Alpine.js is a great…

App Ideas: 17 Web Apps You Can Build To Level Up Your Coding Skills

Have you ever wanted to build something as a web developer? The answer is probably&hellip;yes. A common problem web developers have is that they don&rsquo;t know WHAT to build and HOW to build them. Well, you&rsquo;ve come to the right place. This is a list of 17 web apps you can (and should) build to level up your coding skills and expand your coding knowledge. This isn&rsquo;t just a simple list…

Alpine.js + jQuery/JavaScript Plugin Integration: a Select2 example

One of the jQuery ecosystem&rsquo;s greatest strength is the wealth of drop-in plugins available. Alpine.js is a great way to phase out jQuery spaghetti code from current and future projects with its declarative nature and small bundle size. What Alpine doesn&rsquo;t have (yet), is a thriving plugin ecosystem. However, it&rsquo;s all &ldquo;just JavaScript&rdquo; and it&rsquo;s completely possible…

JavaScript remove duplicates, get unique/distinct values from Array with ES6+ Set and spread

With ES6+, more developers should be leveraging built-ins than are using lodash functions. This post will go through how to remove duplicates ie. get distinct/unique values from an Array using ES6 Set. This gives you a one-line implementation of lodash/underscore&rsquo;s uniq function: const dedupe = list => [... new Set ( list )]; This rest of the post goes through the how and why this works. It…

AVA: pass or fail a test if an environment variable is missing/empty

In a recent project I needed to fail/pass some AVA if a runtime environment variable was unset or empty. Here&rsquo;s how I solved this issue. AVA is a test runner for Node.js with a concise API, detailed error output, embrace of new language features and process isolation that let you write tests more effectively. I&rsquo;m a big fan of AVA&rsquo;s explicit nature and it plays nicely with my…

Use microbundle for a TypeScript npm module

For those looking to write a package and publish it to npm, TypeScript + microbundle is a low-friction way to build a high-quality library. I&rsquo;ve created a GitHub repository template with microbundle, TypeScript, ava and xo . You can find it at github.com/HugoDF/microbundle-ts-pkg/

Add days to a Date in vanilla JavaScript

Despite the JavaScript Date warts, it&rsquo;s straightforward to add day(s) to a date in JavaScript. While it would be very easy to reach for moment.js or another date manipulation library (date-fns, luxon, dayjs) to do something as simple as adding days to a Date in JavaScript, writing a short helper function might just be easier.

Synchronize x-data and the URL in Alpine.js with the location/History APIs and $watch

Alpine.js doesn&rsquo;t have a router as yet since it&rsquo;s designed to deliver simple interactive experiences on top of server or statically rendered sites. For single page applications that make heavy use of the History API or require a router, one would be better served heading over to Vue, React or Angular since they come with well-supported routers and routing solutions (eg. react-router,…

Integrating Alpine.js + Pre/Server-rendered content

Alpine.js is a great choice for adding some interactive feature to a server rendered, static or pre-rendered site. In the Alpine.js GitHub Issues, we&rsquo;ve seen a lot of questions around how to deal with content that&rsquo;s pre-rendered or server-rendered in Alpine.js in order to use Alpine.js as a progressive enhancement. From a poll I ran recently, 95.2% of Alpine.js users want to use it…

Integrating Alpine.js with Eleventy & YAML files to create Alpine Playground's Collections

Adding collections to Alpine.js Playground, essentially bringing it in line with projects such as awesome-alpine and alpinetoolbox.com . It came from the fact that I&rsquo;m curating quite a bit of content for each newsletter and it makes sense that content featured on the newsletter should be accessible in an easy to scan manner. Here&rsquo;s the rough mockup of what it should look like, ready…

How to migrate a bunch of HTML pages (Alpine.js Playground) to Eleventy

Alpine.js Playground was recently migrated from custom build scripts & HTML pages to leverage Eleventy . For context, Alpine.js Playground&rsquo;s custom build scripts + HTML files had the following pros and cons. Pros: simple very simple, everything is in the scripts folder. no dependencies (except the scripts do have dependencies) Cons: hand-rolled, doesn&rsquo;t leverage any tooling no…