Skip to content

Commit

Permalink
fix: same link
Browse files Browse the repository at this point in the history
  • Loading branch information
xuany committed May 22, 2024
1 parent 035eb4d commit cfdfcaf
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 35 deletions.
25 changes: 15 additions & 10 deletions playground/index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="app"></div>
<a href="/__inspect/#/module?id=./main.ts&index=2" target="_blank" style="text-decoration: none; margin-top:10px; display: block;">visit /__inspect/ to inspect the intermediate state</a>
<script type="module" src="./main.ts"></script>
</body>
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="app"></div>
<a
href="/__inspect/#/module?id=./main.ts&index=2"
target="_blank"
style="text-decoration: none; margin-top: 10px; display: block"
>visit /__inspect/ to inspect the intermediate state</a
>
<script type="module" src="./main.ts"></script>
</body>
</html>
5 changes: 3 additions & 2 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"private": true,
"scripts": {
"dev": "nodemon -w '../src/**/*.ts' -e .ts -x vite",
"build:webpack": "webpack --watch --config webpack.config.js",
"build:webpack": "webpack --config webpack.config.js",
"build:vite": "vite build"
},
"dependencies": {
Expand All @@ -12,7 +12,8 @@
"babel-loader": "^9.1.3",
"html-webpack-plugin": "^5.6.0",
"ts-loader": "^9.5.1",
"typescript": "^5.3.2"
"typescript": "^5.3.2",
"unplugin-prefetch-dns": "^0.1.3"
},
"devDependencies": {
"vite": "^5.0.4",
Expand Down
14 changes: 5 additions & 9 deletions playground/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const HtmlWebpackPlugin = require('html-webpack-plugin')
const DnsPrefetchPlugin = require('../dist/webpack.cjs').default

module.exports = {
mode: 'production',
mode: 'development',
entry: './main.ts',
output: {
path: path.resolve(__dirname, 'dist'),
Expand All @@ -16,18 +16,14 @@ module.exports = {
include: path.resolve(__dirname),
exclude: /node_modules/i,
loader: require.resolve('babel-loader'),
// options: {
// presets: [],
// babelrc: false,
// configFile: false,
// cacheDirectory: true,
// cacheCompression: false,
// },
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [DnsPrefetchPlugin(), new HtmlWebpackPlugin({})],
plugins: [
new HtmlWebpackPlugin({}),
DnsPrefetchPlugin(),
],
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 24 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import urlRegex from 'url-regex'
import type { Compiler } from 'webpack'
import type { Options } from './types'

const PLUGIN_NAME = 'unplugin-dns-prefetch:webpack'
const PLUGIN_NAME = 'unplugin-prefetch-dns:webpack'

const URL_REG = /https:\/\/[^/]*/i

export const unpluginFactory: UnpluginFactory<Options | undefined> = () => {
const htmlTemplatePaths = [] as string[][]
const urls = new Set<string>()
const URL_REG = /https:\/\/[^/]*/i

function process(dir: string, filePaths: string[]) {
htmlTemplatePaths.length = 0
urls.clear()
return Promise.all(filePaths.map(async (fileName) => {
const content = await fs.readFile(`${dir}/${fileName}`, 'utf-8')

Expand All @@ -29,21 +32,28 @@ export const unpluginFactory: UnpluginFactory<Options | undefined> = () => {
if (matched)
urls.add(matched[0])
})

})).then(() => {
// insert url
if (urls.size === 0)
return

// insert url
const links = [...urls].map(url => `<link rel="dns-prefetch" href="${url}">`).join('\n ')
let links = [...urls].map(url => `<link rel="dns-prefetch" href="${url}">`)
for (const [path, content] of htmlTemplatePaths) {
const newHTML = content.replace(/(<head[^>]*>)/, (_, head) => `${head}\n ${links}`)
await fs.writeFile(path, newHTML, 'utf-8')
const headS = content.indexOf('<head>')
const headE = content.indexOf('</head>')
const headStr = content.slice(headS - 1, headE + 1)
links = links.filter((link) => {
return !headStr.includes(link)
})
if (!links.length)
return
const newHTML = content.replace(/(<head[^>]*>)/, (_, head) => `${head}\n ${links.join('\n ')}`)
fs.writeFile(path, newHTML, 'utf-8')
}
}))
})
}

return {
name: 'unplugin-prefetch-dns',
name: PLUGIN_NAME,
enforce: 'post',
vite: {
writeBundle: {
Expand All @@ -55,10 +65,10 @@ export const unpluginFactory: UnpluginFactory<Options | undefined> = () => {
},
},
webpack(compiler: Compiler) {
compiler.hooks.done.tapAsync({ name: PLUGIN_NAME }, async (stats) => {
const path = stats.compilation.outputOptions.path
const fileNames = stats.compilation.assetsInfo.keys()
await process(path!, [...fileNames])
compiler.hooks.afterEmit.tapAsync({ name: PLUGIN_NAME }, async (stats) => {
const path = stats.outputOptions.path
const fileNames = stats.assetsInfo.keys()
process(path!, [...fileNames])
})
},
}
Expand Down

0 comments on commit cfdfcaf

Please sign in to comment.