我正在使用 Vite 和 Vue Router 构建 Vue.js 应用程序。我有一个图像 WEBP,单击该图像时,应该在新选项卡中打开该图像的 PNG 版本。当我使用
npm run dev
在本地运行应用程序时,效果很好,但是当我为生产构建时,当我尝试在新选项卡中打开图像时,会收到 404 错误。
<div id="art-container">
<a id="art-link" href="#" target="_blank" title="Loading...">
<img id="art-image" class="w-auto max-h-96 mb-4 rounded-lg shadow-lg" alt="Artwork" loading="eager" />
</a>
<!-- rest of the code -->
</div>
artDisplay.js
let artData = [
{
image: "/img/art/example.webp",
fullRes: "/img/art/example.png",
artist: "Art from <a class='text-lg font-semibold text-blue-500' href='https://example.com' target='_blank'>example</a>",
description: "Cool description",
hoverText: "Hover text",
}
];
let currentArtIndex = Math.floor(Math.random() * artData.length);
export function updateArtDisplay() {
document.getElementById("next-art-button").addEventListener("click", nextArt);
const art = artData[currentArtIndex];
document.getElementById("art-image").src = art.image;
document.getElementById("art-link").href = art.fullRes;
document.getElementById("artist-name").innerHTML = art.artist;
document.getElementById("art-description").innerHTML = art.description;
document.getElementById("art-link").title = art.hoverText;
}
function nextArt() {
currentArtIndex = (currentArtIndex + 1) % artData.length;
updateArtDisplay();
}
路由器.js
import { createRouter, createWebHistory } from 'vue-router';
// Import pages here
import index from './views/index.vue';
import notFound from './views/notFound.vue';
const routes = [
// system pages
{ path: '/', component: index },
// catch-all route
{ path: '/:pathMatch(.*)*', component: notFound },
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
vite.config.js
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import { join, parse, resolve } from "path";
const entryPoints = getEntryPoints("index.html");
// convert to route paths
const dynamicRoutes = Object.keys(entryPoints).map(key => `/${key}`);
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
],
alias: {
"~": __dirname,
},
build: {
outDir: 'dist',
base: '/',
minify: 'esbuild',
sourcemap: 'true',
rollupOptions: {
input: entryPoints,
},
},
})
function getEntryPoints(...paths) {
const entries = paths.map(parse).map(entry => {
const { dir, base, name, ext } = entry;
const key = join(dir, name);
const path = resolve(__dirname, dir, base);
return [key, path];
});
const config = Object.fromEntries(entries);
return config;
}
完整代码托管于 GitLab
不要使用
image
文件夹中的子文件夹;所有文件都应该像 /img/example.png
而不是 /img/subfolder/example.png
。
经过几个小时的研究这个问题,我找到了解决办法。
将文件位置从
/img/art/example.png
更改为 /img/example.png
似乎可以解决问题。此重命名如何解决图像加载问题?没有线索。我检查过这不是 Vue-router 和 VitePWA 的问题。这可能是我的特定配置或 Vue 本身的问题。