Import maps go universal

#​632 — March 31, 2023

Read on the Web

JavaScript Weekly

JavaScript Import Maps Now Supported Cross-Browser — ES modules provide a modern way to include and reuse JavaScript code in web apps, and import maps provide the bridge between using module names in code and where those modules can actually be loaded from.

Thomas Steiner (Chrome Developers)

???? The import map news comes off the back of the release of Safari 16.4 which introduces a lot of new functionality to the Mac-based browser, from Web Push and import maps to improved Web Component support and lazy-loading support for iframes.

Updates from the 95th TC39 Meeting — Working group meetings might not seem interesting on the surface, but a lot of what TC39 discusses ends up in our day to day code. Of special interest this time are the progression of support for ranges and the async context proposal to stage 2, and awaiting a dictionary of promises and decorators for class constructors/methods to stage 1.

Hemanth HM

React Authentication, Simplified — In this article, we lay out a new approach to authentication (plus access control & SSO) in React applications.

Userfront sponsor

React Labs: What React Core Has Been Working On — The latest update from the React core team. The most striking update comes around the progress of React Forget, an optimizing compiler with the goal being able to build fully reactive systems using the JavaScript and React mental models you already have, with the compiler tackling the trickiest parts.

The React Core Team

IN BRIEF:

Over on Twitter, ???? Stefan Judis notes that Firefox Nightly is the first browser shipping support for @media (scripting: none) to detect disabled JavaScript in CSS.

???? Over half of new npm packages are junk. Though that’s an improvement on packages riddled with malware… Could we improve things by using ChatGPT to analyze packages? Maybe, says Socket.

???? Excited about the future of Angular? Next Tuesday, the Angular team is doing a livestream on YouTube about the Angular Signals RFC.

Microsoft has ‘rebuilt Teams from the ground up’ with React replacing AngularJS at the heart of the UI.

Did you know SVG almost got built-in network socket support? ????

The Cloudflare Workers edge serverless platform is based around V8 isolates rather than Node.js but is now gaining support for some Node.js APIs.

RELEASES:

Rome 12
↳ Big release for the linter & formatter.

Solid 1.7
↳ Flexible declarative library for UIs.

Visual Studio Code March 2023
↳ Now with improved switch scaffolding for TS/JS.

Ionic 7.0
↳ Powerful cross-platform mobile app toolkit.

Docusaurus 2.4
↳ React-powered docs site generator.

Node.js v16.20.0 (LTS)

???? Articles & Tutorials

Janet for MortalsJanet is a Lisp-like functional dynamic language that can nonetheless be compiled and interact with C libraries. This online book about Janet targets folks who already know JavaScript in particular.

Ian Henry

In Praise of Vite“The single best feature of Vite, as far as I’m concerned, is its simplicity. Compared to the nightmare of configuring WebPack and Babel? Vite is delightfully easy to use.”

Scott Vandehey

???? Robin Wieruch has just published a tutorial on migrating to Vite from Create React App (CRA) if you want to give it a go for yourself.

The Easiest Way to Add Chat to Your Application. Try Stream for Free — Build and ship real-time messaging in less time with our highly reliable chat infrastructure and feature-rich SDKs. Free 30-day trial.

Stream sponsor

Building Framer Motion Animations Inside a Qwik Application — Also touches on Motion One as a bonus, an animation library similar to Framer but lighter and faster to use.

Yoav Ganbar

A Business Case for SvelteKit — A good post covering the experience of migrating from Meteor to SvelteKit, the process this team undertook, and the outcomes from both a performance and UX point of view.

Chris Ellis

How to Enable OpenTelemetry Traces in React Apps — A ten-step approach to enabling OpenTelemetry traces in React apps all the way through to viewing the end results in Jaeger.

Purva Naik (Red Hat)

Build Developer-First Automations with Retool Workflows

Retool sponsor

Understanding module.exports and exports in Node

James Hibbard

???? Code & Tools

NPKILL 0.11.1: Delete node_modules Even Faster — NPKILL (homepage) is a popular tool for listing node_modules folders and how much space they take up, before allowing you to quickly delete them. This new release makes it even faster than before through using worker threads.

Gallardo and Gómez

Inferno 8.1: A Fast, React-a-Like with a Different Approach — React-like, but you might be more intrigued by its differences (which include a different approach to optimizing performance and lifecycle events on functional components).

Inferno

Breakpoints and console.log Is the Past, Time Travel Is the Future — 15x faster JavaScript debugging than with breakpoints and console.log, supports Vitest, Jest, Karma, Jasmine, and more.

Wallaby.js sponsor

Nano JSX: A Lightweight SSR-First JSX Library — Features include no Virtual DOM, no external dependencies, on-demand hydration, and support for Node and Deno-based server-side rendering situations.

Nano JSX

Concurrent.js: Load Modules into Background Threads — For JS environments including the browser, Node and Deno, this library dynamically imports modules into worker threads (in Node) or Web Workers (in the browser) to run them away from the main thread.

Bitair

cron-schedule 4.0: Cron Parser and Scheduler — Parse and query cron style expressions in the browser, Node or Deno.

Pascal Sthamer

Bright: A React Server Component for Syntax Highlighting — Customizable and includes all of VS Code’s syntax highlighting themes, some of which are demonstrated on the page.

Code Hike

typescript-json-serializer 6.0 — Deserialize JSON into TypeScript classes and serialize classes into JSON.

Gillian Pérard

???? Jobs

