对于我的多页应用程序,我不能将 html Assets 导入指向根目录,因为我需要在子文件夹中上传我的项目。
使用 -
module.exports = defineConfig({
base: "./",
});
解决了根页面的这个问题,但导致嵌套页面的错误导入。
例子
- assets
- index.html
- nested
- nested.html
index.html 的导入将指向 ./assets,这是正确的。
nested.html 的导入也将指向 ./assets,这是不正确的。它需要指向 ../assets。
最佳答案
您可以设置一个别名
来指向assets
文件夹:
alias: {
"@": resolve(__dirname, './assets'),
},
根据您的树示例,使用以下多页示例 vite.config.js
,您可以导入 Assets
来自组件:import logo from '@/logo.png'
(假设文件夹 assets
中有一个 logo.png
文件)
import vue from "@vitejs/plugin-vue";
import { join, parse, resolve } from "path";
export default {
base: '',
root: './',
plugins: [vue()],
alias: {
"@": resolve(__dirname, './assets'), // will resolve to `/assets/`
},
build: {
rollupOptions: {
input: entryPoints(
"index.html",
"nested/nested.html",
"foo/index.html",
"foo/bar/index.html",
),
},
},
};
function entryPoints(...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;
}
嵌套 FooBar
组件的示例代码:
<template>
<img alt="Vue logo" :src="logo" />
<Nav/>
<h1>Foo Bar</h1>
</template>
<script setup>
import Nav from "~/components/Nav.vue";
import logo from '@/logo.png'
import "@/style/style.scss"
</script>
关于rollupjs - 使用 vite 的多页面应用程序的基本 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70198637/