为什么 create-react-app 可以每次都打开同一个页面,而 vue-cli 不可以?

Facebook 的官方 React 脚手架 create-react-app ( https://github.com/facebookin... ),运行 npm start 的时候,如果页面已经打开,就不会再开一个新页面了,而是直接跳到已打开页面去,体验很不错。

而 vue-cli 是每次都打开一个新的页面。

请问有谁知道 create-react-app 这是怎么实现的吗?

阅读 4.8k
2 个回答

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

PS:刚看到上面已经回答了:

当你使用 npm start 的时候,实际上使用的是 rreact-scripts start,则这部分的代码在node_modules/react-scripts/scripts/start.js,这里面调用了 openBrowser这个方法:

    // 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);
    });

这个函数来自于 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: 原理,上面回答已经说了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题