如何使用 Vite 和 React 处理单独的入口点

问题描述 投票:0回答:1

目前我有一个 Vite 项目,构建了一个 React 应用程序:

Vite 配置如下:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

// Vite config
export default defineConfig({
  plugins: [
    react(),
  ],
});

它从 /src/main.tsx 入口点获取所有代码,然后生成如下输出:

dist/assets/index-[hash].js
dist/assets/index-[hash].css
dist/index.html

我没有在任何地方定义index.html,事实上它是自动生成的,并且包括重要的

<script type="module" crossorigin src="/assets/index-CSOHzRbG.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Lja8sGTP.css">

现在我想要这样的输出:

dist/assets/index-[hash].js
dist/assets/index-[hash].css
dist/index.html
dist/my-other-script.js

基于:

...
src/main.tsx
src/my-other-script.ts

我尝试了chatgpt建议的添加构建汇总信息,如下所示:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import { resolve } from 'path';

// Vite config
export default defineConfig({
  plugins: [
    react(),
  ],
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'src/main.tsx'), // React app entry point
        contentScript: resolve(__dirname, 'src/my-other-script.ts'), // Content script entry point
      },
      output: {
        entryFileNames: (chunkInfo) =>
          chunkInfo.name === 'contentScript' ? 'content-script.js' : 'assets/[name].[hash].js',
        chunkFileNames: 'assets/[name].[hash].js',  // Ensure chunk files also have hashed names
        assetFileNames: 'assets/[name].[hash][extname]', // Hash assets (CSS, images)
      },
    },
    outDir: 'dist', // Output directory
    assetsDir: 'assets', // Folder for assets like CSS, images
  },
});

但是,虽然这适用于所有脚本。

.html
文件不再生成,这是新的输出:

dist/assets/index-[hash].js
dist/assets/index-[hash].css
dist/my-other-script.js

您知道如何保留默认捆绑(包括完整的

index.html
生成),同时还具有单独的流捆绑和输出
src/my-other-script.ts

谢谢!

javascript reactjs vite
1个回答
0
投票

在 Grok 的帮助下,我找到了这个解决方案:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import { resolve } from 'path';

// Vite config
export default defineConfig({
  plugins: [
    react(),
  ],
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'), // This should point to your index.html if it exists
        app: resolve(__dirname, 'src/main.tsx'), // React app entry point
        contentScript: resolve(__dirname, 'src/content-script/index.ts'), // Content script entry point
      },
      output: {
        entryFileNames: (chunkInfo) => 
          chunkInfo.name === 'contentScript' ? 'content-script.js' : 'assets/[name]-[hash].js',
        chunkFileNames: 'assets/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash][extname]',
      },
      preserveEntrySignatures: 'strict', // This helps maintain the signature of the entry
    },
    outDir: 'dist', // Output directory
    assetsDir: 'assets', // Folder for assets like CSS, images
  },
});

看来我需要在此过程中单独包含项目根目录下的index.html。

© www.soinside.com 2019 - 2024. All rights reserved.