LoginSignup
0
0

npm を Ubuntu にインストールして Hello World する

Last updated at Posted at 2023-03-20

npm を Ubuntu にインストールして Hello World する

こんにちは、@studio_meowtoon です。今回は、WSL の Ubuntu 22.04 に npm をインストールする手順を紹介します。
npm_on_ubuntu.png

目的

Windows 11 の Linux でクラウド開発します。

こちらから記事の一覧がご覧いただけます。

実現すること

Windows 11 の WSL Ubuntu 22.04 に npm をインストールします。

技術トピック

npm とは?

こちらを展開してご覧いただけます。

npm

特徴とメリット
npm (Node Package Manager) は、Node.js 用のパッケージマネージャーであり、Node.js アプリケーションで使用するパッケージを管理するためのツールです。
Node.js は JavaScript の実行環境であり、サーバーサイドの JavaScript アプリケーションを実行します。
また、フロントエンドの開発においては npm を使用して依存関係の管理ビルドツールの実行などを行います。
これらのツールは、Node.js 実行環境で実行されます。つまり、フロントエンドの開発において Node.js が必要とされるのはこれらのツールを使用するためであり、Web ブラウザ上で Node.js が実行されるわけでありません

開発環境

  • Windows 11 Home 22H2 を使用しています。

WSL の Ubuntu を操作していきますので macOS の方も参考にして頂けます。

WSL (Microsoft Store アプリ版) ※ こちらの関連記事からインストール方法をご確認いただけます

> wsl --version
WSL バージョン: 1.0.3.0
カーネル バージョン: 5.15.79.1
WSLg バージョン: 1.0.47

Ubuntu ※ こちらの関連記事からインストール方法をご確認いただけます

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04

この記事では基本的に Ubuntu のターミナルで操作を行います。Vim を使用してコピペする方法を初めて学ぶ人のために、以下の記事で手順を紹介しています。ぜひ挑戦してみてください。

npm のインストールと設定

存在を確認します。

$ node -v
コマンド 'node' が見つかりません。次の方法でインストールできます:
※ 以下省略
$ npm -v
コマンド 'npm' が見つかりません。次の方法でインストールできます:
※ 以下省略

Node.js の公式パッケージリポジトリを追加します。

$ curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash -

パッケージリポジトリを削除する場合は以下のコマンドを使用します。

$ sudo rm /etc/apt/sources.list.d/nodesource.list

インストールします。

$ sudo apt update
$ sudo apt install nodejs

バーションを確認します。

$ node -v
v19.8.1
$ npm -v
9.5.1

ここまでの手順で、Ubuntunpm をインストールすることができました。

作成する Web アプリケーションの仕様

No エンドポイント HTTPメソッド MIME タイプ
1 / GET text/html
説明を開きます。

Web ブラウザで / というエンドポイントにアクセスすると、HTML ファイルがレスポンスされるシンプルな Web アプリを実装します。

Hello World を表示する手順

プロジェクトフォルダの作成

プロジェクトフォルダを作成します。
※ ~/tmp/frontend をプロジェクトフォルダとします。

$ mkdir -p ~/tmp/frontend
$ cd ~/tmp/frontend

JS ファイルの作成

index.js JS ファイルを作成します。

$ mkdir -p src
$ vim src/index.js

ファイルの内容

src/index.js
const hello = () => {
    const app = document.querySelector("#app");
    const h1 = document.createElement("h1");
    h1.textContent = "Hello World!";
    app.appendChild(h1);
}

hello();

HTML ファイルの作成

index.html ファイルを作成します。

$ vim src/index.html

ファイルの内容

src/index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Vanilla JS</title>
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>

webpack 設定の作成

webpack.config.js ファイルを作成します。

$ vim webpack.config.js

ファイルの内容

webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
  ],
};

ビルドと実行

プロジェクトの初期化を行います。

$ npm init -y

package.json を修正します。

$ vim package.json

ファイルの内容

package.json
{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack serve --port 3000 --mode development --open "
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

ライブラリをインストールします。

$ npm install \
    webpack webpack-cli html-webpack-plugin \
    --save-dev

ビルドします。

$ npm run build

起動します。
※ ctrl + C で停止します。

$ npm run start

以下の URL で Web ブラウザが立ち上がります。

http://localhost:3000/

image.png

ここまでの作業で、Web ブラウザに Hello World! が表示されました。

何が起こりましたか?

npm は、index.jsindex.html ファイルを以下のように変換して dist ディレクトリにファイルを出力しました。今回の記事の例ではシンプルな構成なので変化は少ないですが、規模の大きいプロジェクトでは npm は必要とされます。

$ tree -I node_modules
.
├── dist
│   ├── index.html
│   └── main.js
├── package-lock.json
├── package.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js
dist/main.js
/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "./src/index.js":
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
/***/ (() => {

eval("const hello = () => {\n    const app = document.querySelector(\"#app\");\n    const h1 = document.createElement(\"h1\");\n    h1.textContent = \"Hello World!\";\n    app.appendChild(h1);\n}\n\nhello();\n\n\n//# sourceURL=webpack://frontend/./src/index.js?");

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module can't be inlined because the eval devtool is used.
/******/ 	var __webpack_exports__ = {};
/******/ 	__webpack_modules__["./src/index.js"]();
/******/ 	
/******/ })()
;
dist/index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Vanilla JS</title>
    <script defer src="main.js"></script></head>
    <body>
        <div id="app"></div>
    </body>
</html>

まとめ

Ubuntu に Node.js 環境と npm をインストールして、最小構成のフロントエンド JavaScript 開発環境を構築することが出来ました。

Ubuntu を使うと Linux の知識も身に付きます。最初は難しく感じるかもしれませんが、徐々に進めていけば自信を持って書けるようになります。

どうでしたか? npm の操作には、この他にもたくさんのコマンドがあります。みなさんも少しづつ試してみてください。今後も開発環境などを紹介していきますので、ぜひお楽しみにしてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0