首页 > 解决方案 > @vue/cli build dist/ 文件夹在托管为子目录时不呈现

问题描述

我正在制作一个简单的 2 页网站@vue/cli / vue version 3.5.5

到目前为止一切顺利,当我在本地运行网站npm run serve然后使用npm run build.

当我将 dist/ 文件夹中的文件添加到主机的根目录并访问页面上的生产环境时http://www.my-website.com,页面呈现并正常运行。

但是,我想将应用程序托管在子目录中,但这会弄乱路由,因为 index.html 没有呈现。访问时http://www.my-website.com/dist: index.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

但是现在,当我在子目录中托管我的项目时,我在控制台中得到一个空白的 index.html 页面和错误消息。如果我将它托管在根目录中,该项目运行良好

标签: vue.jsbuildvue-clivue-cli-3

解决方案


即使您没有在分发文件夹下创建特定文件夹,也可能发生此错误。在这种情况下,请参阅以下解决方案:

默认情况下,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: ''
};

它将确保 index.html 将如上所示生成。


推荐阅读