foreword
Modern front-end frameworks like React, Angular, Vue, etc. rely heavily on the terminal. If you are not used to using the command line interface, you will have a hard time running a local development server or building your application.
Ironically, our entire work is built on graphical user interfaces, but the tools we use in development are mostly command-line based.
Unless you have a computer science background, or grew up with computers in the 1980s, chances are you won't have extensive terminal experience. However, most online resources assume that you are already proficient at this.
It takes years of practice to become a terminal boss, but the good news is: we can take shortcuts. We don't really need to know the vast majority of things that can be done with the terminal. If we focus on the most important key fundamentals, we should be able to adapt to the command line in no time. ✨
This is what this article wants to introduce. It's a manual on terminal basics that you need to use modern JS frameworks like React, and with it you can move on to the fun stuff: building user interfaces.
I'll also share tips and tricks I've gotten from the terminal that I wish someone could have told me when I first started working.
Preparation
Well, before we start, we need to do two more things.
First, we need some terminal software. Terminal software is an application that runs a command line environment.
Almost every operating system will have a built-in terminal, such as Terminal.app
Command Prompt
Windows, and both of these applications work, but are not very satisfactory. Most developers will choose to use other software.
As long as you're using modern technology, it doesn't matter which end application you choose to use. So here I have two main suggestions:
- Hyper . Hyper is a modern, multi-platform terminal application. It looks great and comes with some funky features, like the ability to split into multiple windows.
- If you use VS Code as your code editor, VS Code already has a powerful, modern terminal built in. This is great, and means that code and terminal can run side-by-side within one app. You can open a terminal in VS Code by selecting View → Terminal.
In this post, I will use Hyper to show all the examples.
At this point, the terminal application is selected and only half is completed. We also need to make sure the correct shell
language is running.
When we enter a command in the terminal and press Enter, the command will be interpreted and executed through the shell
language. It's essentially an environment that runs in a terminal application.
The most popular shell
language is Bash. When you see command line instructions online, there's a good chance those instructions are based on Bash. This is the default shell
language used by most Linux distributions.
Modern MacOS versions come with Zsh, not Bash. But Zsh is very similar to Bash: they belong to the same family and share almost all the same commands. For purpose, they are used interchangeably.
If you're using Linux or MacOS, it's time to get started. Your computer is already using an "industry standard" shell
language. However, if you are using Windows, we still have a little work to do.
image metaphor
Have you ever opened the developer console in your browser to run some arbitrary JavaScript code?
In this case, the application is Chrome and the language is JavaScript. Chrome provides a command line interface, but when we run commands, those commands are interpreted in JavaScript.
It's the same when it comes to the terminal. A terminal app like Hyper might be running the Bash shell
language. Unlike browsers, terminal applications can switch between multiple shell
languages.
Windows settings
First off, I need to admit that I'm not a pro when it comes to Windows development. Please take everything I say next with a grain of salt.
Bash is based on the Linux shell
language, and it doesn't run natively on Windows. Fortunately, newer versions of Windows have the ability to install and run Linux as if it were an application. This is called Windows Subsystem for Linux, often abbreviated to WSL.
Here's a tutorial that walks through the steps required: How to Install and Use Zsh in Windows .
I ran the steps myself, and while it was a bit tedious, it worked!
Once set up, you can configure the terminal to use either Bash or Zsh. Here's some introduction to configuring Hyper to use Zsh .
If you're having trouble with these steps, here are some other solutions you can try. A popular method is Git Bash , which allows you to run Bash using emulation inside Windows.
At the end of the day, it doesn't matter how you do it. Importantly, you can use Bash or Zsh in Windows.
Hello World
When you first open the Terminal app, you'll encounter this rather unhelpful interface:
Your terminal may look a little different, depending on the operating system, terminal application, shell
language you are using. In general, you might see a line of text, and a bunch of blank space.
This line of text is called a hint. It's called a "hint" because it's waiting for you to give some kind of instruction.
For our first command, enter the text echo "hello world"
and hit enter:
The syntax is a little different, but you can think of commands as built-in JavaScript functions. echo
command is very similar to console.log
function in JavaScript.
Like functions, commands can also receive arguments. In this example, echo
takes an argument and outputs a string.
When we press enter, the command is executed immediately and the value is printed. The next line presents a new prompt letting us know it's ready for the next command.
Just like that, you have successfully run your first terminal command.
skip $
When reading installation instructions for NPM packages, you will often see something like this:
$ npm install some-package
If you try to run this piece of text, you will get an error. This is because the dollar sign ($) should not be included. You should type everything after the dollar sign.
Why do the installation instructions include a random symbol that isn't actually part of the command? Well, in Bash shell
language, $ is the prompt, which is displayed at the end of the prompt.
It's essentially a symbol that says: Hey, here's something to run in the terminal!
Although in many modern shell
languages (such as Zsh), $ is not actually used as a prompt character, its symbolic meaning still exists, such as the saved icon is a floppy disk shape, although we have decades Floppy disks are not used anymore.
navigation
The main purpose of the terminal is to be able to let you move files around in the filesystem, and open/run things. It's essentially a text-based version of the GUI file explorers we use every day (like Finder, Windows Explorer).
To help us navigate around, there are a number of terminal commands available. Let's explore some of them.
The pwd command stands for Print Working Directory, and it's kind of like the "you are here" arrow on a mall map. It will tell you where you are currently:
When you open the Terminal application, you are usually thrown into the "home" directory, which contains the Documents and Desktop directories. On my machine, this directory is located at /Users/joshu
.
Using the ls
(short for List) command, you can view the contents of the current directory:
On my terminal, the directory is bold and displayed in light aqua. The single file is the normal text thickness, displayed in white.
We can use the cd
(Change Directory) command to move the file system:
This is equivalent to double-clicking the "stuff" directory in the GUI file explorer.
Note that the prompt changed from a tilde (~) to "stuff". In the Zshshell
language, the default prompt consists of an arrow and the name of the current directory, eg "→ Documents". Wait, why is it preceded by a tilde and not the name of the parent directory? On MacOS and Linux, the tilde is an abbreviation for the userhome
directory. On my machine, "~" is equivalent to "/Users/joshu
". It's easy to mistake "~" for a prompt character, like "$" in Bash.
What if I want to go back one level, back to the home
directory? I can also use the cd command to do the trick, but with two dots ( ..
).
In most shell
languages, the dot character ( .
) has a special meaning:
- A dot (
.
) represents the current directory. - The two dots (
..
) indicate the parent directory.
If you've used the module system in JavaScript, you're probably already familiar with this convention. It uses the same notation, with two dots to denote the parent directory:
import { COLORS } from '../../constants';
import Button from '../Button';
There is one important thing to know about the cd
command. That is cd
can receive complex paths. Beginners of the terminal tend to go step by step like in a GUI file explorer:
Doing this is fine, but requires a lot of extra work. We can do the same path jump in one step like this:
Tab autocompletion
One of the most intimidating things about Terminal is that it doesn't give you any clues or hints. Using the GUI File Explorer, you can see a full list of files and folders to refresh your memory and help you find what you're looking for.
If you want to use cd
as I suggest, jumping from place to place in one fell swoop, it looks like you might need a photographic memory. You can't do that unless you remember the exact name of each directory in the path chain, right?
Fortunately, a very handy trick makes this easier: tab autocompletion.
The Tab key is crucial when using the terminal effectively. In addition to the navigation tricks shown here, we can also use the Tab key to autocomplete Git branches, or to complete the rest of a command.
Try pressing the Tab key in different situations and see what happens.
Visual autocompletion
If you find it difficult to master Tab's autocompletion, you might be interested in Fig . Fig is a terminal plugin that adds editor-style autocompletion.
I've also just started experimenting with Warp , a modern terminal built for speed and user experience. As of this writing, it's exclusive to MacOS, but they do plan to port it to Windows and Linux after the beta.
We are living in an era of terminal renaissance, and there are a lot of tools designed to make it less intimidating.
logo
Earlier, I mentioned that commands in Bash/Zsh are like functions in JavaScript. When it comes to logos, the analogy doesn't quite apply.
Flags are modifiers that adjust the behavior of a command in a predefined way.
For example, let's take a look at rm
command. This command allows us to delete individual files:
We didn't get any sort of confirmation, but if we looked again, theme-song.mp3
file had indeed been deleted.
Before going any further, I should warn you: the terminal can be quite intolerant.rm
The command does not have a "Are you sure?" confirmation prompt. There are also no undo actions. When you userm
to delete a file, it doesn't go to Recycle Bin/Trash. It is permanently and irreversibly removed. This is a common theme for terminals. There aren't many safety mechanisms. So be careful when using commands likerm
.
If you try to use the rm
command on the directory, you will get an error:
By default, rm
can only delete a single file, but we can use the r
flag to change the rules:
r
flag stands for recursive. It will delete anything inside the stuff
stuff
directory, anything inside the ---d845da28a238bcb95385590a950d5a78---directory, stuff
directory, And so on.
You may also encounter some file permission issues. For this reason, the f
flag (Force) is also commonly used. We can group multiple flags with a single dash, like this:
Logos come in many shapes and sizes. By convention, flags usually have a short form (eg: -f) and a full form (--force). The full form usually uses two dashes and uses whole words instead of individual letters.
Let's look at another example. The ls
command we've seen earlier is usually invoked with two flags:
-
l
flag, which islong
. It prints the directory contents as a detailed listing with metadata. -
a
flag, which isall
. It will contain hidden files and directories.
This largely changes the output format:
There's a lot of annoying data here, including puzzling permission characters. But some metadata, such as showing the date the file was last updated, can be useful.
manual
To learn more about the command, you can use the man
command (short for manual) to call up its built-in documentation.
What I'm telling you is that man
the documentation is dense and often difficult to parse. But it's still useful to know what flags some commands have.
In some cases the file will open in your default text editor, but usually it will open in the terminal as shown. A program called less
is used here.
To scroll through files in less
use the up/down arrow keys. On modern versions of MacOS, you can also use the mouse wheel to scroll, although this may lead to incorrect behavior on other platforms.
When you have finished viewing the manual, press q
to exit. It should revert to the typical terminal view.
interrupt command
Some processes run continuously for a long time, and if they want to stop running, they need to be interrupted.
For example, open a terminal and try to run the following command: ping 8.8.8.8
.
ping
command will check the latency for a given IP address. It is useful for checking if a given server is online. 8.8.8.8
is the IP address of Google DNS server.
Unlike the commands we've seen so far, ping
is a long-running process that never stops. By default, it will be ping
Google's DNS servers until the time runs out.
When we are satisfied with the result, we can interrupt the command by pressing ctrl
and c
. Even on MacOS, most shortcut keys use the ⌘ modifier, here we use ctrl
.
Another useful command is ctrl
+ d
. This will terminate the current session. If ctrl
+ c
doesn't work in some cases, ctrl
+ d
may work.
Finally, if the above methods fail, you can directly close the current tab page or window. The shortcut keys for this method depend on the operating system and terminal program you are using. If you are using Hyper on MacOS, the shortcut key combination to close the current window is ⌘
+ w
.
Exit Vi/Vim
Sometimes, Vi
or Vim
is used to edit the file. These editors are notoriously hard to quit; ctrl
+ c
can't help you here.
To exit without saving, follow these steps:
- Press
Escape
. - Press
:
, which should add a prompt to the bottom of the terminal. - Type
q!
and press Enter.
Common development tasks
So far, we've seen a lot of examples of how to use the terminal to do things. Next let's take a look at how to accomplish some typical development tasks through the terminal.
The following examples assume you have Node.js installed locally. If you haven't installed it yet, you can download the installation package from the Node homepage to install it.
Manage dependencies
Suppose today is your first day at work. Your team has given you access to the project's source code, which you have downloaded to your computer. and then?
The first step is to download the project's third-party dependencies.
Here are the steps to follow:
cd path/to/project
npm install
npm
stands for Node Package Manager. When you install Node.js, npm
will be installed automatically.
Running this command will download all third-party code that the project depends on from the NPM repository. These codes will exist locally in the node_modules
directory.
run npm scripts
At this point, you have downloaded the third-party code, and then what?
If you look at the project's package.json
, you might see a partial configuration like this:
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
}
These scripts
are tasks that can be run with NPM tools. They can be executed by running npm run [name]
. For example, to start a local development server, we would run:
cd path/to/project
npm run start
Running this command starts a long-running process. It starts a Node server that allows us to develop on top of the application, listen for changes to files, and repackage them when we edit them.
When we finish development, we can use ctrl
+ c
to shut down the service.
The beauty of NPM scripts is that they standardize things. start
, build
, and test
are common names for these standard tasks. Therefore, we don't have to remember commands customized for each project, even if those projects use completely different tools.
We can also create our own NPM scripts. About this, I will explain in detail in a later article.
Open the project in the IDE
When I want to start working on a project, first I navigate to the root of the project in the terminal. Then run the following commands:
cd path/to/project
code .
We mentioned earlier that .
refers to the current working directory. code
is a command added by my code editor VS Code. Running this command opens the entire project in my code editor, allowing me to easily jump between different files as I want.
Note that the execution of this command depends on your editor. And, for those of you using VS Code on MacOS, you need to do some work to enable code
command.
reinstall dependencies
Did you know that the standard recommendation for any computer problem is to reboot?
The javascript version of the problem is to reinstall the npm dependencies. Sometimes, just a clean removal and reinstallation will fix the problem. Especially if you edit the node_modules
file and debug it.
We can do this:
cd path/to/project
rm -rf node_modules
npm install
After we enter the correct directory, use the rm
command to delete all third-party code, and then use npm install
to reinstall the dependencies.
Using Git
While there are GUI applications to use Git, many developers prefer to use the command line for Git-related tasks.
A complete Git command line tutorial is well beyond the scope of this article, but here is a quick cheat sheet of the commands I use frequently:
// 下载Git仓库到本地
git clone [URL]
// 检查哪些文件被修改
git status -s
// 查看更改
git diff
// 添加所有文件到暂存区
git add .
// 提交暂存的文件
git commit -m "Short descriptive message"
// 创建新的本地分支
git switch -c [new branch name]
// 切换分支
git switch [branch name]
// 推送代码
git push origin [branch name]
// 开启可交互的变基
git rebase -i [branch name or commit hash]
Tips
Over the years, I've mastered a few terminal tricks. They are not important, but they help improve the developer's experience with the terminal.
Cycle and toggle commands
Many terminal programs log every command you run in a particular session. You can use the up key to cycle through previous commands.
If I know for certain that a command has been run recently, hitting the up key a few times is usually faster than typing it from scratch.
Here's another magic trick I learned a while back: -
characters.
Suppose we want to use cd
to jump back and forth between two directories. We can do this by entering the entire path. Or use cd -
to quickly switch to the previous cd
directory.
clear terminal
Just like clearing the desktop, clearing the terminal can clear your mind.
There are several ways to do this. First look at clear
command, which clears all previously entered commands and makes it look like you just started a new terminal session.
There is also a general shortcut key, ctrl
+ L
. It has the same effect as the clear
command. It should work in MacOS, Windows and Linux.
This command/shortcut is implemented in Bash/Zsh. It is part of the shell
environment. This means it only works when shell
is idle.
Some terminal programs also implement their own shortcuts that even work when shell
is busy. Here is a list of shortcut keys I know of:
- In MacOS, for almost all
shell
(Terminal.app, iTerm2, Hyper), the shortcut is ⌘ + k. - If using Hyper on a non-MacOS platform, the shortcut keys are
ctrl
+shift
+k
.
These application-level shortcuts are much easier to use. They can be used even when shell
is busy.
For example, let's say you're running a development server, which is a long-running process, so the shortcut ctrl
+ L
won't work. As you develop a project, a lot of information is logged in the terminal window. The app's shortcut keys allow you to clear old logs, just like archiving old emails. This is really useful and a great example of how modern terminal programs can make things easier for us.
alias
Every once in a while, I find myself typing some commands over and over again. If the command is long and complicated, it is very annoying to type out in full every time and memorize it word for word.
Both Bash and Zsh support aliases, a way to create custom shortcut keys. For example, I can set it to automatically run echo "Hello World!"
whenever I type hi
d75b9029c0edf34d45bc9f0cd5ee94c1---.
Setting up aliases is a bit beyond the scope of this tutorial, and depending on your shell
language, the instructions are also a little different. Here are some more in-depth helpful tutorials:
Switch to GUI File Explorer
Unless you've reached the black belt of using the terminal, sometimes you'll want to open the working directory in the GUI file explorer.
In MacOS, the open .
command can do this.
open
command is generally used to open a file, just like double-clicking a file in the GUI file explorer to open it.
However, when we tried to open a directory, it chose to pop up a new Finder window showing the contents of that directory at the same time.
Since the dot character ( .
) represents the current directory, opening .
allows us to switch from Terminal to Finder to continue our work outside of Terminal.
On Windows, you can use explorer .
for the same purpose.
On Linux, as long as the Linux distribution implements the FreeDesktop standard, xdg-open
can be used to open a file, or the current directory.
chain command
Whenever I clone a new project from Github, I generally do two things:
-
npm install
to pull third-party dependencies. -
npm run start
to start the local development server.
npm install
command usually takes a few minutes. I don't have enough attention to sit and watch dependencies download complete, so I use Twitter to distract myself a lot. The next thing I know is that 20 minutes passed and I completely forgot that I was going to start a development server.
We can use chained commands to solve this problem. Here's how it works:
&&
operator allows us to chain together multiple commands. The first command will be executed, which is npm install
. While it's done, the second command will run automatically.
This is a particularly neat trick because npm run start
usually opens a browser window that grabs my attention and lets me know that everything is ready. By contrast, npm install
is done silently.
Once I got the hang of chaining commands, I started using it everywhere. I often line up a bunch of Git commands together:
git add . && git commit -m "Stuff" && git push origin main
Summarize
We covered a lot in this article. Hope you don't feel too much pressure.
Terminal has a good reputation for being intimidating and tricky for beginners. If you're struggling with it, that's perfectly normal.
Hopefully this article at least narrows down what you need to learn. There are many things that can be done with the terminal, but we can focus on a certain part of the function.
If you think this article is helpful to you, welcome to collect, follow and forward~
Original link: https://www.joshwcomeau.com/javascript/terminal-for-js-devs/#cycling-and-toggling-commands
Author: Joshua Comeau
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。