怎么做陪玩app,先来了解DNS预解析的使用
怎么做陪玩app,先来了解DNS预解析的使用
在项目中我们可能会遇到一个问题,就是很多地方使用到了第三方的外链,比如图片、CSS、JS,由于项目是团队开发,有时候还不知道项目哪些地方引用了第三方的外链,所以我们不可能通过 link 标签的形式将这些第三方外链一个个引入并开启 DNS 预解析。
这个时候需要写一个插件去帮我们查找项目中所有的引入的第三方外链,在网上搜了下找不到满足需求的插件,只能自己写了,由于 Vite 项目使用 rollup 打包的,而 Vue-cli 项目用的是 webpack,不同的工具打包机制是不一样的,所以不采用插件的形式,在运行打包命令的时候运行一段代码,去修改打包的结果,这里以 Vite 工程为例:
// package.json "scripts": { "build": "vite bulid && node ./scripts/dns-prefetch.js" }
具体的代码如下,简单来说就是,遍历打包后的 dist 目录中的所有 HTML、JS、CSS 文件,将所有外链的域名存起来,然后在 dist 目录下 index.html 文件的 head 标签中依次插入 link 标签,同时开启 DNS 预解析:
// dns-prefetch.js const fs = require('fs') const path = require('path') const { parse } = require('node-html-parser') const { glob } = require('glob') const urlRegex = require('url-regex') // 获取外部链接的正则表达式 const urlPattern = /(https?:\/\/[^/]*)/i const urls = new Set() // 遍历dist目录中的所有HTML、JS、CSS文件 async function searchDomin() { const files = await glob('dist/**/*.{html,css,js}') for (const file of files) { const source = fs.readFileSync(file, 'utf-8') const matches = source.match(urlRegex({ strict: true })) if (matches) { matches.forEach((url) => { const match = url.match(urlPattern) if (match && match[1]) { urls.add(match[1]) } }) } } } // 在index.html文件<head>标签中插入link标签 async function insertLinks() { const files = await glob('dist/**/*.html') const links = [...urls].map((url) => `<link rel="dns-prefetch" href="${url}" />`).join('\n') for (const file of files) { const html = fs.readFileSync(file, 'utf-8') const root = parse(html) const head = root.querySelector('head') head.insertAdjacentHTML('afterbegin', links) fs.writeFileSync(file, root.toString()) } } async function main() { await searchDomin() await insertLinks() } main()
以上就是怎么做陪玩app,先来了解DNS预解析的使用, 更多内容欢迎关注之后的文章