在本地环境的前端项目中配置https
w2xi Lv2

前言

这几天在看一个大佬的博客,看到这个标题 Local HTTPS 的时候,一个大大的问号浮现在我的脑海中,本地还能https?

于是带着好奇跟着文章的步骤一步步来,发现果然可行,然后就觉得自己知识面又加宽了💪。

其实很久以前我就听说过HTTPS的鼎鼎大名,知道它是HTTP协议的安全版本,但是也仅此而已,可以说对HTTPS的了解一无所知吧😢。

于是今天在网上找了一篇文章稍微了解了一下,知道了它大概的原理,然后就觉得自己知识面又加宽了💪。

逃~)🏃

使用 mkcert

因为我使用的是Windows,所以 Install for Windows,其它的操作系统找到对应方式安装即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 安装 mkcert 
$ choco install mkcert

# 为本地环境安装 CA
$ mkcert -install
Created a new local CA 💥
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊

# 切换到你的项目根目录
$ cd /path/to/your_project_root_path

# 生成证书
$ mkcert w2xi.tech '*.w2xi.tech' w2xi.test localhost 127.0.0.1 ::1
Created a new certificate valid for the following names 📜
- "w2xi.tech"
- "*.w2xi.tech"
- "w2xi.test"
- "localhost"
- "127.0.0.1"
- "::1"

Reminder: X.509 wildcards only go one level deep, so this won't match a.b.w2xi.tech ℹ️

The certificate is at "./w2xi.tech+5.pem" and the key at "./w2xi.tech+5-key.pem" ✅

It will expire on 19 June 2024 🗓

最终成功安装了 CA,并生成 certkey 两个文件,文件目录如下,接下来的步骤会用到这两个文件。

1
2
3
4
{
key: './w2xi.tech+5-key.pem',
cert: './w2xi.tech+5.pem',
}

在 Webpack 中配置 https

我测试的项目是基于 vue-cli4 的,所以直接在 vue.config.js 配置即可。

1
2
3
4
5
6
7
8
9
10
const fs = require('fs')

module.exports = {
//...
devServer: {
https: true,
key: fs.readFileSync('./w2xi.tech+5-key.pem'),
cert: fs.readFileSync('./w2xi.tech+5.pem'),
}
}

启动项目,即可运行在 https 环境中了🚀。

最后

阅读大佬的博客,深刻地感受到了自己的渺小。

路还很长,但贵在坚持。

加油,打工人。

参考

https://shanyue.tech/frontend-engineering/local-https.html

https://github.com/FiloSottile/mkcert

https://juejin.cn/post/6925296374628122632

https://www.cnblogs.com/you-men/p/13955113.html

  • Post title:在本地环境的前端项目中配置https
  • Post author:w2xi
  • Create time:2022-03-19 22:12:17
  • Post link:https://w2xi.github.io/2022/03/19/在本地环境的前端项目中配置https/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.