我正在用@vue/cli / vue version 3.5.5
制作一个简单的 2 页网站。
到目前为止一切顺利,当我使用npm run serve
在本地运行网站,然后使用npm run build
创建我的 dist/文件夹时。
当我将 dist/文件夹中的文件添加到我的托管根目录并访问生产环境时http://www.my-website.com
页面会正常呈现和运行。
但是我想在子目录中托管应用程序,但这会弄乱路由,因为索引.html不会呈现。 访问http://www.my-website.com/dist
时:索引.html返回为空白,并在控制台中显示错误消息:
app.a1183de6.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
chunk-vendors.ff22d1fb.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
about.ad763791.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
app.a1183de6.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
提供背景信息,包括您已经尝试过的内容
我花了几个小时搜索,最常见的是创建一个vue.config.js
文件并将根路径更改为子目录
module.exports = {
baseUrl: process.env.NODE_ENV === 'production'
? '/dist/'
: '/'
}
我也试过这个,但它不起作用:
// module.exports = {
// publicPath:' /dist/ '
// }
我按照指示将vue.config.js
文件放在项目文件夹的根目录中,但似乎在npm run build
上被忽略
了描述预期结果和实际结果:
我想在子目录中渲染我的 vue-app,例如:
http://www.website.com/dist
但是现在,当我在子目录中托管项目时,我在控制台中收到一个空白的索引.html页面和错误消息。 如果我在根目录中托管它,该项目运行良好
nvm...它现在正在工作....
在项目根目录中创建:vue.config.js
添加了以下内容:
module.exports = {
publicPath: '/dist/'
}
运行npm run build
后,js 和 css 文件的路径现在包括子目录
即使您没有在分发文件夹下创建特定文件夹,也可能发生此错误。在这种情况下,请参阅以下解决方案:
默认情况下,index.html 是使用如下所示的链接标记生成的:
<link href=/js/chunk-vendors.2f2d9c51.js rel=preload as=script>
在开头添加一个不需要的斜杠,以便尝试在错误的路径中搜索 js 和 css 文件。 您实际上需要如下所示的它:
<link href=js/chunk-vendors.2f2d9c51.js rel=preload as=script>
没有前导斜杠字符。
前导正斜杠"/"表示路径是根目录的绝对路径,而不是当前目录。
为了修复它,只需将一个vue.config.js文件添加到你的 vue 项目中,其中包含以下代码:
module.exports = {
publicPath: ''
};
它将确保索引.html将如上所示生成。