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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Forbes - Security
Forbes - Security
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
W
WeLiveSecurity
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News and Events Feed by Topic
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
PCI Perspectives
PCI Perspectives
Martin Fowler
Martin Fowler
T
The Exploit Database - CXSecurity.com
F
Full Disclosure
WordPress大学
WordPress大学
S
Security Affairs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
SegmentFault 最新的问题
P
Privacy International News Feed
IT之家
IT之家
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Check Point Blog
美团技术团队
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
MyScale Blog
MyScale Blog
H
Help Net Security
宝玉的分享
宝玉的分享
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
I
Intezer
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AI
AI
I
InfoQ
N
News | PayPal Newsroom
TaoSecurity Blog
TaoSecurity Blog

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
MDX Layout Best Practices: Import Order and Component Placement
Mustafa ERBA · 2026-05-17 · via DEV Community

Mustafa ERBAY

While developing my bilingual technical blog, I became very familiar with MDX files. Initially, my main concern was getting everything to work quickly. However, over time, I realized how critical the import order and component placement within MDX files truly are. As content grew more complex and the number of components increased, both readability and maintenance costs began to be significantly affected.

This problem isn't unique to my blog; it's a common challenge in many projects that use MDX with modern static site generators like Astro. After a while, each code block within an MDX file can turn into a small island of chaos. To tackle this, I developed some best practices, which I want to share here.

The Importance of Order in MDX Files: Why Bother?

MDX files are a fantastic tool because they combine the flexibility of Markdown with the power of React (or another JSX-compatible framework) components. However, this power, when used without control, can quickly turn into a headache. In my experience, especially with frequently updated content like blog posts, the organization within MDX files became a critical factor for overall project health.

When you have to scroll up and down for minutes just to understand where a component comes from or what it does, maintaining that file becomes impossible. I realized that I needed to apply the same meticulousness I use when organizing systemd unit files or PostgreSQL configurations to MDX files. Otherwise, a small component error could prolong compilation times or lead to unexpected rendering issues.

ℹ️ Experienced Problem

While integrating a new reporting component into an MDX-based help document for a production ERP, I inadvertently created a build loop due to a randomly added import at the top of the file. The error message wasn't very descriptive, and it took me about 4 hours to find the root cause. Situations like these demonstrate that order isn't just about aesthetics; it directly impacts operational costs.

Import Order: Dependency Hierarchy and Readability

The order of import declarations in MDX files is crucial for file readability and dependency management. On my blog and in other projects, I follow a specific hierarchy. This hierarchy allows me to quickly understand where a component or module originates.

My general rule is as follows:

  1. Standard Library/Node.js Modules: If any, these come first.
  2. Third-Party Libraries: External libraries defined in the project's package.json file.
  3. Local Components (General): General components from the project's components directory or root directory, used in many different places.
  4. Local Components (Specific): Components closer to the current MDX file's directory, used only for a particular section or topic.

This ordering allows me to instantly see how "distant" or "specific" a dependency is when I look at the import block. This way, in case of an error, I can more easily guess the source of the problem (is it my own code, a third-party library, or a layout component?).

---
title: "MDX Import Order"
---
import { Fragment } from 'react'; // React behaves like a standard library
import { marked } from 'marked';   // Third-party library (e.g., for syntax highlighting)
import Callout from '../../../components/mdx/Callout.astro'; // General, reusable component
import FeatureCard from '../components/FeatureCard.astro'; // Local, specific to this topic
import type { Post } from '../types'; // Type imports, usually at the bottom

Enter fullscreen mode Exit fullscreen mode

In the example above, you can see that imports are logically grouped, enhancing readability. This discipline proved very useful in a side project where I manage 20-30 different MDX files.

Global vs. Local Component Definitions

MDX's power also allows you to define components directly within the file. However, this feature can lead to chaos if not used carefully. My approach is to draw clear boundaries here.

When should I define local (inline) components?

  • Very simple, single-use, small UI elements that won't be used anywhere else.
  • Structures specific only to that MDX file, without complex state or logic. For example, a small highlight within text or a special icon.

When should I import from an external file?

  • Highly reusable components that will be used in multiple MDX files or sections (e.g., Callout, CodeBlock, ImageWithCaption).
  • Components involving complex logic, state management, or API calls. Keeping these in a separate .astro, .jsx, or .tsx file improves testability and maintainability.
  • Components that need to integrate with global styles or themes.

⚠️ Inline Component Pitfalls

While inline components might seem practical at first, they can force you to traverse all MDX files for minor changes. One day, in a side project, I needed to change the text of a small Disclaimer component that I had copied into 15 different MDX files. This meant manual changes in 15 files, which was highly prone to error. Since then, I always import such components externally.

Component Placement: Where to Put What?

Just as important as import order is where we place components within the MDX file. I generally see three main scenarios:

  1. Layout or Wrapper Components: These typically wrap all MDX content or provide a general layout. In Astro, this can also be managed with the layout frontmatter property. If I'm using a custom wrapper component directly within MDX, I usually place it at the very beginning of the content.
  2. In-Content Components: Components used within the flow of the blog post, rendered alongside the text. For example, a code block, a graphic, or a Callout component. These should be placed in the relevant section of the content.
  3. Helper Components: Sometimes, we might add components to the end of an MDX file that are not directly related to the main content but need to be displayed at the bottom of the page (e.g., "related posts" or "comments" section). Similarly, some small script tags can also go here.

💡 My Approach on My Own Blog

On my own blog, I frequently use Callout components. I always import them at the top of the file and use them as ... wherever needed. This ensures a consistent look and enriches the content. Additionally, my main layout file, which determines the overall layout of the article, uses the slot structure to place the MDX content correctly.

Layout Components and MDX Relationship

Frameworks like Astro offer very powerful mechanisms for combining MDX files with layout components. This ensures that MDX files only contain content, while general page layout and elements like headers/footers are managed from a central location.

In my practice, I use a specific BlogPostLayout.astro component for each blog post. This component takes data like title and description from the frontmatter to configure the page's <head> tag, and renders the main menu and footer. The content from the MDX file is then placed into the slot of this layout component.

---
layout: ../../layouts/BlogPostLayout.astro
title: "MDX Layout Best Practices: Import Order and Component Placement"
description: "I'm sharing my experiences gained while organizing MDX files."
category: "technology"
tags: ["MDX", "Astro"]
---

This is the main content of my blog post. The layout component will wrap this content.

Enter fullscreen mode Exit fullscreen mode

A simple structure for the BlogPostLayout.astro file might look like this:

---
import BaseLayout from './BaseLayout.astro'; // General, base layout for all pages
const { frontmatter } = Astro.props;
---

  <article class="prose dark:prose-invert max-w-none">
    <h1>{frontmatter.title}</h1>
    <p class="text-gray-500 text-sm">Publish Date: {frontmatter.publishDate}</p>
    <slot /> {/* MDX content is rendered here */}
  </article>

Enter fullscreen mode Exit fullscreen mode

This approach keeps MDX files clean and focused solely on content. Working on a single file for layout changes is much more efficient than making manual edits across hundreds of MDX files. In a documentation system I developed for an internal banking platform, this separation ensured that hundreds of technical documents had a consistent