如何用Vite创建多HTML文件?页面专属脚本配置求助
Vite多页面配置解决方案
你当前的问题出在全局entry配置只作用于默认页面,没有为about页面指定专属的入口脚本。要让每个页面的TS文件自动编译并插入对应HTML,需要在pages数组的每个页面对象中单独配置entry:
修改后的Vite配置代码如下:
import { defineConfig } from "vite"; import { createHtmlPlugin } from "vite-plugin-html"; export default defineConfig({ root: "src", plugins: [ createHtmlPlugin({ minify: true, // 移除全局entry,改为在pages中单独配置 pages: [ { filename: "index", template: "index.html", entry: "js/home.ts" // 对应index页面的入口脚本 }, { filename: "about", template: "about.html", entry: "js/about.ts" // 对应about页面的入口脚本 }, ], }), ], build: { outDir: "../dist", emptyOutDir: true, }, });
关键修改说明
- 移除全局
entry配置,避免默认只作用于单个页面 - 给
pages数组内的每个页面对象添加entry字段,指定该页面对应的TS入口文件路径 - 配置完成后,Vite会自动编译每个页面的入口脚本,并将编译后的资源自动插入到对应HTML中
全局CSS补充方案
如果希望tachyons.css在所有页面生效,除了在每个页面的入口TS中导入外,也可以通过createHtmlPlugin的inject选项全局注入:
createHtmlPlugin({ minify: true, inject: { // 全局注入CSS到所有页面 tags: [ { tag: 'link', attrs: { rel: 'stylesheet', href: '/css/tachyons.css' // 假设tachyons.css放在src/css目录下 } } ] }, pages: [/* ... 页面配置 ... */] })
这样就无需在每个TS文件中重复导入全局CSS。
内容的提问来源于stack exchange,提问作者izaac mendes
相关产品推荐
相关产品推荐