Full Stack JavaScript Engineer @ Emerging Cybersecurity Startup — Small team/big results. Fun + flexible + always interesting. Come build our award-winning, all-in-one cybersecurity platform.

Defendify

Software Engineer — Join our happy team. Stimulus is a social platform started by Sticker Mule to show what’s possible if your mission is to increase human happiness.

Stimulus

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

????‍???? Got a job listing to share? Here’s how.

QUICK RELEASES:

Ink 4.1
↳ Use React to build interactive CLI apps.

Ember Simple Auth 5.0
↳ Authentication and authorization for Ember apps.

Cypress 12.9
↳ Browser-oriented testing framework.

SVGR 7.0
↳ Transform SVGs into React components.

???? JZZ 1.6.1
↳ MIDI library for Node and browsers.

Vue Sonner
↳ The Sonner toast component but for Vue.

np 7.7 – A better npm publish.

Qwik 0.100 – The HTML-first framework.

DOM Testing Library 9.2

React Date Picker 4.11

pnpm 8.1

Playwright now offers a UI mode

#​631 — March 24, 2023

Read on the Web

JavaScript Weekly

Speeding Up the JavaScript Ecosystem: npm Scripts — The latest in what has been a fascinating series on finding ‘low hanging fruit’ when it comes to performance in the JavaScript world. The author explains it best himself:

“‘npm scripts’ are executed by JavaScript developers … all the time. Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.”
What Marvin does here is a valuable skill for all developers to pick up, and you can enjoy more by going back to the start.

Marvin Hagemeister

Playwright v1.32 – Now with UI Mode — The popular Web testing and automation framework is taking more steps toward the ground currently served by tools like Cypress by offering a ‘UI mode’ that lets you explore, run and debug tests in a UI environment, complete with watch mode. ▶️ This video provides a good introduction.

Microsoft

A Grid Component with All the Features & Great Performance — Try our powerful JS data grid component which lets you edit, sort, group and filter datasets with fantastic performance. Includes a TreeGrid, API docs and plenty of demos. Seamless integration with React, Angular & Vue apps.

Bryntum sponsor

Why We Added package.json Support to Deno — Deno shares some provenance with Node.js but till recently it hadn’t focused on supporting Node features like npm modules. But with Node and npm compatibility beginning to improve, the team has faced questions about the runtime’s priorities. Ryan Dahl explains more about their thinking here.

Ryan Dahl

???? In other Deno news, Deno 1.32 has been released with… improved package.json support, and more.

How to Start a React Project in 2023 — There are lots of ways, but this well-regarded author explains the pros and cons of a few approaches, and gives you a few options targeting specific use cases you might have.

Robin Wieruch

IN BRIEF:

GitHub had to update its RSA SSH host key today so you may see security related warnings when pushing and cloning. It’s easy to fix, but check the new fingerprint matches – it’s for your own security.

The New Stack caught up with Svelte’s Rich Harris on SvelteKit and what’s coming for Svelte 4.

The React team shared some cutting edge updates on what they’re working on including React Server Components and an optimizing compiler.

If you were experiencing errors on the official Node site last week, here’s the (detailed) post mortem of why. Config errors and inappropriate caching, mostly.

✨ Did you know there’s a market in fake GitHub stars? Some developers analyzed some repos to learn more about it.

???? Congratulations to Lea Verou on her TC39 appointment9. Her efforts to push the Web forward are legendary. Prism is one project you may be aware of.

Make your opinions known on what should be in the next version of Vite.

RELEASES:

Docusaurus 2.4
↳ Easy to maintain documentation site generator.

Puppeteer 19.8
↳ Headless Chrome Node.js API.

Neutralinojs 4.11
↳ Lightweight cross-platform desktop app framework.

Qwik 0.23

???? Articles & Tutorials

Buying a Hard-to-Get Bicycle using Playwright — An unusual use case for JavaScript, Playwright, and GitHub Actions, but Maciek managed to buy his bike.

Maciek Palmowski

Snyk Top 10: JavaScript OSS Vulnerabilities — Dive into the most prevalent critical and high open source vulnerabilities found by Snyk scans of JavaScript apps in 2022.

Snyk sponsor

The ‘End’ of Front-End Development? — A recent narrative doing the rounds suggests that large language models like GPT-4 (or even tools like Copilot X) could soon put some developers out of a job — however, Josh is “optimistic about what these AI advancements mean for the future of software development”.

Josh W. Comeau

In related news, Eric Elliott put ChatGPT through its paces to see if it would make for a good JavaScript tutor. It did well, though with mixed results.

Migrating from ts-node to Bun — A look at adopting performance-oriented Bun when you’re used to using TypeScript with Node.js. John runs us through porting a console app from the ts-node approach over to Bun — “a pretty easy process,” he says.

John Reilly

▶  A Pinia Crash Course for BeginnersPinia is a store / state management solution for Vue that does believe in pineapple on pizza.

Alexander Gekov

A Practical Guide to Getting Started with Astro — An extensive walkthrough of Astro that covers all the topics you’ll need to get you started.

Mojtaba Seyedi

???? Test Website Speed Continuously and Rank Higher In Google — You need a fast website to make users happy and meet Google’s Core Web Vitals metrics. Test and optimize with DebugBear.

DebugBear sponsor

Automatic npm Publishing with GitHub Actions and Granular Tokens

Tim Perry

Make Sure You Do This Before Switching to Signals in Angular

Jordan Powell

Six CSS Snippets Every Developer Should Know

Adam Argyle (Google)

???? Code & Tools

