鍍金池/ 問答/HTML/ 為什么 create-react-app 可以每次都打開同一個(gè)頁面,而 vue-

為什么 create-react-app 可以每次都打開同一個(gè)頁面,而 vue-cli 不可以?

Facebook 的官方 React 腳手架 create-react-app ( https://github.com/facebookin... ),運(yùn)行 npm start 的時(shí)候,如果頁面已經(jīng)打開,就不會(huì)再開一個(gè)新頁面了,而是直接跳到已打開頁面去,體驗(yàn)很不錯(cuò)。

而 vue-cli 是每次都打開一個(gè)新的頁面。

請問有誰知道 create-react-app 這是怎么實(shí)現(xiàn)的嗎?

回答
編輯回答
哚蕾咪

create-react-app使用的是react-dev-utils里的openBrowser方法。而且 reuse tab 這一功能只在 mac 上生效。而非 mac 下的,默認(rèn)用的是跟 vue-cli 一樣的 opn(跨平臺(tái))。

openBrowser 源碼

2018年5月20日 06:07
編輯回答
舊酒館

如果你使用create-react-app,查看 node_modules/react-dev-utils/openBrowser.js 代碼即可。

PS:剛看到上面已經(jīng)回答了:

當(dāng)你使用 npm start 的時(shí)候,實(shí)際上使用的是 rreact-scripts start,則這部分的代碼在node_modules/react-scripts/scripts/start.js,這里面調(diào)用了 openBrowser這個(gè)方法:

    // Launch WebpackDevServer.
    devServer.listen(port, HOST, err => {
      if (err) {
        return console.log(err);
      }
      if (isInteractive) {
        clearConsole();
      }
      console.log(chalk.cyan('Starting the development server...\n'));
      openBrowser(urls.localUrlForBrowser);
    });

這個(gè)函數(shù)來自于 react-dev-utils/,依賴地址:node_modules/react-dev-utils/openBrowser.js

  // If we're on OS X, the user hasn't specifically
  // requested a different browser, we can try opening
  // Chrome with AppleScript. This lets us reuse an
  // existing tab when possible instead of creating a new one.
  const shouldTryOpenChromeWithAppleScript =
    process.platform === 'darwin' &&
    (typeof browser !== 'string' || browser === OSX_CHROME);

  if (shouldTryOpenChromeWithAppleScript) {
    try {
      // Try our best to reuse existing tab
      // on OS X Google Chrome with AppleScript
      execSync('ps cax | grep "Google Chrome"');
      execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
        cwd: __dirname,
        stdio: 'ignore',
      });
      return true;
    } catch (err) {
      // Ignore errors.
    }
  }

PS: 原理,上面回答已經(jīng)說了

2017年9月14日 03:24