今日已更新 240 条资讯 | 累计 23823 条内容
关于我们

标签:#JavaScript

找到 648 篇相关文章

AI 资讯

Why I’m Building an Open-Source Frontend Engineering Handbook

Every frontend developer eventually reaches the same point. You know React. You know TypeScript. You know how to build components. But then you join a real project. Suddenly the questions are no longer about writing a component — they’re about engineering. How should the project be structured? Where should authentication logic live? When is React Context enough? When should React Query own the data? How do you prevent a codebase from becoming impossible to maintain? What makes a frontend application scalable? How do AI coding tools fit into modern development? These are the questions I kept asking myself while working on frontend applications. The problem wasn’t the lack of information. The problem was that the information was scattered across hundreds of blog posts, GitHub repositories, conference talks, documentation pages, and personal notes. Tutorials Teach Frameworks Modern tutorials are excellent at teaching frameworks. You can easily learn: React Vue Angular Next.js TypeScript But very few resources explain what happens after that. How do experienced teams actually build production frontend applications? How do they organize folders? How do they write maintainable code? How do they review pull requests? How do they optimize performance? How do they scale applications from one developer to twenty? Those are engineering problems — not framework problems. Frontend Engineering Is a Different Skill Writing React code doesn’t automatically make someone a frontend engineer. Frontend engineering includes topics such as: Project architecture Feature-based organization Authentication and authorization API design State management Data fetching strategies Performance optimization Accessibility Error handling Testing CI/CD Monitoring Code quality Documentation Team conventions These subjects rarely live in one place. AI Has Changed the Way We Build Software Another reason I started this project is the rise of AI coding assistants. Learn about Medium’s values Today many de

2026-07-25 原文 →
AI 资讯

Removing a Photo's Background in the Browser, With No Upload: AI Licenses, ONNX Models, and a Frozen Tab

I wanted to add a background-removal tool to my site's image cluster that stayed true to the 100% client-side processing principle I already use for PDFs and image conversions. The path there was anything but linear: a library dropped over a licensing problem, a carefully chosen model that turned out more limited than expected, and a bug that froze the entire page — not just the tool — during computation. Here's the full build, including the parts that didn't work the first time. The starting problem: what's actually feasible for free? The initial idea was broad: remove backgrounds, and maybe unwanted objects too. The two tasks have very different difficulty levels. Removing objects requires inpainting — plausibly reconstructing the erased area — which in practice still means heavy generative models, impractical to run client-side with good quality on an average device. Removing a background , on the other hand, is a segmentation problem: separating a subject from its surroundings. That has much lighter models available, runnable entirely via WebAssembly with no server involved at all. So: background removal only, object removal shelved for later. The AGPL trap The first library that looked like a perfect fit turned out to be distributed under AGPL , a strong copyleft license. Free to use — but with a real catch for anyone embedding it in a public, closed-source web service: AGPL can require releasing the full source of the project that embeds it, under the same license. "Free for the end user" and "safe to drop into a closed-source commercial product" are two different questions, and it's worth answering the second one before writing integration code, not after deploying it. Before wiring any "free" AI library into a commercial project, check the exact license, not just the price tag. AGPL, GPL, and other strong copyleft licenses are fine for personal or internal tools, risky for a public closed-source product. The fix: switch to Transformers.js — Hugging Face's li

2026-07-24 原文 →
AI 资讯

Knip Keeps My JS/TS Dependencies Honest (I Wish Python Had It)

