Windows 10 の WSL 上で動かしている Linux(Ubuntu) と Visual Studio Code を連携させて、プログラミング環境を作ってみることにしました。
その際のやったことをメモしておきます。
環境
- Windows 10 1903
WSL 環境を作る
Windows Subsystem for Linux (WSL)
まずは、WSL をインストールします。
プログラムと機能
→ Windowsの機能の有効化または無効化
→ Windows Subsystem for Linux のチェックを入れる
PowerShellからコマンドを実行することでもWSLがインストールできるみたいです。
PS C:\Windows\system32> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux この操作を完了するために、今すぐコンピューターを再起動しますか?
[Y] Yes [N] No [?] ヘルプ (既定値は "Y"): N
Path :
Online : True
RestartNeeded : True
PS C:\Windows\system32>
WLS をインストールした後は再起動を求められますので、再起動しておきます。
Ubuntu
WSL で動かす Ubuntu をインストールしましょう。
詳細は割愛しますが、以下のような要領です。
- Microsoft Store アプリを起動する
- 「Ubuntu」で検索する
- 表示された「Ubuntu」をインストールする
インストールしたら、スタートメニュー内のUbuntuアイコンをクリックして起動します。
ターミナルが起動してきて、しばらくすると「Enter new UNIX username: 」と UNIX(Ubuntu)に作成するユーザー名を求められますので、お好みのユーザー名を入力。
「Enter new UNIX password:」とパスワードの入力を求められますので、こちらもお好みのパスワードを設定します。
Retype ときたら、もう一度パスワードを入力します。
うまくいけば、プロンプトが表示されて Ubuntu が使えるようになります。
Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
username@hostname:~$
Ubuntu が使えるようになったら、取り急ぎパッケージ類を最新化しておきましょう。
username@hostname:~$ sudo apt update
username@hostname:~$ sudo apt upgrade
username@hostname:~$ sudo apt-get install -y cmake gcc clang gdb build-essential git
Visual Studio Code
続いて、エディタとして、Visual Studio Code をインストールします。
以下からダウンロードして、インストール。
拡張機能
Python を学習しようと思っているので、以下の拡張機能をインストールしました。
- Python
- Remote WSL
- vscode-icons
- Bracket Pair Colorizer
Visual Studio Code と WSL のリンク
最後に、Visual Studio Code から、WSL 上の Ubuntu のターミナルにアクセスできるようにします。
Ubuntu のターミナルから、「code .」 を入力、エンターキーを押して実行します。
username@hostname:~$ code .
Installing VS Code Server for x64 (2aae1f26c72891c399f860409176fe435a154b13)
Downloading: 100%
Unpacking: 100%
Unpacked 2391 files and folders to /home/naoto-izutsu/.vscode-server/bin/2aae1f26c72891c399f860409176fe435a154b13.
Visual Studio Code が自動的に起動してくればOKです。
続いて、起動してきた Visual Studio Code で「ctrl + shift + p」を押して、「 Terminal:Select default shell」を選択します。
Visual Studio Code 上の Terminal のディフォルト Shell を設定できますので、「WSL Bash」を選びます。
これで、Visual Studio Code でターミナルを起動すると、Ubuntu のシェルが起動するようになります。
まとめ
これで、Visual Studio Code を使って、Ubuntu 上でプログラムを書く準備が整いました。
WSL 上の Ubuntu は、「/mnt/c」に Windows 10 のファイルシステムをマウントしてくれているので、Windows 10 上のファイルも操作することができます。
プログラムファイルを Ubuntu 上のどのディレクトリに配置するかはお好み次第だとは思いますが、「/mnt/c」の配下にすれば、Windows からも Ubuntu からもファイルにアクセスできるので便利だと思いました。