Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: avoid execSync on openBrowser #12510

Merged
merged 1 commit into from Mar 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 7 additions & 10 deletions packages/vite/src/node/server/openBrowser.ts
Expand Up @@ -9,7 +9,7 @@
*/

import { join } from 'node:path'
import { execSync } from 'node:child_process'
import { exec } from 'node:child_process'
import open from 'open'
import spawn from 'cross-spawn'
import colors from 'picocolors'
Expand All @@ -18,25 +18,23 @@ import { VITE_PACKAGE_DIR } from '../constants'

/**
* Reads the BROWSER environment variable and decides what to do with it.
* Returns true if it opened a browser or ran a node.js script, otherwise false.
*/
export function openBrowser(
url: string,
opt: string | true,
logger: Logger,
): boolean {
): void {
// The browser executable to open.
// See https://github.com/sindresorhus/open#app for documentation.
const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''
if (browser.toLowerCase().endsWith('.js')) {
return executeNodeScript(browser, url, logger)
executeNodeScript(browser, url, logger)
} else if (browser.toLowerCase() !== 'none') {
const browserArgs = process.env.BROWSER_ARGS
? process.env.BROWSER_ARGS.split(' ')
: []
return startBrowserProcess(browser, browserArgs, url)
startBrowserProcess(browser, browserArgs, url)
}
return false
}

function executeNodeScript(scriptPath: string, url: string, logger: Logger) {
Expand Down Expand Up @@ -70,7 +68,7 @@ const supportedChromiumBrowsers = [
'Chromium',
]

function startBrowserProcess(
async function startBrowserProcess(
browser: string | undefined,
browserArgs: string[],
url: string,
Expand All @@ -88,20 +86,19 @@ function startBrowserProcess(

if (shouldTryOpenChromeWithAppleScript) {
try {
const ps = execSync('ps cax').toString()
const ps = await exec('ps cax').toString()
const openedBrowser =
preferredOSXBrowser && ps.includes(preferredOSXBrowser)
? preferredOSXBrowser
: supportedChromiumBrowsers.find((b) => ps.includes(b))
if (openedBrowser) {
// Try our best to reuse existing tab with AppleScript
execSync(
await exec(
`osascript openChrome.applescript "${encodeURI(
url,
)}" "${openedBrowser}"`,
{
cwd: join(VITE_PACKAGE_DIR, 'bin'),
stdio: 'ignore',
},
)
return true
Expand Down