Lighthouse CLI 扫描本地 HTML 文件为啥报“无法访问页面”?

极客倩利 阅读 6

我用 Lighthouse CLI 想分析一个本地的静态 HTML 页面,执行命令 lighthouse file:///path/to/index.html 后却提示 “Unable to access the page. Please verify the URL…”。明明文件路径是对的,浏览器里直接打开也能正常显示。

是不是不能直接扫本地 file 协议?那我该怎么用 CLI 分析离线页面?试过开个本地服务器再扫 localhost,但想省掉这一步。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Test Page</title>
</head>
<body>
  <h1>Hello Lighthouse</h1>
  <p>Just a simple static page.</p>
</body>
</html>
我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
东方婷婷
我之前也碰到过这个问题。Lighthouse CLI 确实对 file 协议的支持有点儿问题,即使文件路径是对的,它有时候还是抓瞎。解决办法就是你提到的开一个本地服务器,不过你不想多这一步也可以理解。

不过有个小技巧可以试试:你可以使用 http-server 或者 live-server 这样的工具快速启动一个本地服务器。比如,如果你安装了 http-server,只要在你的项目目录下运行 http-server,它就会自动启动一个服务器,默认监听 8080 端口。然后你就可以用 lighthouse http://localhost:8080 来扫描了。

如果你不想安装额外的工具,也可以考虑使用 Node.js 自带的 http 模块来启动一个简单的服务器。这里有一个示例代码:

const http = require('http');
const fs = require('fs');
const path = require('path');

http.createServer(function (req, res) {
const filePath = '.' + req.url;
const extname = String(path.extname(filePath)).toLowerCase();
let contentType = 'text/html';

switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}

fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
});
}
else {
res.writeHead(500);
res.end(Sorry, check with the site admin for error: ${error.code} ..n);
res.end();
}
}
else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});

}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');


把这个文件保存为 server.js,然后在终端运行 node server.js,同样可以启动一个本地服务器。这样你就能用 Lighthouse 扫描你的页面了。希望这个方法对你有帮助!
点赞
2026-03-23 21:13