在vite中,有没有办法从index.html更新根html名称

发布于 2025-01-10 13:36:51 字数 101 浏览 0 评论 0原文

我正在尝试将现有项目更新为 vite,但我在文档中读到 Vite 需要一个 index.html 文件来工作。 是否有指定 vite 应该构建的另一个文件名? 就我而言 main.html

I'm trying to update an existing project to vite but i read in the docs Vite expects an index.html file to work from.
Is there anyway to specify another file name from which vite should build?
in my case main.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

-小熊_ 2025-01-17 13:36:51

入口点在 build.rollupOptions.input 中配置:

import { defineConfig } from 'vite'
export default defineConfig({
  ⋮
  build: {
    rollupOptions: {
      input: {
        app: './index.html', // default
      },
    },
  },
})

您可以将其更改为 main.html,如下所示。提供应用程序时,您必须手动导航到 /main.html,但您可以配置 server.open 自动打开该文件:

import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  build: {
    rollupOptions: {
      input: {
        app: './main.html',
      },
    },
  },
  server: {
    open: '/main.html',
  },
})

演示

The entry point is configured in build.rollupOptions.input:

import { defineConfig } from 'vite'
export default defineConfig({
  ⋮
  build: {
    rollupOptions: {
      input: {
        app: './index.html', // default
      },
    },
  },
})

You can change that to main.html, as shown below. When serving the app, you'll have to manually navigate to /main.html, but you could configure server.open to open that file automatically:

import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  build: {
    rollupOptions: {
      input: {
        app: './main.html',
      },
    },
  },
  server: {
    open: '/main.html',
  },
})

demo

一片旧的回忆 2025-01-17 13:36:51

如果您不仅尝试更改根 HTML 页面的名称,还尝试更改其路径,则更改 buildserver 选项会成功没有帮助。例如,如果您想加载 /src/main.html 而不是 /index.html,您可以通过以下地址访问它: http://localhost:3000/src/main.html,但不只是localhost:3000

要从不同的路径提供文件,您需要设置 root在配置文件中。请注意,您还需要定义与此新根相关的其他路径,例如 dist。否则,打包后的文件将输出到/src/dist

/src 加载 HTML 文件的更完整的配置文件如下所示:

import path from "node:path";
import process from "node:process";
import { defineConfig } from "vite";

export default defineConfig({
  server: {
    open: "main.html",
  },
  root: "src",
  publicDir: "../public",
  build: {
    outDir: "../dist"
  },
  resolve: {
    alias: { "/src": path.resolve(process.cwd(), "src") }
  },
});

If you're trying to change not just the name of the root HTML page but also the path to it, changing build or server options won't help. For example, if you want to load <project root>/src/main.html instead of <project root>/index.html, you can access it at http://localhost:3000/src/main.html, but not at simply localhost:3000.

To serve files from a different path, you'll need to set root in the config file. Note that you'll also need to define other paths relative to this new root, like dist. Otherwise, the packaged files will be output to /src/dist.

A more complete config file that loads the HTML file from /src looks like this:

import path from "node:path";
import process from "node:process";
import { defineConfig } from "vite";

export default defineConfig({
  server: {
    open: "main.html",
  },
  root: "src",
  publicDir: "../public",
  build: {
    outDir: "../dist"
  },
  resolve: {
    alias: { "/src": path.resolve(process.cwd(), "src") }
  },
});
执笔绘流年 2025-01-17 13:36:51

使用Vite的transformIndexHtml()来交换HTML内容

可能有更有效的方法,但这种方法可能在特殊用例中有一席之地。

TLDR: 在构建时,我们将index.html 的内容与另一个html 文件的内容交换。

对于我的用例,项目暂时需要静态构建输出的两种变体:1. Vue 应用程序,2. 纯 JS 应用程序。交换 index.html 内容是实现这一目标的最直接的方法,而且稍微复杂一点。

为此,会发生文件转换(使用 fs),并且在项目的一次性构建步骤期间没有问题。如果在另一种情况下,存在常规文件操作(不是一次性),则性能可能会成为问题。

Vite 文档:transformIndexHTML()

1.拥有多个html源文件

至少需要一个index.html;制作你自己的变体。

index.html
index_type1.html
index_type2.html
whatever.html
etc

2.在 vite.config 中创建一个 HTML 替换插件

这里我们直接在 vite 配置中创建一个内联插件。这将使用您选择的任何源文件覆盖index.html。它发生在其他构建步骤之前,基本上相当于您在运行 build 之前手动重命名文件。

vite.config.js

import fs from 'fs/promises'

export default defineConfig({

    plugins: [
      // ...

      {
        name: 'my-plugin-for-index-html-build-replacement',
        transformIndexHtml: {
          enforce: 'pre', // Tells Vite to run this before other processes
          async transform() {

            // Do some logic; whatever you want
            if (env.MY_ENV_VARIABLE == 'myType2') {

              // Grab new HTML content to place into index.html
              return await fs.readFile('./index_type2.html', 'utf8')
            }
          }
        }
      }

      // ...
    ]

})

Use Vite's transformIndexHtml() to swap HTML content

There may be more efficient ways, but this method may have a place in special use cases.

TLDR: At build-time, we swap the content of index.html with that of another html file.

