Skip to content

Commit

Permalink
feat: log qrcode in preview server (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Jul 10, 2023
1 parent 4cc7d72 commit 2fc6cb5
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/lazy-laws-exercise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vite-plugin-qrcode': minor
---

Log qrcode in preview server for Vite 4.3.0 and above
2 changes: 1 addition & 1 deletion packages/playground/basic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
"preview": "vite preview"
},
"devDependencies": {
"vite": "^4.3.9",
Expand Down
13 changes: 11 additions & 2 deletions packages/vite-plugin-qrcode/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Plugin, ViteDevServer } from 'vite';
import type { Plugin, PreviewServerForHook, ViteDevServer } from 'vite';
import qr from 'qrcode-terminal';

export function qrcode(options: PluginOptions = {}): Plugin {
Expand All @@ -19,11 +19,20 @@ export function qrcode(options: PluginOptions = {}): Plugin {
// eslint-disable-next-line prefer-rest-params
return _listen.apply(this, arguments);
};
},
configurePreviewServer(server) {
// Preview server has no restarts, so we can hook directly
// The `resolvedUrls` only exist in Vite >=4.3.0, so add a guard to prevent unnecessary hook
if ('resolvedUrls' in server) {
server.httpServer?.on('listening', () => {
setTimeout(() => logQrcode(server, options), 0);
});
}
}
};
}

function logQrcode(server: ViteDevServer, options: PluginOptions) {
function logQrcode(server: ViteDevServer | PreviewServerForHook, options: PluginOptions) {
let networkUrls = server.resolvedUrls?.network;

if (!networkUrls) return;
Expand Down

0 comments on commit 2fc6cb5

Please sign in to comment.