1. Introduction

Hi, I’m Wakawa. Welcome to follow my official account Ruochuan Vision. Recently, I organized an activity to read the source code together. If you are interested, you can join in with ruoChuan12 on wechat.

If you want to learn source code, Underscore, Lodash, Vuex, Sentry, Axios, Redux, KOA, VUUE-Devtools, Vuex4, Koa-Compose, vue 3.2 are highly recommended Release, VUE-this, CREate-Vue, toy Vite and more than 10 source code articles.

This article warehouse open-analysis, ask a star^_^

Recently, we organized a source code reading activity to learn source code together. So we search for all kinds of worth learning, and the code line is not many source.

We often see this scenario: every time I start a project service, my computer opens the browser for me. Of course, you may not have encountered it, but there may be a need. The source code is about 300 lines, the core source code is less than 100 lines. It is closely related to our work and is worth learning from.

Did you write that 99% of people don’t know vue-DevTools can open component files directly? The principle of this article is revealed, is similar to the principle of this article.

Reading this article, you will learn:

1.The computer actually obediently helped me to open the browser principle and source code implementation2.Learn to use node.js's powerful Child_process module3.Learn to debug source code4., etc.Copy the code

2. Use

2.1 Use in Webpack

devServer.open

Tell dev-server to open the browser after the server starts. Set it to true to open your default browser.

webpack.config.js

module.exports = {
  //...
  devServer: {
    open: true,}};Copy the code

Usage via the CLI:

npx webpack serve --open
Copy the code

To disable:

npx webpack serve --no-open
Copy the code

Most of these days are not configured directly with WebPack. Instead, they use scaffolding. So let’s take a look at how the open browser function is used in the familiar scaffolding.

2.2 Using vue-CLI

npx @vue/cli create vue3-project
# Vue3-project folder in my open-analysis project
# npm i -g yarn
# YARN Serve does not automatically open the browser
yarn serve
# --open will automatically open the browser
yarn serve --open
Copy the code

2.3 Use in create-react-app

npx create-react-app react-project
# react-project folder in my open-analysis project
# npm i -g yarn
The browser is automatically opened by default
yarn start
Copy the code

The terminal I use is Windows Terminal, recommend my previous article: use ohmyzsh to build Windows, Ubuntu, MAC system efficient terminal command-line tool, use good.

Webpack, VuE-CLI, and creation-react-app all feature the same use of Open.

The code location to reference the open separation is:

  • webpack-dev-server
  • vue-cli
  • create-react-app

Then we will learn the open principle and source code.

Principle 3.

In the NPM king @SindResorhus’ Open README document, the English description lists several reasons why it is used.

Why recommendedopen

Active maintenance. Application parameters are supported. Safer because it uses spawn instead ofexec. Fixed most node-Open issues. Includes the latest XDG-open scripts for Linux. Support WSL paths for Windows applications.Copy the code

In a word, the principle of open is: for different systems, use the spawn method of node. js child process child_process module to call the system command to open the browser.

The simple form of the corresponding system command is:

# mac
open https://lxchuan12.gitee.io
# win
start https://lxchuan12.gitee.io
# linux
xdg-open https://lxchuan12.gitee.io
Copy the code

Windows start document

Open Description of the package: open

Here you can see which NPM packages depend on Open

Many of the NPM packages we are familiar with rely on Open. Here are a few.

  • webpack-dev-server
  • react-dev-utils
  • @vue/cli-shared-utils
  • patch-package
  • lighthouse
  • release-it

4. Preparation before reading the source code

# I recommend cloning my project to ensure synchronization with the article and complete test files at the same time
git clone https://github.com/lxchuan12/open-analysis.git
# npm i -g yarn
cd open && yarn

# or clone official projects
git clone https://github.com/sindresorhus/open.git
# npm i -g yarn
cd open && yarn
Copy the code

4.1 Write an example to facilitate debugging of the source code

Since the test case is relatively complex, let’s write a simple example ourselves so that we can debug it ourselves.