For my use-case, a project temporarily needed two variants of static build outputs: 1. a Vue app, 2. a plain JS app. Swapping index.html content was the most straightforward way to achieve that with a little less complication.

For this a file transformation occurs (using fs), and is fine during the one-time build step of a project. If, in another context, there would be regular file operations (not one-time), performance might be an issue.

Vite docs: transformIndexHTML()

1. Have multiple html source files

At least one index.html is required; make your own variations of it.

index.html
index_type1.html
index_type2.html
whatever.html
etc

2. Make an HTML-replacement plugin in your vite.config

Here we make a plugin inline directly in the vite config. This will overwrite index.html with whatever source file you choose. It happens before other build steps, and is basically the equivalent of you manually renaming files before running build.

vite.config.js

import fs from 'fs/promises'

export default defineConfig({

    plugins: [
      // ...

      {
        name: 'my-plugin-for-index-html-build-replacement',
        transformIndexHtml: {
          enforce: 'pre', // Tells Vite to run this before other processes
          async transform() {

            // Do some logic; whatever you want
            if (env.MY_ENV_VARIABLE == 'myType2') {

              // Grab new HTML content to place into index.html
              return await fs.readFile('./index_type2.html', 'utf8')
            }
          }
        }
      }

      // ...
    ]

})
静若繁花 2025-01-17 13:36:51

对于任何试图提供位于源文件深处的 index.html 文件,但希望开发服务器实际在 / 上提供该文件的人,您可以使用像这样的 vite 插件,在你的 vite.config 中:

export default defineConfig({
  plugins: [
    vue(),
    {
      name: "deep-index",
      configureServer(server) {
        server.middlewares.use(
          (req, res, next) => {
            if (req.url === '/') {
              req.url = '/some/path/to/your/index.html';
            }
            next();
          }
        )
      }
    }
  ]
})

For anyone trying to serve an index.html file that's somewhere deep in your source files, but wants the dev server to actually serve this on /, you can do it with a vite plugin like this, in your vite.config:

export default defineConfig({
  plugins: [
    vue(),
    {
      name: "deep-index",
      configureServer(server) {
        server.middlewares.use(
          (req, res, next) => {
            if (req.url === '/') {
              req.url = '/some/path/to/your/index.html';
            }
            next();
          }
        )
      }
    }
  ]
})

°如果伤别离去 2025-01-17 13:36:51

使用Vite开发应用时,index.html是入口点。您可以通过将 build.rollupOptions.input 设置为 ./main.html 来调整它。

库模式中,入口点是由 build.lib.entry 而不是 index.html 指定。在这种情况下,index.html演示页面仅与开发服务器相关,它将自动转换任何以.html结尾的文件,因此您只需打开http ://localhost:3000/main.html,无需调整配置。在库模式下设置 build.rollupOptions.input 将覆盖 build.lib.entry 指定的入口点,并将演示页面代码捆绑为库的一部分,同时破坏全球 UMD 出口。

When developing an app with Vite, index.html is the entry point. You can adjust it by setting build.rollupOptions.input to ./main.html.

In Library Mode, the entry point is the one specified by build.lib.entry rather than index.html. In this case, the index.html demo page is only relevant for the dev server, which will automatically transform any files ending in .html, so you simply need to open http://localhost:3000/main.html, without adjusting the config. Setting build.rollupOptions.input in library mode will override the entry point specified by build.lib.entry and bundle the demo page code as part of the library, along with breaking the global UMD export.

累赘 2025-01-17 13:36:51

刚刚在 Vite 上遇到了同样的问题并做出了反应。想要提供不同的 html 文件。构建没有问题。只服务。

唯一有效的解决方案是添加插件:

export default defineConfig(({command, mode, isSsrBuild, isPreview}) => {
 return {
   plugins: [..., {
        name: 'index-html-build-replacement', 
        apply: 'serve',  
        async transformIndexHtml(html) {
            switch (mode) {
                case  'firstMode':
                    return await fs.readFile('./index-first.html','utf8'); 
                case 'secondMode':
                    return await fs.readFile('./index-second.html','utf8');
            }

            return html;
        }
     }],
     ...
    }
  }

您可以通过 Vite env 配置设置模式。

https://vitejs.dev/guide/env-and-mode

Just had the same problem with Vite and react. Wanted to serve different html files. No problem with the build. Only serve.

The only solution that worked was to add the plugin:

export default defineConfig(({command, mode, isSsrBuild, isPreview}) => {
 return {
   plugins: [..., {
        name: 'index-html-build-replacement', 
        apply: 'serve',  
        async transformIndexHtml(html) {
            switch (mode) {
                case  'firstMode':
                    return await fs.readFile('./index-first.html','utf8'); 
                case 'secondMode':
                    return await fs.readFile('./index-second.html','utf8');
            }

            return html;
        }
     }],
     ...
    }
  }

You can set the mode via the Vite env configuration.

https://vitejs.dev/guide/env-and-mode

一身仙ぐ女味 2025-01-17 13:36:51

这是 server.open 属性,这是来自他们的网站,ChatGPT 再次失败:)

export default defineConfig({
  server: {
    open: '/docs/index.html'
  }
})

It's the server.open property, this is from their site, ChatGPT has failed once again:)

export default defineConfig({
  server: {
    open: '/docs/index.html'
  }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文