trace.cafe: Easy Webperf Trace Sharing — A quick way to share a performance profile saved from your DevTools, available for up to 90 days with the DevTools perf panel embedded (see example).

paul irish

VueUse: A Collection of Vue Composition Utilities — With over 200 functions targeting both Vue 2 and 3, there’ll be something in this suite of Composition API-based utility functions for you, whether it’s working with state, browser capabilities, animations, Electron, Firebase, and more.

Anthony Fu

Don’t Let Your Issue Tracker Be a Four-Letter Word. Use Shortcut

Shortcut (formerly Clubhouse.io) sponsor

OTPAuth: One Time Password (HOTP/TOTP) Library — When you log in to a site that uses 2FA and you’re asked for some digits from an authentication app, that’s probably a Time-based One-Time Password (or TOTP). This library for Node, Deno, Bun and the browser lets you work with TOTPs and HOTPs from JS.

Héctor Molinero Fernández

Recharts 2.5: Chart Library Built with React and D3 — Easy to deploy with declarative components, native SVG support, and lightweight dependency on D3. Line, bar, scatter, composed, pie, and radar charts are offered. There are lots of examples, complete with code.

recharts

DOCX 8.0: Generate Word .docx Files from JavaScript — The code to lay out documents is verbose but there’s a lot of functionality. Here’s a CodePen example and release notesGitHub repo.

Dolan Miu

SvHighlight: Code Syntax Highlighter for Svelte — Powered by Highlight.js, it includes a blurring feature to focus attention on specific areas of code and you an customize it with Tailwind. Try the interactive examples to see the effect.

SvHighlight

eslint-formatter-pretty 5.0: Pretty ESLint Formatter — Nicer output than the default. Sort results by severity. Get stylized inline code blocks, and more.

Sindre Sorhus

AWS JWT Verify: Verify JWTs Signed by Amazon Cognito — In both Node.js and the browser.

Amazon Web Services

???? Jobs

Software Engineer (Backend) — Join our “kick ass” team. Our software team operates from 17 countries and we’re always looking for more exceptional engineers.

Sticker Mule

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

????‍???? Got a job listing to share? Here’s how.

melonJS 15.0
↳ Mature HTML5 game engine.

Marked 4.3
↳ Markdown parser and compiler. (Demo.)

v8go 0.9
↳ Execute JavaScript from Go(lang).

Million 2.1
↳ Fast Virtual DOM to make React faster.

Partytown 0.7.6
↳ Take third-party scripts off the main thread.

???? Bonus Item

Make Bookmarklets — Create and test bookmarklets directly in the browser. Makes an irritating task slightly easier if you need to do it.

Cullan Luther

Transformers: JavaScript in Disguise

#​630 — March 17, 2023

Read on the Web

JavaScript Weekly

????  Transformers.js: Running ML Models in the Browser — Transformers are a type of machine learning model often used for natural language or visual processing and while running such models directly in the browser is in its infancy, Transformers.js opens up some ML models to you with some impressive demos here.

Xenova

????  Celebrating 10 Years of Electron — It feels like Electron pops up everywhere (Slack, Spotify, VS Code, and more) so it might feel surprising it’s only been with us for a decade. Slack and Electron developer Erick Zhao gives thanks to Electron’s developers, the community, gives us a bit of Electron related history, and reassures us Electron is still going strong.

Erick Zhao

Dynaboard: A Visual Web App IDE Made for Developers — Build high performance public and private web applications in a collaborative — full-stack — development environment.

Dynaboard sponsor

Announcing TypeScript 5.0 — Note that TypeScript doesn’t follow semantic versioning, so this is as much a ‘major’ release as 4.9 was.. but 5.0 looks cool anyway. This release of the typed JavaScript superset is packed with features like decorators, improved ESM project support for Node and bundlers, const type parameters, and more.

Daniel Rosenwasser (Microsoft)

Turbowatch: File Change Detector and Task Orchestrator — Not just that but it claims to be extremely fast and “if you ever wanted something like Nodemon but more capable, then you are at the right place.” This looks very promising and the README is full of examples.

Gajus Kuizinas

IN BRIEF:

BREAKING NEWS: The JS Party podcast has just dropped an episode called ▶️ The Future of React – so new, we haven’t listened to it, but it features Dan Abramov and Joe Savona so may make for good weekend listening..

“The most dangerous command you run every day: npm install” says Socket, who are introducing what they call ‘safe npm’, a transparent wrapper around npm designed to, well, make it less dangerous.

CORRECTION: In issue 627 we suggested the ECMAScript 2023 spec had entered a new draft stage. TC39 member Jordan Harband pointed out to us that it has been in such a state for some time. “There’s still a stage 4 PR not yet merged,” he noted, but there will be some progress in the next month.

Defer is a new ‘zero-infrastructure’ background jobs platform for Node.js apps.

Recently we linked to ???? Dittytoy, a fun online JavaScript environment for audio coding/experiments. Someone has somehow implemented an entire Commodore 64 SID synthesizer in it!

????  Developer Day: A Front-Row Seat to What’s New with Retool

Retool sponsor

RELEASES:

Node.js v19.8.0/1 (Current)

Jasmine 4.6
↳ Testing framework for browsers and Node.

pm2 5.3
↳ Popular Node production process manager.

Mongoose 7.0
↳ Popular MongoDB ODM for Node.js.

ESLint 8.36

???? Articles & Tutorials

