背景
「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战」
作为一名前端开发,有时候需要查看项目代码打包后的真实效果。这时候就需要把打包后的文件,弄到本地的服务器上看看效果。我们最常用的方法就是:使用 Node.js 起一个本地服务器,挂载对应的资源
快速配置一个本地服务器,在根目录创建service.js文件
const http = require("http");
const fs = require("fs");
const express = require("express");
const app = express();
app.use(express.static("./dist"));
app.get("/", function (req, res) {
res.sendFile(__dirname, "/index.html");
});
http.createServer(app).listen(7777, function () {
console.log("Https server listening on port " + 7777);
});
启动服务器
node service.js
效果图
思考
启动本地服务器需要额外的代码配置,比较繁琐,这样的重复工作比较低效率。那这个问题如何解决呢?在 VScode 的官网插件 Top 榜单,发现了Live Server插件,该是一个提供了本地服务器能力的插件,能很好地解决这个问题。
快速配置 Live Server
预备条件
- 使用 VScode
- 安装 Live Server 插件
配置步骤
- VScode
setting.json中配置 Vue/React 打包后文件夹dist为服务器的根目录
"liveServer.settings.root": "/dist",
- 找到
dist目录下的index.html,鼠标右键,选择Open with Live Server,就可以以dist目录为根路径,index.html为页面入口启动本地服务器
PS: 若无法打开,请再次确认目录是否正确
本地服务器设置https协议
- 本地创建 CA 证书和 TLS 证书
npm install mkcert -g
# create a certificate authority
mkcert create-ca
# 命令执行完毕,得到ca.key / ca.crt 文件
# create a tls certificate
mkcert create-cert
# 命令执行完毕,得到cert.key / cert.crt 文件
- 安装生成的 CA 证书
ca.cert,Windows 安装证书步骤 - VScode setting.json 配置
"liveServer.settings.https": {
"enable": true, //set it true to enable the feature.
"cert": "D:\\workSpace\\my-vue-app\\cert.crt", //full path
"key": "D:\\workSpace\\my-vue-app\\cert.key", //full path
"passphrase": ""
},
- 重新启动
LiveServe,即可看到本地 HTTPS 服务器生效了
代码的配置HTTPS也很简单
const https = require("https");
const fs = require("fs");
const express = require("express");
const app = express();
const PORT = 7777;
app.use(express.static("./dist"));
app.get("/", function (req, res) {
res.sendFile(__dirname, "/index.html");
});
// 配置tls协议的证和秘钥
const options = {
key: fs.readFileSync("./cret.key"),
cert: fs.readFileSync("./cret.crt"),
};
https.createServer(options, app).listen(PORT, function () {
console.log("Https server listening on port " + PORT);
});
更多LiveServe配置,例如:Proxy 接口代理配置等等,可以参考官方文档
总结
在Vscode简单地配置好Live Server插件,能让我们快速地拥有一个本地 HTTPS 服务器,帮助我们的工作提效。插件还有很多能力,等待大家来探索
最后
如果觉得文章对你有帮助,不要忘记点个赞!
好好学习不会差,我是 970,大家一起进步!