W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
如果你想使用傳統(tǒng)的后端(如 Rails, Laravel)來服務(wù) HTML,但使用 Vite 來服務(wù)其他資源,可以查看在 Awesome Vite 上的已有的后端集成列表。
如果你需要自定義集成,你可以按照本指南的步驟配置它:
1、在你的 Vite 配置中配置入口文件和啟用創(chuàng)建 manifest
:
// vite.config.js
export default defineConfig({
build: {
// 在 outDir 中生成 manifest.json
manifest: true,
rollupOptions: {
// 覆蓋默認(rèn)的 .html 入口
input: '/path/to/main.js'
}
}
})
如果你沒有禁用 module preload 的 polyfill,你還需在你的入口處添加此 polyfill:
// 在你應(yīng)用的入口起始處添加此 polyfill
import 'vite/modulepreload-polyfill'
2、在開發(fā)環(huán)境中,在服務(wù)器的 HTML 模板中注入以下內(nèi)容(用正在運(yùn)行的本地 URL 替換 http://localhost:3000
):
<!-- 如果是在開發(fā)環(huán)境中 -->
<script type="module" src="http://localhost:3000/@vite/client" rel="external nofollow" ></script>
<script type="module" src="http://localhost:3000/main.js" rel="external nofollow" ></script>
還要確保服務(wù)器配置為提供 Vite 工作目錄中的靜態(tài)資源,否則圖片等資源將無法正確加載。
如果你正使用 ?@vitejs/plugin-react-refresh
? 配合 React,你還需要在上述腳本前添加下面這個(gè),因?yàn)椴寮荒苄薷哪阏诜?wù)的 HTML:
<script type="module">
import RefreshRuntime from 'http://localhost:3000/@react-refresh'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
3、在生產(chǎn)環(huán)境中:在運(yùn)行 vite build
之后,一個(gè) manifest.json
文件將與靜態(tài)資源文件一同生成。一個(gè)示例清單文件會像下面這樣:
{
"main.js": {
"file": "assets/main.4889e940.js",
"src": "main.js",
"isEntry": true,
"dynamicImports": ["views/foo.js"],
"css": ["assets/main.b82dbe22.css"],
"assets": ["assets/asset.0ab0f9cd.png"]
},
"views/foo.js": {
"file": "assets/foo.869aea0d.js",
"src": "views/foo.js",
"isDynamicEntry": true,
"imports": ["_shared.83069a53.js"]
},
"_shared.83069a53.js": {
"file": "assets/shared.83069a53.js"
}
}
Record<name, chunk>
? 結(jié)構(gòu)的對象。_
?。你可以使用這個(gè)文件來渲染鏈接或者用散列文件名預(yù)加載指令(注意:這里的語法只是為了解釋,實(shí)際使用時(shí)請你的服務(wù)器模板語言代替):
<!-- 如果是在生產(chǎn)環(huán)境中 -->
<link rel="stylesheet" href="/assets/{{ manifest['main.js'].css }}" />
<script type="module" src="/assets/{{ manifest['main.js'].file }}"></script>
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: