You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用共享组件开发两个独立React应用的最佳方案?附示例

Great question! When you're building two separate React apps (like your App1 and App2, each with their own index.html and app1.js/app2.js) that need to share components, there are a few solid approaches depending on your team's workflow, scalability needs, and how tightly you want the apps and components to be coupled. Let's break down the best options with practical examples:

1. Monorepo with a Local Shared Component Library

This is my go-to recommendation for teams working on multiple apps that need close coordination on shared components. Tools like Lerna, Nx, or even plain pnpm/Yarn Workspaces make this straightforward.

How to set it up:

  • Structure your project root with a packages folder containing three subfolders:
    • shared-components: Your reusable React components (e.g., Button.jsx, Card.jsx) with their own package.json
    • app1: Your first React app (with index.html and app1.js)
    • app2: Your second React app (with index.html and app2.js)
  • Configure your monorepo tool to link the shared-components package to both apps locally.

Example usage in App1 (app1.js):

import React from 'react';
import ReactDOM from 'react-dom/client';
import { SharedButton } from '@your-org/shared-components'; // Import from the local package

function App1() {
  return (
    <div>
      <h1>Welcome to App 1</h1>
      <SharedButton label="Click Me (Shared Component)" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App1 />);

Pros:

  • Instant hot-reloading when you update shared components (no need to publish or reinstall)
  • All apps use the exact same version of components, avoiding inconsistencies
  • Easy to test changes across both apps simultaneously

Cons:

  • Requires initial setup of the monorepo tool (minor learning curve for beginners)
  • Ties the apps to a single repository (which might not be ideal if apps are managed by separate teams)

2. Publish a Private/Public NPM Package

If your apps are in separate repositories or need to be shared across teams, packaging your components as an NPM package is the standard approach. You can use a private registry (like Verdaccio) for internal teams, or publish to the public NPM registry if the components are open-source.

How to set it up:

  1. Create a standalone repository for your shared components
  2. Use a bundler like Rollup or Vite to package the components into a format compatible with React (ES modules, CommonJS)
  3. Publish the package to your registry (e.g., npm publish for public, or your private registry command)
  4. Install the package in both App1 and App2:
    npm install @your-org/shared-components
    

Example usage in App2 (app2.js):

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Card } from '@your-org/shared-components';

function App2() {
  return (
    <div>
      <h1>Welcome to App 2</h1>
      <Card title="Shared Card Component" content="This card is reused across both apps!" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App2 />);

Pros:

  • Standardized way to share components across any number of apps/repositories
  • Versioning control lets you roll back changes or support older app versions if needed
  • Works seamlessly with CI/CD pipelines

Cons:

  • Requires publishing a new version every time you update components (slightly slower iteration than monorepo)
  • For local testing, you’ll need to use npm link or yarn link to connect your local component code to the apps

3. Git Submodules (Quick & Dirty for Small Teams)

If you want to avoid monorepos or NPM packages, Git submodules let you embed your shared components repository directly into App1 and App2.

How to set it up:

  • Create a separate Git repo for your shared components
  • Add the submodule to App1:
    git submodule add https://your-shared-components-repo.git src/shared-components
    
  • Do the same for App2

Example usage in App1 (app1.js):

import React from 'react';
import ReactDOM from 'react-dom/client';
import { SharedButton } from './src/shared-components/Button'; // Import directly from submodule

function App1() {
  return (
    <div>
      <h1>App 1 with Submodule</h1>
      <SharedButton label="From Git Submodule" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App1 />);

Pros:

  • No extra tools or packaging required
  • Direct access to component source code

Cons:

  • Git submodules can be tricky to manage (updating, cloning, and checking out versions is non-intuitive)
  • Apps might end up using different versions of the components if submodules aren’t synced regularly

4. Dynamic Component Loading (Micro-Frontend Style)

If your apps are independently deployed and you want to update shared components without redeploying the apps, you can bundle components as UMD modules and load them dynamically from a CDN or static host.

Example usage in App1 (app1.js):

import React, { lazy, Suspense } from 'react';
import ReactDOM from 'react-dom/client';

// Lazy-load the shared component from a CDN
const SharedButton = lazy(() => import('https://your-cdn.com/shared-components/Button.umd.js'));

function App1() {
  return (
    <div>
      <h1>App 1 with Dynamic Components</h1>
      <Suspense fallback={<div>Loading component...</div>}>
        <SharedButton label="Dynamically Loaded" />
      </Suspense>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App1 />);

Pros:

  • Update shared components independently without redeploying App1 or App2
  • Ideal for large-scale micro-frontend architectures

Cons:

  • Adds network latency (components load after the initial app)
  • Debugging dynamic components can be more complex
  • Requires setting up a CDN or static hosting for your component bundles

Final Recommendation

  • If you own both apps and work in the same team: Go with the Monorepo approach for the smoothest development experience.
  • If apps are in separate repos or shared across teams: Use an NPM package for versioned, standardized sharing.
  • If you need a quick solution without extra tooling: Git submodules work, but be prepared for some Git headaches.
  • If you need independent component updates: Try dynamic loading with a CDN.

内容的提问来源于stack exchange,提问作者Rohit Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:43:43