Chrome 111 Gains a ‘View Transition’ Feature for SPAs — The View Transition API is only supported by Chrome so far, but allows easy animated page transitions within single-page apps (demo here). Luckily it suits progressive enhancement so you can start using it right now without feeling too guilty 😉 Multi-page app support is forthcoming.

Jake Archibald (Chrome Developers)

Create and Download Text Files with JavaScript — If you want your code to be able to generate a text (such as JSON) file on the fly and have it downloaded by the user’s browser, it’s reasonably easy.

Amit Merchant

Five Mistakes I Made When Starting My First React Project — Richard shares his early React mistakes with the hope you can learn from his misfortunes. He tackles topics like using defaultProps, propTypes, and class components.

Richard Oliver Bray

Too Much Tech Debt in Your node_modules? Our Team of JS Devs Can Help — We are a team of senior software engineers who specialize in tech debt. Let us modernize your JavaScript stack ????

UpgradeJS.com | JavaScript Upgrade Services sponsor

Progressively Enhancing a Table with a Web Component — Building a web component wrapper to add table sorting.

Raymond Camden

Shell-Free Node.js Scripting with Execa 7.1Execa is a popular process execution library for Node and the latest version includes an interesting $ method feature for writing zx-style scripts with it, making it even more useful for shell scripting style usecases.

ehmicky

What is Vite and Why Use It Over Create React App?

Luke Twomey

Pointers on Upgrading from Cypress v9 to v12

Gleb Bahmutov

How to Use v-model with Form Inputs in Vue

Dmitri Pavlutin

How to Create and Use Path Aliases in TypeScript Imports with Vite

Hasibul Hasan

What Is Deno and How to Use Its Sandbox?

Roman Zaynetdinov

???? Code & Tools

Template: A Simple Framework for Webapps — The author built it for his own projects, but notes: “It’s a joy to work in, feels “frameworky” but it’s just web standards with <100 lines of convenience JS wrapped around it. There is no magic beyond what the browser provides – I like it that way.” We do too.

William Blankenship

React ProseMirror: Integrate the ProseMirror Editor with ReactProseMirror is a toolkit for building rich text editors for the Web.

The New York Times

Breakpoints and console.log Is the Past, Time Travel Is the Future — 15x faster JavaScript debugging than with breakpoints and console.log, now with support for Vitest.

Wallaby.js sponsor

Fable 4.0: F# to JavaScript Compiler — If you fancy F#’s flavor of almost-entirely-functional development, this could be for you. GitHub repo.

Fable

MiniSearch: Small In-Memory Fulltext Search Engine for Browser and Node — The strength is that the indexed data is stored locally, allowing it to work offline and giving good performance, as seen in this demo.

Luca Ongaro

css-variable: Tiny Treeshakable Library to Define CSS Custom Properties in JS — Compatible with popular CSS-in-JS libraries like Emotion, styled-components, Linaria, etc., and it boasts better CSS minification and smaller virtual DOM updates, among other features.

Jan Nicklas

Tremor 2.0: The React Library to Build Dashboards Fast — Provides an array of modular components to build data-driven dashboards. v2.0 is the “first step towards a production-ready version of Tremor” and sees a full switch to Tailwind CSS. Homepage.

Tremor Labs

Stable Diffusion Plugin for Photoshop — Writing code that worked with Adobe’s weird JS variant was ghastly, but this uses their new ‘UXP’ based approach, so is interesting enough for that alone. This plugin also opens up the Stable Diffusion generative art system to Photoshop users.

Abdullah Alfaraj

Flexboard: A React Component Library for Resizable Sidebars — Try the live example. The code allows you to set min/max sizes for the resizable parts of the layout.

Dorbus

???? Jobs

Full Stack JavaScript Engineer @ Emerging Cybersecurity Startup — Small team/big results. Fun + flexible + always interesting. Come build our award-winning, all-in-one cybersecurity platform.

Defendify

Software Engineer (Frontend) — Join our “kick ass” team. Our software team operates from 17 countries and we’re always looking for more exceptional engineers.

Sticker Mule

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

????‍???? Got a job listing to share? Here’s how.

Fuite 2.0
↳ Tool for finding memory leaks in web apps.

???? wavesurfer.js 6.6
↳ Navigable waveform built on Web Audio & canvas.

Svelte-Inview 4.0
↳ Svelte action that monitors when an element enters/leaves the viewport.

Discord.js 14.8
↳ Library for using the Discord chat API.

Plotly.js 2.20
↳ Powerful charting library. (Examples.)

Recharts 2.5
↳ React + D3 charting library. (Examples.)

deepmerge 4.3.1
↳ Merges the enumerable properties of objects.

Vue Testing Library 7.0

React Table Library 4.1

New JavaScript features of the past few years

#​629 — March 10, 2023

Read on the Web

JavaScript Weekly

JavaScript Features from the Past Few Years — Packed with examples, this post tackles the changes and tweaks to JavaScript and TypeScript over the past several years (some as far back as ES6/ES2015, like tagged template literals).

Linus Schlumberger

Astro’s 2023 Web Framework Performance Report — The folks working on Astro looked at data from thousands of sites to understand how sites built around Astro, Gatsby, Next.js, Nuxt, Remix, SvelteKit and WordPress perform on common Web performance metrics. Shipping less JS equals more performance.

Fred Schott (Astro)

In other Astro related news, Astro 2.1 has just been released with experimental automatic image optimization support, plus they’ve visually rebranded the project.

A Fresh Introduction to Next 13+ — Learn Next.js, the complete full-stack framework to create basic blog websites up to full-blown apps and APIs! Plus if you are already familiar with Next.js, we have a course building a full app on Next 13+.

