惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tor Project blog
B
Blog RSS Feed
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
H
Hackread – Cybersecurity News, Data Breaches, AI and More
罗磊的独立博客
GbyAI
GbyAI
N
Netflix TechBlog - Medium
博客园 - 司徒正美
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
宝玉的分享
宝玉的分享
W
WeLiveSecurity
Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
SecWiki News
SecWiki News
V
Vulnerabilities – Threatpost
Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Register - Security
The Register - Security
Cisco Talos Blog
Cisco Talos Blog
Martin Fowler
Martin Fowler
A
About on SuperTechFans
S
Security @ Cisco Blogs
T
Tenable Blog
C
Check Point Blog
N
News and Events Feed by Topic
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Attack and Defense Labs
Attack and Defense Labs
美团技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Cisco Blogs
P
Palo Alto Networks Blog
V
V2EX
博客园 - 聂微东
Project Zero
Project Zero
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
N
News | PayPal Newsroom
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
小众软件
小众软件
Application and Cybersecurity Blog
Application and Cybersecurity Blog
人人都是产品经理
人人都是产品经理
V2EX - 技术
V2EX - 技术
I
Intezer
L
LINUX DO - 最新话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
⚡ Advanced Path Aliases in Vite — Stop Writing ../../ Forever
PRABHANSH TI · 2026-04-26 · via DEV Community

⚡ Advanced Path Aliases in Vite — Stop Writing ../../ Forever

Clean imports aren't just aesthetics — they're architecture.


Hero Banner


🧭 The Problem Nobody Talks About

You're deep in your Vite project. Files are nested. Logic is split. Components are modular. You're doing everything right — and yet, every single import looks like this:

import Button from "../../../components/ui/Button";
import useAuth from "../../hooks/useAuth";
import { formatDate } from "../../../../utils/dateHelper";

Enter fullscreen mode Exit fullscreen mode

Three dots. Four dots. Five dots.

It's messy, it's fragile, and when you refactor even one folder, everything breaks.

There's a better way. It's called Advanced Path Aliases — and in Vite, it's surprisingly simple to set up.


🎯 What Are Path Aliases?

A path alias is a shorthand you define to replace a long, relative path. Instead of traversing directories with ../../, you map a symbol (like @components) directly to a folder.

Think of it like a bookmark. You define it once, and use it everywhere.

Before Alias After Alias
../../../components/Button @components/Button
../../hooks/useAuth @hooks/useAuth
../../../../utils/format @utils/format

Clean. Predictable. Refactor-proof. ✅


🏗️ Project Structure We're Working With

Before diving into config, here's a clean, real-world Vite + React project structure this guide targets:

my-vite-app/
├── public/
├── src/
│   ├── assets/
│   │   └── logo.svg
│   ├── components/
│   │   ├── ui/
│   │   │   └── Button.tsx
│   │   └── layout/
│   │       └── Navbar.tsx
│   ├── hooks/
│   │   ├── useAuth.ts
│   │   └── useFetch.ts
│   ├── pages/
│   │   ├── Home.tsx
│   │   └── Dashboard.tsx
│   ├── utils/
│   │   ├── formatDate.ts
│   │   └── apiHelper.ts
│   ├── services/
│   │   └── authService.ts
│   ├── store/
│   │   └── useStore.ts
│   ├── types/
│   │   └── index.d.ts
│   ├── App.tsx
│   └── main.tsx
├── index.html
├── vite.config.ts
└── tsconfig.json

Enter fullscreen mode Exit fullscreen mode

💡 Note: This guide uses TypeScript. If you're using plain JavaScript, the concepts are identical — just skip the tsconfig.json parts.


⚙️ Step 1 — Configure Vite (vite.config.ts)

Open your vite.config.ts file and add the resolve.alias section:

// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@components": path.resolve(__dirname, "src/components"),
      "@hooks":      path.resolve(__dirname, "src/hooks"),
      "@utils":      path.resolve(__dirname, "src/utils"),
      "@pages":      path.resolve(__dirname, "src/pages"),
      "@assets":     path.resolve(__dirname, "src/assets"),
      "@services":   path.resolve(__dirname, "src/services"),
      "@store":      path.resolve(__dirname, "src/store"),
      "@types":      path.resolve(__dirname, "src/types"),
    },
  },
});

Enter fullscreen mode Exit fullscreen mode

That's it for Vite. But wait — there's one more piece for TypeScript users.


🧠 Step 2 — Configure TypeScript (tsconfig.json)

