0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【webpack】webpack の導入

Last updated at Posted at 2022-08-26

前提条件

以下手順を実施済み

【npm】Nodejsプロジェクトの準備

1. パッケージのインストール

webpack本体と、webpackをCLIで実行するためにwebpack-cliをインストールします。

> npm i -D webpack webpack-cli

2. エントリポイントの準備

webpackのデフォルト設定では、変換元となるファイルはsrcディレクトリ内のindex.jsです。

> mkdir src
> type nul > src/index.js

3. バンドルの作成

webpackの役割は、ウェブコンテンツを構成するファイルをまとめることです。特に、複数のJavaScriptファイルを一つにする機能は最たる例と言えます。

ここでは代表的な例として、関数だけを記述したモジュール functions.js を用意して、エントリポイント(src/index.js)で読み込みます。

functions.js
export function hello(elm){
  elm.innerHTML = 'Hello World!';

  return elm;
}
index.js
import { hello } from "./functions";

const elm = document.createElement('div');

document.body.appendChild(hello(elm));

ここまでで、webpackを試す最低限の準備が整いました。試しに、以下のコマンドを実行してファイルをビルドしてみます。

> npx webpack

プロジェクトルート直下に、dist/main.jsファイルが作成されていれば成功です。

webpackは、ES2015で標準化されたimport/export構文をトランスパイルします。しかし、ES2015の他の機能は変換しないため、もし使用している場合、webpackローダーシステム経由でBabelなどのトランスパイラを使用する必要があります。

4. ビルドしたファイルの動作確認

main.jsを読み込むHTMLファイルを作成して、ブラウザで実行します。

> type nul > dist/index.html

VSCodeでは、HTMLファイルにhtml:5と打ち込んでEnterを押すと、テンプレートが自動で挿入されます。

dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./main.js"></script>
</body>
</html>

ブラウザにHello World!と表示されれば問題ありません。

5. 構成ファイルの使用

プロジェクトルート直下にwebpack.config.jsファイルを作成することで、webpackの挙動をカスタマイズすることが可能です。

webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

では、作成した構成ファイルを使用してビルドを実行してみます。

> npx webpack -c webpack.config.js

ビルドが成功すれば問題ありません。

webpackは、webpack.config.jsファイルが存在する場合、デフォルトでその構成を読み込みます。ただし、上記の用に-c|--configオプションを使用することで、任意の名前を使用することができます。

6. ビルドコマンドをNPMスクリプトに追加

CLIに毎回コマンドを打ち込むのは、特にオプションをしている場合に非常に手間がかかります。そのため、npmスクリプトを使用してショートカットを作成します。

package.json
{
  "scripts": {
    "build": "webpack -c webpack.config.js"
  }
}

これで、ビルドを実行する際はnpm run buildと打ち込むだけで同様の結果が得られるようになります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?