Frontend Masters sponsor

TypeScript’s Migration to Modules — TypeScript has restructured its codebase to use ES modules. For this, we get smaller package sizes, quicker build times, and little disruption to end users. A CommonJS API is provided for now so that build scripts don’t break. This post goes deep in to what the move entailed.

Daniel Rosenwasser and Jake Bailey

IN BRIEF:

A quick look at the 12 most popular Node.js frameworks, as of 2023. Don’t feel left out if you prefer Deno, there’s a roundup of Deno frameworks, too.

Jest 29.5 has added a feature to randomize the order in which tests are run – why? Your tests should be isolated and not depend upon each other – this will unearth any problems.

Three things are certain: death, taxes, and jQuery. Still the most heavily deployed JS library, jQuery 3.6.4 has been released with a reversion to how it determines browser support for CSS selection features.

???? UtahJS Conf 2023 is taking place in September, and their call for speakers is open till April 3.

???? A neat approach to creating a static, password protected page with AES‑256.

The folks at Moddable went to FOSDEM to make the case for using JavaScript in embedded systems.

RELEASES:

TestCafe 2.4 – E2E web testing tool now with a visual selector debugger.

SWR 2.1 – React hooks for data fetching. Now with subscription mode.

Mantine 6.0
↳ 100+ React component library.

Node.js 18.15.0 (LTS)

Ember.js 4.11

???? Articles & Tutorials

Common Beginner Mistakes with React — Experienced React educator Josh has seen all the problems people encounter and here he digs into “9 of the most dastardly gotchas” and how to resolve them.

Josh W Comeau

▶  Coding Kenta Toshikura’s Glass Effect with Three.js — Yet more creative noodling with Three.js and shaders that goes over my head.

Yuri Artiukh

React Authentication, Simplified — In this article, we lay out a new approach to authentication (plus access control & SSO) in React applications.

Userfront sponsor

How to Change the Favicon When Switching Browser Tabs — Originally inspired by Astro, you can see the concept at work on notepad.js.org

Amit Merchant

▶  Progressive Web Apps (PWA) for Beginners — Beginner-focused series on building PWAs, covering their capabilities, pros and cons, and more over 17 videos.

Microsoft Developer

How to Make Slow React Native Apps Faster — The folks over at Retool recently released an app to build native apps in a similar way to Web-based ones. This post covers a few optimizations they made to make it app faster.

James Lee (Retool)

Full-Stack TypeScript with tRPC and React — How to create a CRUD app with Express on the server and React on the client using tRPC to communicate between the two.

Robin Wieruch

Building an Image Recognition App with Pinecone, Hugging Face, and Vercel

Roie Schwaber-Cohen

Using Zod and TypeScript for More Than User Input Validation

Sebastien Castiel

Building Complex Forms in Vue

Olufunke Moronfolu

???? Code & Tools

HuggingFace.js: Use Lots of ML Models from JavaScriptHugging Face is a popular online community and repository of machine learning models. The goal of this library is to open up those models more easily to JavaScript.

Hugging Face

Dynaboard: A Visual Web App IDE Made for Developers — Build high performance public and private web applications in a collaborative — full-stack — development environment.

Dynaboard sponsor

Chrono: A Natural Language Date Parser — Give it a string like “today”, “last Friday”, “2 weeks from now”, or even an entire date and time, and it’ll come up with a date object to suit.

Wanasit Tanakitrungruang

Embetty 4.0: A Privacy-Conscious Way to Show Third Party Embeds — Tweets, and Facebook, Video or YouTube thumbnails (see demo here.) The privacy comes from using a proxy server you host yourself.

heise online

Finder 3.0: CSS Selector Generator — Given an element, it produces the shortest possible selector that reaches (solely) that element.

Anton Medvedev

Tuple, a Lightning-Fast Pairing Tool Built for Remote Developers

Tuple sponsor

Feathers 5: Node.js API & Real-Time App FrameworkFeathers is a great option if you want to spin up a CRUD app tied to a database and now it’s “TypeScript all the way down” too (you can choose to use JS, as you prefer). Leap into the quick start guide to see what it’s about.

David Luecke

FormKit: The Open-Source Form Framework for Vue — Ships with production-ready scaffolding like inputs, forms, submission and error handling, and validation rules.

FormKit, Inc.

???? Jobs

Software Engineer — Join our happy team. Stimulus is a social platform started by Sticker Mule to show what’s possible if your mission is to increase human happiness.

Stimulus

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

????‍???? Got a job listing to share? Here’s how.

ClearScript 7.4
↳ MS library to add JS scripting to .NET apps.

Million 2.0
↳ Fast virtual DOM that makes React faster.

Video.js 8.2
↳ Flexible media player control.

Embla Carousel 7.1
↳ Smooth carousel library. (Examples.)

Deck.gl 8.9
↳ WebGL2-powered data viz framework.

MUI X 6.0
↳ Suite of advanced React UI components.

ReacType 14.0
↳ Rapid React prototyping tool.

Lebab 3.1.2
↳ Turn ES5 into ES6. It’s Babel backwards!

Rimraf 4.4
↳ Cross platform rm -rf for Node.js.

???? A Bonus Item

Ink 4.0: Use the React Approach for Building Interactive CLI Apps — Build your command line apps using React-style components. As of v4.0, Ink is now pure ESM, requires React 18, and requires Node 14.16+.

Vadim Demedes

Introducing nsuv

Introducing nsuv

