三种方案解决Vue项目打包后dist中的index.html用浏览器无法直接打开的问题

24,817 阅读2分钟

index.html为什么打不开?

Vue打包后生成的dist文件中的index.html,双击在浏览器中打开后发现一片空白,打开控制台有很多报错:“Failed to load resource: net::ERR_FILE_NOT_FOUND”。

这是因为dist文件是需要放在服务器上运行的,资源默认放在根目录下。打开index.html可以发现,css和js文件的引用使用的是绝对路径,例如:<link href=/css/chunk-00d5eabc.f78fa75d.css rel=prefetch>,对本地磁盘来说,/指向磁盘根目录,所以找不到引用的文件。

有以下解决方案:1. 使用http-server创建一个服务器来访问资源;2. 将index.html中资源引用的绝对路径改为相对路径;3.还可以手写一个简单的node服务器。

使用http-server

http-server是一个基于命令行的http服务器。使用方法很简单:

  1. 安装:npm install http-server -g
  2. 进入dist文件夹:cd dist
  3. 执行命令:http-server

大功告成!可以打开浏览器在localhost:8080中查看了。

将绝对路径改为相对路径

可以选择手动将index.html中所有引用资源的地方全部改成相对路径,如:<link href=./css/chunk-00d5eabc.f78fa75d.css rel=prefetch><link href=css/chunk-00d5eabc.f78fa75d.css rel=prefetch>

当然,更优雅的做法是修改项目的publicPath:

// vue.config.js
module.exports = {
    // ...
    publicPath: './'
    // ...
};

此时再运行npm run build打包后,打开dist/index.html发现所有资源的引用形式已经变为相对路径:<link href=css/chunk-00d5eabc.f78fa75d.css rel=prefetch>,此时可以双击index.html在浏览器中正常访问了!

手写一个简单的node服务器

在dist同级目录中新增文件server.js:

// server.js
// 1. 引入接下来要用到的node内置模块
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');

// 2. 利用path解析当前目录,然后拼接dist目录,使得服务器当前的根目录变为dist
const root = path.join(path.resolve(process.argv[2] || '.'), 'dist');

// 3. 创建http服务器
const server = http.createServer((request, response) => {

  // 4. 解析请求url获取文件路径
  const pathname = url.parse(request.url).pathname;
  const filepath = path.join(root, pathname);
  
  // 5. 使用fs文件系统模块读取index.html文件并返回给前端
  fs.stat(filepath, (err, stats) => {
    if (!err && stats.isFile()) {
      // 响应头设为200
      response.writeHead(200);
      // 创建一个读写流管道,将index.html文件内容写入response并返回
      fs.createReadStream(filepath).pipe(response);
    } else {
      // 请求路径不对时返回404
      response.writeHead(404);
      response.end('404 Not Found');
    }
  });
});

// 6. 服务器监听8080端口
server.listen(8080);

命令行定位到server.js同级目录中执行node server.js,此时在浏览器中可以访问http://localhost:8080/index.html查看效果。