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

无需Node.js与create-react-app实现React组件导入导出方案问询

Great question—building a minimal React setup without CRA makes total sense for large enterprise systems where you need tight control over your bundle and file structure, especially when deploying to CDNs and integrating with SSO/internal services. Let’s break down exactly how to get import/export working, plus a clean structure that fits your needs:

1. Enable ES Modules in the Browser

First, the browser needs to recognize your scripts as ES modules (which support import/export). Add the type="module" attribute to your entry script in index.html:

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Enterprise React App</title>
  <!-- React/ReactDOM CDNs (or install via npm for production) -->
  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  <!-- React Router CDN (if using) -->
  <script src="https://unpkg.com/react-router-dom@6/dist/react-router-dom.production.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <!-- Entry script marked as ES module -->
  <script type="module" src="/src/index.js"></script>
</body>
</html>
2. Minimal Project Structure (≤10 Files)

Here’s a clean, SOLID-aligned structure that avoids bloat:

your-app/
├── public/
│   └── index.html
└── src/
    ├── index.js          # Entry point (auth + app render)
    ├── App.js            # Root layout component
    ├── routes.js         # React Router configuration
    └── components/
        ├── Header.js     # Auth-aware header
        └── Dashboard.js  # Primary content component

You can merge smaller utility components into a single file (e.g., components/UI.js) to keep total files under 10 if needed.

3. Implement Component Import/Export

With ES modules enabled, you can use standard import/export syntax just like in CRA:

Example: components/Header.js

// Import React (if using JSX)
import React from 'react';

// Export a component (named export for flexibility)
export const Header = ({ user }) => {
  return (
    <header>
      <h1>Enterprise System</h1>
      <span>Welcome, {user.name}</span>
    </header>
  );
};

Example: App.js

import React from 'react';
// Import the Header component
import { Header } from './components/Header';
// Import routing components
import { Routes, Route } from 'react-router-dom';
import { Dashboard } from './components/Dashboard';

export const App = ({ user }) => {
  return (
    <div className="app-container">
      <Header user={user} />
      <Routes>
        <Route path="/" element={<Dashboard />} />
        {/* Add other routes as needed */}
      </Routes>
    </div>
  );
};
4. Handle JSX Transpilation (Browser Doesn’t Support JSX Natively)

To use JSX without CRA, you have two main options:

Option A: Babel Standalone (Quick Prototyping)

Add Babel’s CDN script to index.html and mark your JSX scripts as text/babel (with data-type="module"):

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- Update your entry script -->
<script type="text/babel" data-type="module" src="/src/index.js"></script>

Note: This is great for development but not recommended for production (it adds runtime overhead).

Option B: Minimal Build Tool (Production-Grade)

For production, use a lightweight tool like Vite or Rollup to bundle your code (transpile JSX, tree-shake unused code, and output optimized files for CDN):

  • Vite: Initialize with npm init vite@latest my-app -- --template react, then delete unnecessary files (like src/App.css, src/index.css, public/vite.svg). Your vite.config.js can be as simple as:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      base: '/your-cdn-base-path/', // Configure for CDN deployment
      build: {
        outDir: 'dist', // Output directory for CDN upload
        minify: 'terser', // Optimize for production
      },
    });
    
    Run npm run build to generate a tiny, optimized bundle ready for CDN.
5. Integrate SSO/CDN Data Fetching

In your entry index.js, handle SSO authentication or CDN data retrieval before rendering the app:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { App } from './App';

// Fetch user data from internal CDN/SSO endpoint
const loadApp = async () => {
  try {
    const userRes = await fetch('/internal-cdn/user-session');
    const user = await userRes.json();

    // Render app with authenticated user data
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <BrowserRouter>
        <App user={user} />
      </BrowserRouter>
    );
  } catch (err) {
    // Handle auth failure (redirect to SSO, show error)
    console.error('Auth failed:', err);
    window.location.href = '/sso-login';
  }
};

// Initialize app
loadApp();

This setup keeps your codebase lean, follows SOLID principles (single-responsibility components), and works seamlessly with CDN deployment and enterprise auth flows.

内容的提问来源于stack exchange,提问作者A.J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:53:12