Skip to content

Commit

Permalink
perf: avoid execSync on openBrowser (#12510)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev authored Mar 21, 2023
1 parent aecb9b1 commit a2af2f0
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions packages/vite/src/node/server/openBrowser.ts
Original file line number Diff line number Diff line change
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

0 comments on commit a2af2f0

Please sign in to comment.