Every long-lived JS/TS project I've worked on accumulates the same three kinds of rot: Dependencies in package.json that nothing imports anymore. You added moment , migrated off it, and the line stayed. Exports nothing consumes. A function was public once, the last caller was deleted, the export is still there advertising an API with no users. Whole files that fell out of the import graph but never got deleted, so every new engineer reads them trying to understand code that runs nowhere. None of this breaks the build. That's exactly why it survives. The compiler is happy, the tests pass, and the dead weight compounds quietly until onboarding takes a week and your bundle ships code no user will ever execute. The tool I've settled on for this is knip (by Lars Kappert). I run it on the enterprise codebase I maintain and on basically every other TS project I touch. One command: $ npx knip Unused files (2) src/legacy/formatValue.ts src/hooks/useLegacyModal.ts Unused dependencies (3) lodash package.json moment package.json @types/uuid package.json Unused exports (5) parseLegacy src/parse.ts:42:14 toLegacyDate src/date.ts:9:14 ... Files, dependencies, and exports in one pass, cross-referenced against the actual import graph. It's the first tool I've used that treats all three as the same problem, which they are: something is declared, nothing uses it, delete it. The honest caveat Knip is not zero-config on a real codebase. Anything resolved dynamically, runtime import() , plugin systems, framework entry points it doesn't recognize (Next.js pages, a CLI bin, config files loaded by string), gets flagged as unused when it isn't. You will get false positives on day one. The fix is a knip.json that names your real entry points, and after that it's accurate. But budget an afternoon to tune it before you trust the output enough to delete on it. Anyone who tells you it's instant hasn't run it on a large app. What I actually want Here's the part that bugs me. This problem is not sp

2026-07-24 原文 →
AI 资讯

# From JavaScript to Node.js: Understanding What Really Happens Behind the Scenes (Part 4.3A.1)

# Module Resolution Algorithm (Part 1): How Node.js Finds the Right Module In the previous article, we explored one of the most fascinating parts of Node.js—the hidden Module Wrapper Function. We learned that every CommonJS module is wrapped inside a function before execution, and we also discovered that require() is not a JavaScript feature. It is provided by the Node.js runtime. But a very important mystery still remains. When we write: const fs = require ( " fs " ); or const math = require ( " ./math " ); how does Node.js know where these modules are located? How does it decide whether "fs" is a built-in module or a file inside your project? Why does require("./math") work even if you don't write .js ? And what happens internally before your code starts executing? The answer lies inside one of Node.js's most important systems: The Module Resolution Algorithm Understanding this algorithm is essential because every Node.js application uses it hundreds or even thousands of times while starting. What is Module Resolution? The word resolution simply means: Finding the actual file represented by the string passed to require() . Suppose you write: require ( " ./math " ); To you, "./math" looks like a file. But for Node.js, it is initially nothing more than a string. "./math" Node cannot execute a string. It needs the real file. So its first job is to answer one question: "Which exact file should I load?" The complete process of converting the string inside require() into an actual file on disk is called Module Resolution . Why Does Node Need a Resolution Algorithm? Imagine a project like this: project/ ├── app.js ├── math.js ├── database.js ├── auth.js └── utils/ ├── logger.js └── helper.js Now look at these statements. require ( " ./math " ); require ( " ./database " ); require ( " ./utils/logger " ); require ( " fs " ); require ( " express " ); All of them look similar. But internally they are completely different. Some point to your own files. Some point to Node's bu

2026-07-24 原文 →
开发者

Ich habe einen echten Speedtest in Vanilla JS gebaut (mit Cloudflare API)

Ich habe einen echten Speedtest in Vanilla JS gebaut (mit Cloudflare API) Kein npm install. Kein React. Kein 200-MB-node_modules-Ordner. Nur HTML, CSS und ~250 Zeilen JavaScript, die deine echte Internetgeschwindigkeit messen. 👉 Live-Demo: dsl.nevik.de/speedtest Warum noch ein Speedtest? Es gibt Speedtest.net, FAST.com und dutzende andere. Warum also selbst bauen? Drei Gründe: Transparenz: Ich wollte genau verstehen, was gemessen wird – und was nicht. Größe: Die meisten kommerziellen Speedtests laden mehrere MB an Tracking-Scripts. Meiner ist eine einzige HTML-Datei mit eingebettetem JS. Kontrolle: Ich kann das Ergebnis direkt gegen den gebuchten Tarif des Nutzers bewerten und eine fundierte Empfehlung geben. Das Ergebnis ist ein Speedtest, der in unter 50 KB ausgeliefert wird, auf jedem Gerät läuft und echte Messwerte liefert – keine Schätzwerte. Die Architektur: Drei Phasen, drei Messungen Ein guter Speedtest misst drei Dinge: Ping (Latenz): Wie schnell kommt ein Datenpaket hin und zurück? Download: Wie schnell kommen Daten bei dir an? Upload: Wie schnell kommen Daten von dir raus? Für alle drei nutze ich die öffentliche Cloudflare-Speedtest-API , die unter speed.cloudflare.com läuft. Cloudflare betreibt eines der größten Edge-Netzwerke der Welt, hat Server in praktisch jedem Land und – ganz wichtig – erlaubt CORS für diese Endpunkte, sodass wir direkt aus dem Browser heraus messen können. Die zwei Endpunkte, die alles tragen: const CF_DOWN = ' https://speed.cloudflare.com/__down?bytes= ' ; const CF_UP = ' https://speed.cloudflare.com/__up ' ; __down?bytes=N liefert exakt N Bytes zurück. __up nimmt einen POST-Body beliebiger Größe entgegen. Das war's. Kein API-Key, keine Rate-Limits, die für unsere Zwecke relevant wären, keine Kosten. Phase 1: Ping messen (ohne WebSocket) Klassische Speedtests nutzen für den Ping oft WebSockets oder RTCPeerConnection -Tricks. Das ist komplex und fehleranfällig. Mein Ansatz: Wir laden einfach einen winzigen Datenblock (1 KB) fünfma