nsuv is a C++ wrapper around libuv with the main goal of supporting compile-time type safety when propagating data.

You can find the open source package here: https://github.com/nodesource/nsuv

Here at NodeSource we are focused on fixing issues for the enterprise. This includes adding functionality and features to Node.js that are useful for enterprise-level deployments but would be difficult to upstream. One is the ability to execute commands remotely on Worker threads without the addition of running the inspector, such as capturing CPU profiles or heap snapshots. Another feature necessary to make Node.js more reliable in production is the ability to record and send metrics without being at the mercy of a busy event loop.

To achieve these, we run a separate thread that receives commands and gathers metrics from each Node.js thread. The locks and data queues in the separate thread are managed by libuv. As the codebase grew, usability issues began to come up, such as remembering the correct type of each void pointer and keeping track of the lifetime of the many shared locks and resources. Our solution was to write a wrapper for libuv to alleviate these problems.

We had a lot of existing libuv code and didn’t want to rewrite everything from scratch. So we wrote a template class library that inherits from each libuv handle or request type and uses the curiously recurring template pattern (CRTP) for inheritance. Doing so made it possible to write a wrapper that serves as a drop-in replacement, allowing for incremental improvements while supplementing the wrapper’s API with what was needed.

N|Solid has a zero-failure tolerance, so none of our code can accidentally terminate your process. One way we do this is to try our best not to perform additional allocations. If an allocation is necessary, it always does with a strong exception guarantee, which is then caught and returned as a libuv error code.

We have also enabled compile time warnings when returned error codes aren’t handled. While developing nsuv, we analyzed many existing C++ projects that use libuv and discovered that most of them assume the state of the application and lack sufficient error handling in case something unexpected occurs. This can be especially painful when working with asynchronous code, but we understand that not everyone requires the same level of caution. It can be disabled by defining NSUV_DISABLE_WUR in your flags.

Getting Started

The following code example shows the execution of a simple libuv timer, and the only change was to turn the uv_timer_t to a nsuv::ns_timer instance while still being able to use the original libuv APIs:

static void timer_cb(uv_timer_t* handle) {
Foo* foo = static_cast<Foo*>(handle->data);
delete foo;
uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
}

