前端架构演进:从单体到微前端

前端架构演进:从单体到微前端

前端架构的发展历程

第一阶段:单体应用(Mono Repo)

复制代码
├── src/
│   ├── components/
│   ├── pages/
│   ├── services/
│   ├── utils/
│   └── styles/
└── index.html

特点:

  • 代码集中管理
  • 部署简单
  • 适合小型项目

第二阶段:组件化架构

复制代码
├── src/
│   ├── components/
│   │   ├── Button/
│   │   ├── Card/
│   │   └── Modal/
│   ├── containers/
│   ├── pages/
│   └── store/
└── index.html

特点:

  • 代码复用性高
  • 关注点分离
  • 便于团队协作

第三阶段:微前端架构

复制代码
├── apps/
│   ├── shell/
│   ├── home/
│   ├── profile/
│   └── checkout/
└── packages/
    └── ui-components/

特点:

  • 独立开发和部署
  • 技术栈无关
  • 高扩展性

微前端架构模式

模式一:基座模式

javascript 复制代码
// shell/src/App.js
import { registerMicroApps, start } from 'qiankun';

registerMicroApps([
  {
    name: 'home',
    entry: '//localhost:8081',
    container: '#container',
    activeRule: '/home'
  },
  {
    name: 'profile',
    entry: '//localhost:8082',
    container: '#container',
    activeRule: '/profile'
  }
]);

start();

模式二:路由分发模式

javascript 复制代码
// router/index.js
const routes = [
  {
    path: '/home',
    microApp: 'home'
  },
  {
    path: '/profile',
    microApp: 'profile'
  }
];

模式三:构建时集成

javascript 复制代码
// webpack.config.js
module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'shell',
      remotes: {
        home: 'home@http://localhost:8081/remoteEntry.js'
      }
    })
  ]
};

状态管理方案对比

方案一:Redux

javascript 复制代码
// store.js
import { createStore } from 'redux';

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    default:
      return state;
  }
};

const store = createStore(reducer, { count: 0 });

方案二:Zustand

javascript 复制代码
// store.js
import create from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 }))
}));

方案三:Jotai

javascript 复制代码
// store.js
import { atom, useAtom } from 'jotai';

const countAtom = atom(0);

function Counter() {
  const [count, setCount] = useAtom(countAtom);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

组件设计原则

单一职责原则

javascript 复制代码
// ❌ 违反:一个组件处理多个职责
function UserProfile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchUser().then(data => {
      setUser(data);
      setLoading(false);
    });
  }, []);
  
  if (loading) return <Spinner />;
  
  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

// ✅ 正确:职责分离
function useUser() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchUser().then(data => {
      setUser(data);
      setLoading(false);
    });
  }, []);
  
  return { user, loading };
}

function UserProfile() {
  const { user, loading } = useUser();
  
  if (loading) return <Spinner />;
  
  return (
    <UserCard user={user} />
  );
}

可组合性

javascript 复制代码
function withAuth(Component) {
  return function AuthenticatedComponent(props) {
    const { isLoggedIn } = useAuth();
    
    if (!isLoggedIn) {
      return <Redirect to="/login" />;
    }
    
    return <Component {...props} />;
  };
}

const ProtectedPage = withAuth(MyPage);

代码组织策略

按功能组织

复制代码
src/
├── features/
│   ├── auth/
│   │   ├── components/
│   │   ├── hooks/
│   │   ├── services/
│   │   └── index.js
│   └── dashboard/
│       ├── components/
│       ├── hooks/
│       └── index.js
└── shared/
    ├── components/
    ├── utils/
    └── styles/

按类型组织

复制代码
src/
├── components/
│   ├── Button/
│   └── Card/
├── hooks/
│   ├── useAuth.js
│   └── useFetch.js
├── services/
│   └── api.js
└── pages/
    └── Home.js

性能优化策略

代码分割

javascript 复制代码
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
    </Suspense>
  );
}

懒加载

javascript 复制代码
const Image = ({ src, alt }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  
  return (
    <div>
      {!isLoaded && <Placeholder />}
      <img
        src={src}
        alt={alt}
        loading="lazy"
        onLoad={() => setIsLoaded(true)}
      />
    </div>
  );
};

总结

前端架构设计是一个持续演进的过程,需要根据项目规模和团队情况选择合适的方案。关键在于:

  1. 保持代码的可维护性和可扩展性
  2. 遵循单一职责和高内聚低耦合原则
  3. 合理利用设计模式和最佳实践
  4. 持续关注性能优化和用户体验

选择适合当前项目的架构方案,才能让团队高效协作,构建出优秀的产品。

相关推荐
外域速览7 分钟前
2026世界动力电池大会今日宜宾启幕:固态电池从实验室走向量产,IEC 国际标准终结概念乱象
大数据·人工智能·microsoft
金智维科技官方13 分钟前
财务核算如何提效?这三条核心链路正在加速自动化
运维·人工智能·ai·自动化·财务·智能体
Csvn13 分钟前
第 16 章 多智能体 Multi-Agent
人工智能·aigc·agent
xsd2024111817 分钟前
从BEV感知透视3D检测
人工智能
Python大数据分析@23 分钟前
推荐一个非常好用的画图skill-Archify
人工智能
小刘快学习42 分钟前
一把钥匙开所有门:企业AI网关的统一身份与权限治理
大数据·人工智能
熊猫钓鱼>_>1 小时前
MiniMax 深度观察:不是又一个大模型,是AI生产效率的范式革新
人工智能·ai·自然语言处理·媒体·benchmark·minimax·行业
TechWayfarer1 小时前
Cloudflare 9·15新政倒计时:用IP风险画像识别AI爬虫,防止误伤Googlebot
网络·人工智能·爬虫·python·tcp/ip·网络安全
Anhty1 小时前
2026九月最新变声器测评:iOS安卓双端适配,低延迟运行更稳定
android·人工智能·功能测试·ios·智能手机
DisonTangor1 小时前
【腾讯混元雪耻归来】 Hy4 preview:770B 参数 MoE 旗舰模型,1M 上下文全面开源
人工智能·算法·开源·aigc·腾讯云·腾讯云ai代码助手