2026-07-24 原文 →
AI 资讯

A CSV Viewer That Never Uploads Your Data

I just wanted to open a CSV file quickly. Instead, I got: Slow spreadsheet apps Online tools that upload my data Way too much friction So I defined a simple goal: Fast and frictionless Fully local (no uploads) Spreadsheet-like experience That’s what I built. What you can do with it Open CSV files instantly (drag & drop, no setup) Search and filter large datasets in seconds Edit data like a spreadsheet Export exactly what you see Why this matters Everything happens locally in your browser: Your data never leaves your device No account required No tracking, no storage Built with client-side JavaScript — no backend involved. Just open, edit, and export. How it works Built with client-side JavaScript — no backend involved. Spreadsheet-Like Editing Click a cell to select it, then press Enter or double-click to start editing. Press Enter again to save the value and move to the cell below. Use Option + Enter on macOS or Alt + Enter on Windows to insert a line break. You can also drag the small fill handle to copy a value across multiple cells. Export the Current View The exported CSV reflects the current table state, including: Search results Sorting order Visible columns Saved cell edits Try it yourself Open a CSV file, edit a few cells, and export it — all without uploading anything. 👉 https://csv-open.github.io/ No signup. No upload. Just works. Handles CSV files up to 25MB Supports multiple languages

2026-07-24 原文 →
AI 资讯

The Hidden Part of Refresh Token Implementation that every developers should know