Vite knows about your aliases now, but TypeScript doesn't. Your IDE will throw red squiggles everywhere unless you also update tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@hooks/*":      ["src/hooks/*"],
      "@utils/*":      ["src/utils/*"],
      "@pages/*":      ["src/pages/*"],
      "@assets/*":     ["src/assets/*"],
      "@services/*":   ["src/services/*"],
      "@store/*":      ["src/store/*"],
      "@types/*":      ["src/types/*"]
    }
  },
  "include": ["src"]
}

Enter fullscreen mode Exit fullscreen mode

⚠️ Important: The paths in tsconfig.json and the alias in vite.config.ts must always stay in sync. A mismatch means Vite builds fine, but TypeScript screams.


🚀 Step 3 — Install the path Types (If Needed)

If TypeScript complains about __dirname or the path module, install the Node types:

npm install --save-dev @types/node

Enter fullscreen mode Exit fullscreen mode

Then update your tsconfig.json (if not already):

{
  "compilerOptions": {
    "types": ["node"]
  }
}

Enter fullscreen mode Exit fullscreen mode


✨ Step 4 — Using Your Aliases in the Wild

Now for the fun part. Here's what real usage looks like across different file types:

📦 Component Imports

// Before 😩
import Button from "../../../components/ui/Button";
import Navbar from "../../components/layout/Navbar";

// After 🎉
import Button from "@components/ui/Button";
import Navbar from "@components/layout/Navbar";

Enter fullscreen mode Exit fullscreen mode


🪝 Custom Hook Imports

// Before 😩
import useAuth from "../../hooks/useAuth";
import useFetch from "../../../hooks/useFetch";

// After 🎉
import useAuth from "@hooks/useAuth";
import useFetch from "@hooks/useFetch";

Enter fullscreen mode Exit fullscreen mode


🛠️ Utility Imports

// Before 😩
import { formatDate } from "../../../../utils/formatDate";
import { apiHelper } from "../utils/apiHelper";

// After 🎉
import { formatDate } from "@utils/formatDate";
import { apiHelper } from "@utils/apiHelper";

Enter fullscreen mode Exit fullscreen mode


🎨 Asset Imports

// Before 😩
import logo from "../../assets/logo.svg";

// After 🎉
import logo from "@assets/logo.svg";

Enter fullscreen mode Exit fullscreen mode


🧩 A Real Component — Before vs After

Let's look at a realistic Dashboard component:

// ❌ Dashboard.tsx — BEFORE (nightmare imports)
import React from "react";
import Navbar from "../../components/layout/Navbar";
import Button from "../../components/ui/Button";
import useAuth from "../../hooks/useAuth";
import useFetch from "../../hooks/useFetch";
import { formatDate } from "../../utils/formatDate";
import { fetchUser } from "../../services/authService";
import logo from "../../assets/logo.svg";

export default function Dashboard() {
  const { user } = useAuth();
  // ...
}

Enter fullscreen mode Exit fullscreen mode

// ✅ Dashboard.tsx — AFTER (clean & readable)
import React from "react";
import Navbar from "@components/layout/Navbar";
import Button from "@components/ui/Button";
import useAuth from "@hooks/useAuth";
import useFetch from "@hooks/useFetch";
import { formatDate } from "@utils/formatDate";
import { fetchUser } from "@services/authService";
import logo from "@assets/logo.svg";

export default function Dashboard() {
  const { user } = useAuth();
  // ...
}

Enter fullscreen mode Exit fullscreen mode

The logic is identical — but now a new developer can glance at the imports and instantly understand the architecture.


🔄 Advanced Pattern: Barrel Files + Aliases

Take aliases to the next level by combining them with barrel files (index.ts):

// src/components/ui/index.ts  (barrel file)
export { default as Button } from "./Button";
export { default as Input } from "./Input";
export { default as Modal } from "./Modal";
export { default as Card } from "./Card";

Enter fullscreen mode Exit fullscreen mode

Now you can import multiple UI components in a single line:

// 🚀 One import to rule them all
import { Button, Input, Modal, Card } from "@components/ui";

Enter fullscreen mode Exit fullscreen mode

This pattern is especially powerful for design systems and component libraries.


🛡️ Pro Tips & Best Practices

1. Prefix Everything with @

The @ prefix is the community convention. It signals "this is an alias, not a package."

// ✅ Conventional
"@components/*"

// ⚠️ Possible but unusual
"~components/*"
"components/*"  // ← Can conflict with npm packages!

Enter fullscreen mode Exit fullscreen mode


2. Keep Aliases Shallow

Map to top-level folders, not deeply nested ones:

// ✅ Alias to top-level folder
"@components": "src/components"

// ❌ Over-aliasing — gets confusing fast
"@uiButtons": "src/components/ui/buttons"

