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】出力の管理

Posted at

この記事では、ビルドされたファイルや、index.html ファイルの出力をカスタマイズする方法を紹介します。

なお、より詳しく知りたい場合は、公式ドキュメントを参照するのをおすすめします。

前提条件

以下手順を実施済み

【webpack】webpack の導入

複数のエントリポイント

webpack では、エントリポイントを追加することで、複数のバンドルを出力することが出来ます。

試しに print.js ファイルを作成して、エントリポイントを複数に分割してみます。

1. print.js の作成

src ディレクトリ直下に作成します。

print.js
const print = () => {
  console.log('I get called from print.js!');
}

const btn = document.createElement('button');
btn.innerHTML = 'Click me and check the console!';
btn.onclick = print;

document.body.appendChild(btn);

2. webpack.config.js の修正

次に、設定ファイルを修正してエントリポイントごとにバンドルが出力されるようにします。

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

module.exports = {
  entry: {
    index: './src/index.js',
    print: './src/print.js'
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  }
};

output > filename > '[name].bundle.js'[name] は、entry フィールドのキー名が使用されます。

3. index.html の修正

読み込むJavaScriptファイルを修正します。

index.html
...
<body>
  <script src="./index.bundle.js"></script>
  <script src="./print.bundle.js"></script>
</body>
...

4. ビルドの実行とテスト

ビルドコマンドを実行します。

> npm run build

最後に、ブラウザで index.html ファイルを開き、表示されたボタンをクリックしてコンソールを確認します。問題なければ、「I get called from print.js!」と表示されているはずです。

index.html ファイルを動的に生成する

ここまでで、複数のエントリポイントを作成し、読み込むことが可能であることを確認しました。しかし、例えばエントリポイントを追加したり、出力されるファイルの名前を変更した場合、 index.html ファイルも手動で修正する必要があります。

この手順では、上記問題を解決する為、HtmlWebpackPlugin プラグインを使用して、webpack の設定を基に index.html ファイルを動的に生成する方法を紹介します。

1. プラグインのインストール

> npm i -D html-webpack-plugin

2. webpack.config.js の修正

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

module.exports = {
  ...,
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Document'
    }),
  ],
	...
};

ビルドの実行とテスト

ビルドコマンドを実行します。

> npm run build

index.html をテキストエディタなどで開き、既存のファイルと異なるファイルが出力されていることが確認できれば成功です。

より詳しい設定オプションについては、html-webpack-plugin のリポジトリで確認できます。

dist ディレクトリのクリーンアップ

output フィールドに clean: true オプションを追加することで、dist ディレクトリの中身が使用されるファイルのみとなるよう、webpack.config.js を修正します。

webpack.config.js
...

module.exports = {
  ...,
  output: {
    ...,
    clean: true
  }
};

npm run build を実行して、不要なファイル(例えば main.js など)が削除されていれば成功です。

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?