What happens when 5 parallel API calls hit for an expired JWT at the exact same millisecond. Imagine this: You’ve built a sleek, high-performance React dashboard. The UI is sharp, dark mode is gleaming, components are modularized, and React Query is executing parallel data fetches like a grand symphony. You brew a cup of coffee, open the app after lunch, hit refresh, and… BAM! You are immediately booted back to the Login screen. No warnings, no friendly error toasts—just a cold, ruthless redirect. You check your JWT expiration timer. The access token died 5 seconds ago, but your refresh token is valid for another 14 days. So why on earth did your app decide to kick you out like an uninvited party crasher? Welcome to the chaotic nightmare of Token Refresh Race Conditions in Axios Interceptors . In this article, we’ll walk through how parallel React queries can accidentally DDOS your own backend, why standard interceptor tutorials fail in production, how we built a promise-queue lock mechanism to solve it, and the subtle "gotcha" lurking in simple error detail checks that almost broke everything anyway. 1. The Problem: The Dashboard Stampede When a user logs into our app and opens the main dashboard, React Query triggers a stampede of concurrent API requests: GET /api/teams/users/ (Fetch team members) GET /api/teams/addresses/ (Fetch locations) GET /api/auth/profile/ (Fetch user profile) GET /api/auth/activity/recent/ (Fetch activity log) GET /api/notifications/ (Fetch unread alerts) Under normal circumstances, all five requests ride happily on the same valid Bearer <access_token> HTTP header. React App ---------------------------------------------> Django Backend GET /users/ [Bearer valid] ---> 200 OK GET /locations/ [Bearer valid] ---> 200 OK GET /profile/ [Bearer valid] ---> 200 OK The Ticking Time Bomb Fast forward 15 minutes. The short-lived access token expires. The user clicks on the "Analytics" tab. All 5 queries trigger at the exact same millisecond ( T = 0ms

2026-07-24 原文 →
AI 资讯

A Button Showcase with One-Click HTML Copy

When building a website, choosing a button design can take more time than expected. You may want something simple, soft, colorful, dark, outlined, or slightly unusual—but comparing many styles usually means repeatedly editing CSS and refreshing the page. To make that process easier, I created a browser-based button showcase. Try It Online You can use it directly from the following page: https://uni928.github.io/Uni928PublicHTMLs/index78.html There is nothing to install. Open the page, browse the available designs, and choose a button you like. Many Button Styles in One Place The page includes a wide range of button designs, including: Light and subtle buttons Solid-color buttons Dark buttons Gradient buttons Outline buttons Rounded and pill-shaped buttons Buttons with icons More experimental designs The buttons are displayed as actual interactive elements, so you can compare their hover, focus, and pressed states directly in the browser. Click a Button to Copy It The main feature of this tool is its copy workflow. Clicking a button copies a minimal HTML example for that design. This makes it easier to take only the button you need instead of copying the entire showcase page. The generated example includes the necessary HTML and CSS, so it can be pasted into a new file and tested immediately. Copy Features for Faster Comparison The site also includes additional copy-related features to make browsing a large number of designs more convenient. You can: Copy a button directly by clicking it Review the generated code Copy frequently used button types from the quick-copy panel Receive visual feedback after a successful copy Use copied examples as standalone HTML files This is especially useful when you want to compare several designs before deciding which one to use in a project. Useful for Prototypes and Small Projects This tool is intended for situations where you need a usable button quickly, such as: Creating a prototype Building a small static website Testing a landi

2026-07-24 原文 →
AI 资讯

How We Built a 153-Node Interactive Lore Graph for Black Myth: Zhong Kui Using D3.js and Astro

The Challenge Rendering a complex 153-concept-node, 1,200-edge mythic relationship topology for mobile devices without triggering main-thread layout thrashing or heavy client-side JavaScript execution. The Technical Approach Build-Time D3 Force Layout Computation : Pre-computing node coordinates and physics simulation during the Astro static build step. Zero-Runtime SVG Pre-rendering : Outputting the rendered topology as inline SVG with CSS design tokens, preserving 60 FPS scrolling on mobile. Canonical Lore Data Architecture : Structuring 153 canonical concept nodes across Tang Dynasty exorcistic texts ( Nuo rituals) and Black Myth: Zhong Kui motifs. Check out the live interactive relationship map: Black Myth Lore & Concept Map Official website: blackmyth.game

2026-07-24 原文 →
AI 资讯

Three free tools for the CI noise tax

Serious engineering teams pay a quiet tax: dependency alerts nobody trusts, full test suites on one-line PRs, and CI YAML that only fails after a push. I built three small open-source CLIs that attack those loops: Tool Install Job vulntriage npm i -g vulntriage Which CVEs matter impactest npm i -g impactest Which tests to run gha-step npm i -g gha-step Run CI shell steps now npx vulntriage . --group --fail-on fix_now npx impactest -f vitest -q | xargs -r npx vitest run npx gha-step run test --dry-run All Apache-2.0. No SaaS. Designed to earn a place in CI by being boringly explainable. Canonical: https://sybilgambleyyu.github.io/posts/tool-family.html

2026-07-24 原文 →
AI 资讯

# 📓 TanStack Query: Core Concepts & Summary

1. Introduction: What is TanStack Query? TanStack Query (formerly React Query) is a framework-agnostic state management library designed specifically to manage Server State —handling data fetching, caching, background updating, and cache invalidation. 2. Server State vs. Client State & The Memory Reality Client State: Owned and controlled entirely by the browser (e.g., isModalOpen , selected UI theme). Server State: Owned by the remote backend database (e.g., user profiles, posts, cart items). The browser only holds a read-only temporary snapshot . Where is data physically stored? Physical Location: By default, cached data lives strictly in the browser tab's JavaScript RAM (In-Memory) . Backend ("The Server"): Refers to your remote API/database (regardless of whether it runs on Kubernetes, Docker containers, serverless functions, or bare metal). Optional Persistence: You can opt to sync this RAM cache to localStorage , sessionStorage , or IndexedDB using TanStack Query Persisters. import React , { useState } from ' react ' ; import { QueryClient , QueryClientProvider , useQuery , useMutation , useQueryClient , } from ' @tanstack/react-query ' ; // 1. Initialize QueryClient (manages the RAM cache) const queryClient = new QueryClient ({ defaultOptions : { queries : { staleTime : 10000 , // Data stays fresh in RAM for 10 seconds }, }, }); // Mock API functions async function fetchPost ( postId ) { const res = await fetch ( `[https://jsonplaceholder.typicode.com/posts/$](https://jsonplaceholder.typicode.com/posts/$){postId}` ); if ( ! res . ok ) throw new Error ( ' Network error ' ); return res . json (); } async function createPost ( newPost ) { const res = await fetch ( ' [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts) ' , { method : ' POST ' , headers : { ' Content-Type ' : ' application/json ' }, body : JSON . stringify ( newPost ), }); return res . json (); } // 2. Query Component (Fetching & Reading Data) function PostViewe

2026-07-24 原文 →
AI 资讯

Why I Built Yet Another JavaScript Date Picker

Every developer has had this moment. You need a date picker, so you start searching. You find one that's perfect... until you realize it requires React. Or Vue. Or jQuery. Or an entire date library just to select a few dates. After trying several solutions, I kept asking myself: Why is such a common UI component often more complicated than it needs to be? So I decided to build my own. Meet RollDate . The Goal I didn't want to create "another date picker." I wanted to build something that I would actually enjoy using in my own projects. The goals were simple: Infinite scroll Zero framework dependencies Simple API Modern UI Mobile-friendly scrolling TypeScript support Easy customization Good documentation Why Scrolling? Most date pickers rely on clicking tiny arrows or dropdowns. On mobile devices, this often feels awkward. I wanted something closer to native mobile pickers, where changing the month or year is just a smooth scroll. That became one of RollDate's core ideas. More Than Just Picking a Date While building the component, I realized different projects need different selection modes. So instead of maintaining separate components, RollDate supports: Single date selection Date range selection Multiple date selection The API stays the same regardless of the mode. new RollDate ( " #date " , { selectType : " range " }); Optional Time Picker Many date pickers force you to install another plugin if you need time selection. I wanted it built in. RollDate supports: 24-hour mode 12-hour AM/PM mode Configurable minute steps Enable it with one option. new RollDate ( " #date " , { enableTime : true }); Dependency-Free One of the main design goals was keeping the library independent. No React. No Vue. No jQuery. No Moment.js. No Day.js. Just plain JavaScript. That means it works almost anywhere: Vanilla JavaScript React Vue Angular Svelte Astro ...or any framework capable of using DOM components. A Better Developer Experience I care a lot about developer experience. That's

2026-07-23 原文 →
AI 资讯

Why Most Web Change Monitors Fail: Solving DOM Mutations and False Positives

If you have ever tried building a website change detection system or visual testing tool, you’ve likely stumbled into the "False Positive Trap." You configure a cron job to monitor a target URL, take snapshots every 15 minutes, and compare them. But within hours, your inbox is flooded with alerts for: Tailwind CSS dynamic hash class mutations (e.g. class="bg-blue-500_a3f9" turning into class="bg-blue-500_b81c" after a deployment) Lazy-loaded images rendering at offset offsets Anti-bot verification scripts altering invisible DOM nodes Hydration mismatches in React/Vue single-page applications At PageWatch.tech , solving these exact edge cases was the primary focus of our engineering roadmap. In this article, I’ll share the 3 core algorithmic fixes we implemented to achieve reliable, noise-free website change monitoring. 🛑 Problem 1: Structural Hash Instability in Modern Frameworks Modern frontend frameworks like Next.js, Nuxt, and Remix insert dynamic build IDs, hydration keys, and inline CSS chunk hashes into the HTML structure. For example, a innocent paragraph tag might look like this today: <p class= "text-gray-700 css-1a2b3c" data-reactroot= "" > Product Price: $99 </p> And like this tomorrow after a routine production deployment: <p class= "text-gray-700 css-9x8y7z" data-reactroot= "" > Product Price: $99 </p> A standard raw string comparison flags this as a critical change even though zero user-facing content changed . The Solution: Attribute Normalization & CSS Class Sanitization Before computing DOM structural hashes, we run a normalize pass that strips generated hashes and framework-specific attributes: import * as htmlparser2 from " htmlparser2 " ; /** * Normalizes dynamic framework attributes and hashed CSS classes * before running DOM diff calculations. */ export function normalizeDOMNode ( node : any ): void { if ( node . attribs ) { // 1. Remove hydration and framework metadata const volatileAttrs = [ " data-reactroot " , " data-reactid " , " data-hydr

2026-07-23 原文 →
AI 资讯

Understanding Monads in TypeScript: A Practical Guide

You have read five blog posts about monads. Each one started with category theory, mentioned burritos, and left you more confused than before. Let's skip all of that. Here is the short version: a monad is a container that supports three operations. You already use two monads every day in TypeScript — Promise and Array . Once you see the pattern, every monad in @oofp/core will feel familiar. The Three Operations Every monad has three things: of(a) — Put a value into the container. map(f) — Transform the value inside, keep the container shape. chain(f) — Transform the value into a new container, then flatten. That's it. If a type supports these three operations and follows a few simple laws, it's a monad. Let's see this with types you already know. Promise — a monad you use daily // of — wrap a value const p = Promise . resolve ( 42 ); // map — transform the inside (then with a plain return) const doubled = p . then (( x ) => x * 2 ); // Promise<number> // chain — transform into a new Promise (then with an async return) const fetched = p . then (( id ) => fetch ( `/api/users/ ${ id } ` )); // Promise<Response> Promise.resolve is of . .then acts as both map and chain — JavaScript conflates them. When your callback returns a plain value, it's map . When it returns a Promise , it's chain . The runtime flattens the nested Promise<Promise<T>> into Promise<T> automatically. Array — another monad hiding in plain sight // of — wrap a value const arr = [ 42 ]; // map — transform each element const doubled = arr . map (( x ) => x * 2 ); // [84] // chain — transform each element into an array, then flatten const expanded = arr . flatMap (( x ) => [ x , x * 10 ]); // [42, 420] Array.of (or just [value] ) is of . .map is map . .flatMap is chain . Same pattern, different container. The insight is: chain is map followed by flatten . That's why it's also called flatMap or bind . You apply a function that returns a new container, then flatten the nested result. Maybe: Eliminating null

2026-07-23 原文 →
AI 资讯

How to Detect Event Loop Freezes in Node.js

You've probably seen this: Kubernetes probes are green, /health returns 200, CPU isn't on fire - and users are timing out. Process is up. Just not doing anything useful. Classic event loop freeze. Something sync and expensive (or a dumb busy loop) grabs the thread, and suddenly timers, HTTP, DB callbacks - all of it waits. Including your health endpoint, because that also needs the loop. monitorEventLoopDelay() is fine for dashboards. It won't yell at you while the process is stuck, and it definitely won't write a log line from outside the frozen loop. That's the part that annoyed me enough to build this. I made @js-ak/watchdog - tiny N-API addon. The monitor runs in C++ on its own thread and writes JSON lines to stderr/file even while the JS event loop is stuck. Your freeze / recovered handlers only run after the loop unblocks. Optional RSS/CPU, optional stack sample. npm install @js-ak/watchdog const watchdog = require("@js-ak/watchdog"); watchdog.on("freeze", (e) => console.log(e.event, e.duration_ms)); watchdog.on("recovered", (e) => console.log("back after", e.duration_ms, "ms")); watchdog.start({ freezeThresholdMs: 1000, logTarget: "stderr", // or "file" | "both" source: "payments-api", }); Real freezes usually aren't while (true) . More like giant JSON.parse, a cursed regex, sync crypto/compress, or some dependency doing sync I/O on a hot path. Stuff you only notice after people complain. Prebuilds for the usual platforms (Node 22+). MIT. Repo: https://github.com/JS-AK/watchdog Curious how other people catch loop stalls in prod - and what you'd actually want in the freeze payload. Roast the API if it's wrong.

2026-07-23 原文 →