利用 Node.js 自定义部署 Vditor 的 CDN 地址
# 后端控制台 这里注意要和前端版本一致 不然几率报错
npm i vditor@3.11.0
// 后端 nodejs
const express = require("express");
const app = express();
const port = 3000;
// 假设Vditor资源位于项目目录下的node_modules/vditor/dist目录
app.use("/vditor", express.static("node_modules/vditor"));
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
# 前端控制台 这里注意要和后端版本一致 不然几率报错
npm i vditor@3.11.0
// 前端
const vditor = new Vditor("vditor", {
// ...其他配置
cdn: "/vditor",
});
下面是凑字数的废话
在现代 Web 开发中,Markdown 编辑器被广泛应用于各种内容创作场景,Vditor 作为一款功能强大且开源的浏览器端 Markdown 编辑器备受开发者青睐。通常我们会使用公共 CDN 来引入 Vditor 资源,但在某些特定场景下,比如网络环境受限、追求更稳定的资源加载、保障数据隐私安全等,将 Vditor 的 CDN 资源部署到自己的服务器上是更好的选择。借助 Node.js,我们可以轻松实现这一目标,接下来就详细介绍部署过程。
前期准备
在开始部署之前,需要确保系统中已经安装了 Node.js 和 npm(Node.js 包管理器)。打开终端,输入 node -v
和 npm -v
命令,若能显示出版本号,说明已经正确安装;若未安装,前往Node.js 官方网站 下载对应操作系统的安装包进行安装。
下载 Vditor 资源
通过 npm 下载
- 打开终端,创建一个新的项目目录用于存放 Vditor 资源,例如
mkdir vditor-self-hosted
,并进入该目录cd vditor-self-hosted
。 - 初始化项目,生成
package.json
文件,执行npm init -y
。 - 安装 Vditor,运行
npm install vditor
命令。安装完成后,Vditor 的资源会存放在node_modules/vditor
目录下,其中dist
目录包含了我们需要的核心文件,如样式表和 JavaScript 脚本。
从 GitHub 仓库下载
- 访问Vditor 的 GitHub 仓库 。
- 点击页面上的 “Code” 按钮,选择 “Download ZIP” 选项,下载项目的压缩包。
- 解压压缩包,在解压后的文件夹中找到
dist
目录,其中的文件就是我们后续部署需要用到的资源。
配置 Node.js 服务器
我们可以使用 Node.js 的一些 Web 框架,如 Express,来搭建一个简单的服务器,用于提供 Vditor 资源的访问服务。
安装 Express
在之前创建的项目目录(vditor-self-hosted
)下,执行 npm install express
命令安装 Express 框架。
上述代码中,首先引入 Express 框架并创建应用实例,然后指定服务器监听的端口为 3000。接着,使用 express.static
中间件,将 node_modules/vditor/dist
目录设置为静态资源目录,并通过 /vditor
路径进行访问。最后,启动服务器,在终端输出服务器运行的地址。
如果希望对路径进行更个性化的设置,或者 Vditor 资源存放在其他位置,可以修改 express.static
方法中的路径参数。例如,若将 Vditor 资源手动复制到了项目目录下的 my-vditor
文件夹,代码可修改为:
const express = require("express");
const app = express();
const port = 3000;
app.use("/custom-vditor", express.static("my-vditor"));
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
这样,就可以通过 http://localhost:3000/custom-vditor
来访问部署的 Vditor 资源。
使用部署的 Vditor 资源
在 HTML 文件中,将原本引用公共 CDN 的路径替换为我们自己服务器的路径。例如,原本引用公共 CDN 的代码为:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor@latest/dist/index.css" />
<script src="https://cdn.jsdelivr.net/npm/vditor@latest/dist/index.min.js"></script>
替换为我们部署的资源路径后,代码变为:
<link rel="stylesheet" href="http://localhost:3000/vditor/index.css" />
<script src="http://localhost:3000/vditor/index.min.js"></script>
通过以上步骤,我们成功利用 Node.js 部署了 Vditor 的 CDN 地址。这种方式不仅可以让我们在特定环境下稳定使用 Vditor,还能根据实际需求对资源进行管理和优化。随着项目的发展,如果需要对 Vditor 进行版本更新,只需重新下载资源并替换服务器上的文件,同时注意更新 HTML 文件中的引用路径即可。