Develop Node.js Projects with WSL 2

I have a PC in my apartment. But I never use it as a development machine. Recently, I feel tired of bringing the Mac mini everyday. So I decided to set up a development environement on my PC. Here is what I've done for Node.js projects.

Network Issues

If you don't live in mainland China, you can just skip this section.

If you want to be a competent developer in mainland China, you must resolve some well-known network issues. But I just hadn't expected that these issues showed up so early.

First, find the IP address of Windows by running cat /etc/resolv.conf. You will get something like this.

# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 192.168.163.65

The IP address after nameserver is the host. Suppose your proxy runs at port 7890, you can set the HTTP and HTTPS proxy by following commands.

export https_proxy=http://192.168.163.65:7890
export http_proxy=http://192.168.163.65:7890

And, of course, proxy for git. This step is of two parts. First, you have to tell ssh that use SSH over HTTPS for github.com by adding following content to ~/.ssh/config.

Host github.com
  Hostname ssh.github.com
  Port 443

Second, let git use the proxy.

git config --global http.proxy http://192.168.163.65:7890

Remember to set the proxy in root user because apt runs at root.

Intall Node.js and Yarn

Install Node.js by following commands in NodeSource. For example, I like to use the latest (15).

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_15.x | sudo bash -
sudo apt-get install -y nodejs

Then, install Yarn according to its docs.

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn

Install Dependencies

Because WSL 2 is a barely naked install, i.e. without many necessary packages by default. In order to build some Gatsby dependencies, we must install some build tools first.

# For pngquant
sudo apt install libpng-devel automake libtool autoconf
# For mozjpeg
sudo apt install nasm pkg-config

Then, run yarn. Everything will be okay.

Signing Commits Using GPG

Just follow steps in this gist.

I encountered this error when I signed off commits.

$ git commit -S
error: gpg failed to sign the data
fatal: failed to write commit object

According to this post, just run export GPG_TTY=$(tty) before using GPG.