static void call_timer() {
ns_timer timer;
Foo* foo = new Foo();

timer.data = foo;
uv_timer_init(uv_default_loop(), &timer);
uv_timer_start(&timer, timer_cb, 1000, 0);
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

As you can see, there’s no need to cast timer before being passed to libuv’s timer function since ns_timer is a derived class of uv_timer_t and upcasting is implicit. It offers the first step in converting code to be more type-safe and improve overall usability. Improvements can be made incrementally from here. Below we take advantage of the CRTP and use it to downcast the uv_timer_t to the nsuv counterpart after using libuv’s timer API:

static void timer_cb(uv_timer_t* handle) {
// Downcast the libuv handle to its nsuv counterpart.
ns_timer* timer = ns_timer::cast(handle);
// Convenience method to retrieve and cast data.
Foo* foo = timer->get_data<Foo>();

delete foo;
timer->close();
}

While this is a good first step, it still requires we know what the data value should be cast to. The call to get_data() only serves as a convenience method for easier casting.

Passing Data

One of the most painful parts of working with libuv was ensuring we didn’t accidentally cast a void pointer to the wrong type from a specific queue. While this could be verified by hand, having the compiler tell us if we did it wrong would have been more reassuring.

To accomplish this, we wrapped libuv in a way that allows any function that takes a callback to be passed an arbitrary pointer. That pointer is then passed along as an argument in the callback’s parameters. Preventing us from needing to use the uv_handle_t::data property and ensuring the callback always has the correct pointer type.

Below we have fully converted the previous code to use nsuv. As you can see, the pointer that would have been stored in the data parameter can now be passed to the method, making it available as an argument in the callback.

static void call_timer() {
ns_timer timer;
Foo* foo = new Foo();
int r;

r = timer.init(uv_default_loop());
//check r
r = timer.start(+[](ns_timer* handle, Foo* foo) {
delete foo;
handle->close();
}, 1000, 0, foo);
// check r

uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

For the sake of the example, a C++ lambda function was used. Remember that when passing a lambda function, it needs to be converted to a plain old function pointer using the + operator.

Also notice that we are assigning and handling all return values from each call. As mentioned above, the compiler will warn us if we do not check each call’s return codes. For simplicity of future examples, the return value will be assigned but not include a comment that it needs to be checked.

Locks

Because of all the communication between threads, mutexes were heavily used. To make things simpler, we added a couple of APIs for convenience. The first API of note is that init() accepts an optional boolean value. If true is passed in, the mutex is automatically destroyed when the destructor is called. The other was to add an API for scoped locking.

static void try_mutex() {
ns_mutex mutex;
// The optional boolean argument sets if the mutex should be
// automatically destroyed in the destructor.
int r = mutex.init(true);
// Convenience class to create scoped locks. Accepts either a
// pointer or reference.
{
ns_mutex::scoped_lock lock(mutex);
}
}

Having a mutex call destroy() in the destructor was kept false by default to maintain parity with the libuv API and prevent surprises while migrating to nsuv.

Example Usage

At first, we only implemented the libuv APIs that were necessary for us to use internally, but since deciding to open source the library we have begun to add as much of the remaining libuv APIs as possible. But despite not having yet ported the entire libuv API, it’s still possible to take advantage of what has been done. The following is an example from a test that includes the checks to demonstrate how class instances are being passed around.

#include “nsuv-inl.h”

using namespace nsuv;

ns_tcp client;
ns_tcp incoming;
ns_tcp server;
ns_connect<ns_tcp> connect_req;
ns_write<ns_tcp> write_req;

static void alloc_cb(ns_tcp* handle, size_t, uv_buf_t* buf) {
static char slab[1024];
assert(handle == &incoming);

buf->base = slab;
buf->len = sizeof(slab);
}

static void read_cb(ns_tcp* handle, ssize_t, const uv_buf_t*) {
assert(handle == &incoming);

handle->close();
client.close();
server.close();
}

static void write_cb(ns_write<ns_tcp>* req, int) {
assert(req == &write_req);
// Retrieve a reference to the uv_buf_t array as a std::vector.
assert(req->bufs().size() == 2);
}

static void connection_cb(ns_tcp* server, int) {
int r;
r = incoming.init(server->get_loop());
r = server->accept(&incoming);
r = incoming.read_start(alloc_cb, read_cb);
}

static void connect_cb(ns_connect<ns_tcp>* req, int, char* data) {
static char bye_ctr[] = “BYE”;
uv_buf_t buf1 = uv_buf_init(data, strlen(data));
uv_buf_t buf2 = uv_buf_init(bye_ctr, strlen(bye_ctr));
// Write to the handle attached to this request and pass along data
// by constructing a std::vector.
int r = req->handle()->write(&write_req, { buf1, buf2 }, write_cb);
}

static void do_listen() {
static char hello_cstr[] = “HELLO”;
struct sockaddr_in addr_in;
struct sockaddr* addr;
int r;

r = uv_ip4_addr(“127.0.0.1”, 9999, &addr_in);
addr = reinterpret_cast<struct sockaddr*>(&addr_in);

// Server setup.
r = server.init(uv_default_loop());
r = server.bind(addr, 0);
r = server.listen(1, connection_cb);

// Client connection.
r = client.init(uv_default_loop());
r = client.connect(&connect_req, addr, connect_cb, hello_cstr);

uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

The request types ns_write and ns_connect are also used in the above example. They inherit from uv_write_t and uv_connect_t respectively, and can be upcast and downcast the same way as handles. Each request type API is templated to identify which handle is being used and can return the correct handle type.

While the write() method does accept a uv_buf_t[] array, we’ve also added the ability to pass in a std::vector of buffers for ease of use. Once the request is complete, the list of written buffers can be retrieved via the ns_write::buf() API as a reference to the std::vector that’s stored internally.

Conclusion

One goal when creating nsuv was to reduce cognitive load by mimicking the libuv API naming and structure while adding safety features offered by C++. We’ve made it easy to transition existing projects to nsuv. By open-sourcing nsuv, we hope to give developers more confidence that their code will behave as expected when expected.

There is near zero runtime overhead using nsuv. The template function proxy pattern used can be completely optimized out by modern compilers. Combining that with the ability to enforce type checks at compile time, I won’t be using libuv in C++ without nsuv going forward.

Using nsuv is as simple as including the two header files from the project repository. We are still working on getting complete coverage of the libuv API and hope the community can help us decide what to work on next. We are also working on porting all applicable tests from libuv to nsuv, which can serve as usage examples. We hope that you’ll find nsuv as useful as we have.

NodeSource has delivered Node.js fresh to your Linux system via your package manager within hours, minutes, days, or weeks. For NodeSource, sustaining the community is essential because we want to support more people using Linux to have Node.js in production.

Also, we are looking for more community involvement in the project. Help will be appreciated! So if you have ideas or solutions or want to help us continue supporting open source, you can contribute to this GitHub Repo.

Continue the conversation with NodeSource here:
Twitter
LinkedIn
Github
As always, the best place to contact us is via our website or [email protected]

Ready for more?

If you are looking for NodeSource’s Enterprise-grade Node.js platform, N|Solid, please visit https://downloads.nodesource.com/. For detailed information on installing and using N|Solid, please refer to the N|Solid User Guide.

Garbage collector experiments

#​628 — March 3, 2023

Read on the Web

JavaScript Weekly

Sandworm Audit: A New JS Auditing Tool — A command-line tool to scan a project and dependencies for vulnerabilities, license issues, and related problems. You get JSON reports, visualizations of dependency trees, and a CSV of all dependencies and license information.

Sandworm

Experiments with the JavaScript Garbage Collector — A look at the prevalence of elusive memory leaks and how understanding the garbage collector’s decision-making process can help avoid them. Sheds light on some scenarios related to GC behavior across five examples.

Alexey Lebedev

The Fastest JavaScript Data Grid Component — A solid JS data grid is essential in all business apps. Bryntum’s powerful Grid component lets you sort, group and filter datasets with great performance. Includes a TreeGrid, API docs and demos. Seamless integration with React, Angular & Vue apps.

Bryntum sponsor

‘You Don’t Need a Build Step’ — You need to remember the Deno folks have an alternative JS runtime to promote, but they always make great points. A build step has helped with getting things to run in the browser or to transpile and bundle code elsewhere. But with modern tooling, do we still need a build step? Andy lays out the problem and explains how, unsurprisingly, Deno and Fresh work around it.

Andy Jiang (Deno)

Announcing TypeScript 5.0 RC — Barring any critical bug fixes, this is as good as done. The headline feature in 5.0 is likely to be decorators and Daniel does a rather extensive job of showing them off here. Other tweaks include being able to add const modifiers to type parameter declarations, supporting multiple config files in extends, and all enums are now union enums.

Daniel Rosenwasser

The 2023 JavaScript Site Generator Review — Zach puts Astro, Eleventy, Enhance, Gatsby, Next.js, Nuxt, Remix and SvelteKit through their paces, focusing on quantitative factors like build time, the amount of JavaScript code needed at runtime, and the presence (or not) of telemetry.

Zach Leatherman

IN BRIEF:

Node.js Toolbox is a new site bringing together data-driven comparisons of Node packages in various categories.

The React Flow project shared how it ‘gets paid fairly’ for open source.

You can now add pronouns to your GitHub profile.

RETRO VIBES: Using JavaScript to recreate ANSI art from a screenshot.

James Q Quick floats some ideas for JavaScript trends in 2023.

RELEASES:

Deno 1.31 – Now with package.json support.

Preact 10.13 – Fast 3KB React alternative.

zx 7.2 – JS shell scripting approach.

Papa Parse 5.4 – Fast in-browser CSV parser.

???? Articles & Tutorials

Crawling Weather Forecasts with Cypress — Even if you don’t care for the weather, this is a neat code-led demonstration of using the Cypress browser oriented testing tool for performing a variety of productive activities.

Gleb Bahmutov PhD

????  The JavaScript Era Happened Because ‘We Were Fed a Line’ — If you want a spicy (literally) opinion piece, this is your fill for this week. Jared rails against the ebb and flow of things that are considered outdated/bad or not (e.g. HTML-first was in, then out, then in). Unsurprisingly, it provoked an extensive discussion on Hacker News.

Jared White opinion

Need to Upgrade to Node 18? Don’t Have Time? Our Experts Can Help ???? — Stuck in dependency hell? We’ve been there. Hire our team of experts to upgrade dependencies, gradually paying off tech debt.

UpgradeJS.com: JavaScript Upgrade Services sponsor

Using Sourcegraph to Discover Non-NPM JS Projects“If you want to discover package.json files for JavaScript projects that are not NPM libraries, how would you do it?” An interesting walkthrough one approach using the Sourcegraph platform.

StackAid

Building an Animated SVG Logo with Anime.jsAnime.js is a JS animation library that works with CSS properties, SVG, DOM attributes and JS objects.

Jozef Maxted

Bootstrap Your React Journey with Tic-Tac-Toe — It’s easy to forget that not a day goes by that somebody is taking their first steps on their journey to learn React. Here’s a recently updated way to start, direct from the source.

React Docs

▶  A Deep Dive into the Node.js Event Loop

Tyler Hawkins

What is ref() in Vue?

Dmitri Pavlutin

???? Code & Tools

Text Highlighter: Highlight Search Results in Textareas — Responsively highlight search results within a textarea element without interfering with its operation. There’s a live demo.

Walter Staeblein

Civet: It’s Like CoffeeScript.. for TypeScript! — I’ve gotta admit, I like this. This example alone shows off the power. In a world where build toolchains are the norm, maybe this could take off, but my CoffeeScript experiences of yesteryear restrain me from going ‘all in’ on something like this for now.

Daniel X Moore and contributors

✈️ Get Your Tests Flying with Wallaby.js — Turbocharge your productivity with the 15x faster test runner. Spend more time coding, less time waiting.

Wallaby.js sponsor

Remult: A CRUD Framework for Full-Stack TypeScript — Promises a ‘zero-boilerplate’ CRUD API experience by using your TypeScript entities as a single source of truth for your API, frontend type-safe API client and backend ORM. There are tutorials for using it alongside React, Angular, Vue and Next.js.

Remult Team

React Flow: Create Node-Based UIs — The example on the homepage shows off this powerful React component well.

Webkid GmbH

ts-reset: A ‘CSS Reset’ for TypeScript — CSS isn’t involved but much like a reset stylesheet flattens out browser quirks and differences, ts-reset aims to ‘smooth off’ some hard edges of TypeScript.

Total TypeScript

Full Stack Monitoring Made Affordable

TelemetryHub sponsor

Lenis: A Smooth Scroll Library — Boasts a number of extra features compared to similar libraries that allow you to do scroll animations, parallax, etc. You can try it out here.

Studio Freight Darkroom

iDraw.js: A Web Vector Graphics Drawing Framework — One motivation for this high level abstraction appears to be to power Web-based graphics editing tools like this.GitHub repo.

idrawjs Team

eta (η) 2.0.1
↳ Embedded template engine for Node, Deno & browser.

pnpm 7.28
↳ Alternative, efficient package manager.

???? Jobs

Full Stack JavaScript Engineer @ Emerging Cybersecurity Startup — Small team/big results. Fun + flexible + always interesting. Come build our award-winning, all-in-one cybersecurity platform.

Defendify

Software Engineer (Frontend) — Join our “kick ass” team. Our software team operates from 17 countries and we’re always looking for more exceptional engineers.

Sticker Mule

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

????‍???? Got a job listing to share? Here’s how.

???? Experimental Projects..

Ezno: A (Now Open Source) Experimental JS Compiler — We first mentioned Ezno (explained here) last year but this week it has been open-sourced. It’s a parser, partial-executor, optimizer and type checker for JavaScript written in Rust and it continues to get better in 2023.

Ben X

Dak: A Lisp-Like Language That Transpiles to JS“I had an itch to make a lisp like language that was a thin layer on top JavaScript. … It’s brittle, hot off the oven.” We appreciate such honesty. There’s a playground and a language tour if you want to check it out.

Naitik Shah