Enter fullscreen mode Exit fullscreen mode

Let the path after the alias carry the rest of the depth.


3. Document Your Aliases

Add a comment block to vite.config.ts so your team always knows what's available:

resolve: {
  alias: {
    // 📦 UI Components — import { Button } from "@components/ui"
    "@components": path.resolve(__dirname, "src/components"),
    // 🪝 Custom Hooks — import useAuth from "@hooks/useAuth"
    "@hooks":      path.resolve(__dirname, "src/hooks"),
    // 🛠️ Utilities — import { formatDate } from "@utils/formatDate"
    "@utils":      path.resolve(__dirname, "src/utils"),
    // 🌐 API Services — import { authService } from "@services/auth"
    "@services":   path.resolve(__dirname, "src/services"),
  },
},

Enter fullscreen mode Exit fullscreen mode


4. Keep vite.config.ts and tsconfig.json in Sync (Automate It)

Install vite-tsconfig-paths to automatically sync Vite aliases with TypeScript paths — no duplicate config:

npm install --save-dev vite-tsconfig-paths

Enter fullscreen mode Exit fullscreen mode

// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [react(), tsconfigPaths()], // ← just add this!
});

Enter fullscreen mode Exit fullscreen mode

Now you only manage aliases in tsconfig.json. Vite reads them automatically. 🎯


🧪 Testing With Aliases (Vitest / Jest)

Don't forget your test runner! Aliases must also be configured for tests.

Vitest (Native Vite Testing)

Vitest automatically inherits your Vite config — no extra setup needed. ✅

// vitest.config.ts (optional — just extend vite.config.ts)
import { defineConfig } from "vitest/config";
import { alias } from "./vite.config"; // reuse your aliases

Enter fullscreen mode Exit fullscreen mode

Jest

For Jest, add a moduleNameMapper to jest.config.js:

// jest.config.js
module.exports = {
  moduleNameMapper: {
    "^@components/(.*)$": "<rootDir>/src/components/$1",
    "^@hooks/(.*)$":      "<rootDir>/src/hooks/$1",
    "^@utils/(.*)$":      "<rootDir>/src/utils/$1",
    "^@services/(.*)$":   "<rootDir>/src/services/$1",
  },
};

Enter fullscreen mode Exit fullscreen mode


🌍 ESLint Integration

If you use eslint-plugin-import, tell it about your aliases:

npm install --save-dev eslint-import-resolver-typescript

Enter fullscreen mode Exit fullscreen mode

// .eslintrc.json
{
  "settings": {
    "import/resolver": {
      "typescript": {
        "alwaysTryTypes": true,
        "project": "./tsconfig.json"
      }
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Now ESLint respects your aliases for import-order rules. No more false positives. ✅


📊 The Full Config Cheat Sheet

Here's your complete, copy-paste-ready setup:

vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@components": path.resolve(__dirname, "src/components"),
      "@hooks":      path.resolve(__dirname, "src/hooks"),
      "@utils":      path.resolve(__dirname, "src/utils"),
      "@pages":      path.resolve(__dirname, "src/pages"),
      "@assets":     path.resolve(__dirname, "src/assets"),
      "@services":   path.resolve(__dirname, "src/services"),
      "@store":      path.resolve(__dirname, "src/store"),
      "@types":      path.resolve(__dirname, "src/types"),
    },
  },
});

Enter fullscreen mode Exit fullscreen mode

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@hooks/*":      ["src/hooks/*"],
      "@utils/*":      ["src/utils/*"],
      "@pages/*":      ["src/pages/*"],
      "@assets/*":     ["src/assets/*"],
      "@services/*":   ["src/services/*"],
      "@store/*":      ["src/store/*"],
      "@types/*":      ["src/types/*"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode


🏁 Summary

Here's everything covered in one glance:

Step What You Did
1 Added resolve.alias to vite.config.ts
2 Mirrored paths in tsconfig.json for TypeScript
3 Installed @types/node for __dirname support
4 Replaced all ../../ imports with @alias/
5 Combined with barrel files for super clean imports
6 Optionally used vite-tsconfig-paths to DRY up config
7 Configured test runners and ESLint to understand aliases

💬 Final Thoughts

Advanced path aliases are one of those things that feel like a minor developer-experience tweak — until you use them for a week and can never go back.

Your imports become self-documenting. New teammates onboard faster. Refactoring is safer. Your codebase reads like prose instead of a directory traversal.

"Code is read far more often than it is written."
— Robert C. Martin

Set up your aliases today. Future-you will send a thank-you note. 🙏


Found this helpful? Share it with your team — especially the one who still writes ../../../../.