Following the README, we will create a new folder, examples, under the open-Analysis folder to hold an index.js file. The content of the document is as follows:

// open-analysis/examples/index.js
(async() = > {const open = require('.. /open/index.js');
    await open('https://lxchuan12.gitee.io'); }) ();Copy the code

Await the open (” https://lxchuan12.gitee.io “); Break point. On the terminal command line

node examples/index.js
Copy the code

Debug mode is automatically invoked. Node.js debugging in VSCode is not supported. If the debugging in VSCode is not supported, you can upgrade to the latest version of VSCode.

Following debugging we can enter the open function.

4.2 open Open the function

// open/index.js
const open = (target, options) = > {
	if (typeoftarget ! = ='string') {
		throw new TypeError('Expected a `target`');
	}

	returnbaseOpen({ ... options, target }); };Copy the code

Following the breakpoint, we look at the final baseOpen call. Const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); This sentence, we can plan to debug breakpoints.

4.3 baseOpen Basic opening function

// open/index.js
const childProcess = require('child_process');
const localXdgOpenPath = path.join(__dirname, 'xdg-open');

const {platform, arch} = process;
// During debugging, we can adjust the platform by ourselves to facilitate debugging of different platforms, such as MAC, Win, Linux
// const {arch} = process;
// mac
// const platform = 'darwin';
// win
// const platform = 'win32';
// const platform = 'other ';

const baseOpen = async options => {
    options = {
		wait: false.background: false.newInstance: false.allowNonzeroExitCode: false. options };// Omit some code
    / / command
    let command;
    // Command line arguments
	const cliArguments = [];
    // Child process options
	const childProcessOptions = {};
    if (platform === 'darwin') {
        command = 'open';
        // Omit some MAC code
    } else if (platform === 'win32'|| (isWsl && ! isDocker())) {// Omit window or window subsystem code
        const encodedArguments = ['Start'];
    } else {
        const useSystemXdgOpen = process.versions.electron ||
            platform === 'android'|| isBundled || ! exeLocalXdgOpen; command = useSystemXdgOpen ?'xdg-open' : localXdgOpenPath;
        // Omit the Linux code
    }
    // Omit some code
    const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
    
    // Omit some code
    subprocess.unref();

	return subprocess;
}
Copy the code

From this we can see:

In a word, the principle of open is: for different systems, use the spawn method of node. js child process child_process module to call the system command to open the browser.

The simple form of the corresponding system command is:

# mac
open https://lxchuan12.gitee.io
# win
start https://lxchuan12.gitee.io
# linux
xdg-open https://lxchuan12.gitee.io
Copy the code

5. To summarize

In a word, the principle of open is: for different systems, use the spawn method of node. js child process child_process module to call the system command to open the browser.

This article starts from the daily common scenario that the browser can be automatically opened every time the service is started. It first describes how to use this function in webpack, VUE-CLI and creation-react-app. Finally, it explains the principle and source code implementation of Open from the source level. Work commonly used knowledge can be done to know, know why, than many people.

Because the article should not be too long, so did not fully expand on all the details of the source code. It is highly recommended that readers use VSCode to debug open source code in accordance with the method in the article. After learning to debug source code, source code is not as difficult as imagined.

Finally, you can continue to pay attention to me @Ruogawa. Welcome to join us in ruochuan12 and learn about the source code together.


About && communication groups

Recently, I organized a reading activity for source code. If you are interested, you can join me in wechat ruochuan12 for long-term communication and learning.

Author: Often in the name of ruochuan mixed traces in rivers and lakes. Welcome to add my wechat account ruochuan12. Front road | know very little, only good study. Concern about the public number if chuan vision, every week to learn the source code, learn to see the source code, advanced advanced front end. Wakawa’s blog segmentfault wakawa’s view column, has opened a column on wakawa’s view, welcome to follow ~ dig gold column, welcome to follow ~ github blog, beg a star^_^~