ゆるふわエンジニアのブログ

行ったこと、調べたこと等をつらつらと書いていくかもしれません。

webpackを使用してjsファイルをまとめる方法

本記事では、webpackを使用してjsファイルを
まとめる方法を紹介していきます。

本記事の内容です。

webpackって何?

簡単に説明しますと、複数のリソースファイル(jsファイル、cssファイル、画像ファイル等)を
まとめた配布物を生成するビルドツールです。
これを使用すると、複数のファイルを配布する必要が無くなり、
また、ブラウザでファイルを読み込む時に複数のファイルを読み込む必要が
無くなるため、パフォーマンス向上を図れます。

また、公式サイトは下記になります。
webpack.js.org

webpackを使用する準備

コマンドプロンプトを開き、webpackを使用する対象の
ソースコードが存在するフォルダへ移動します。
その後、下記のコマンドを実行して、package.jsonを生成します。

npm init -y

webpackのインストール

package.jsonの生成が終わったら、次は、下記のコマンドを実行して
webpackを使用するためにwebpack本体のインストールを行います。

npm i -D webpack webpack-cli

webpackの設定ファイル作成

webpackのインストールが終わったら、package.jsonが存在するフォルダに
webpackの設定ファイル(webpack.config.js)を作成します。
下記の内容は、index.jsをメインにdistフォルダへ、
main.jsという名前で複数のjsファイルをまとめた結果を出力するようになっています。

module.exports = {
 
    // メインとなるJavaScriptファイル(エントリーポイント)
    entry: `./js/index.js`,

    // ファイルの出力設定
    output: {
      //  出力ファイルのディレクトリ名
      path: `${__dirname}/dist`,
      // 出力ファイル名
      filename: 'main.js'
    },
  };

JavaScriptソースコードの準備

今回は、index.jsとindex2.jsという2つのファイルを用意し、1つにまとめてみます。
それぞれのファイルの内容は、下記の通りです。

index.js

import * as hogeFile from './index2';

$(function() {
    hogeFile.hoge();
    hogeFile.fuga();
});

index2.js

export function hoge() {
    alert('hoge');
}

export function fuga() {
    alert('fuga');
}

ビルド

下記のコマンドを実行し、ビルドを行います。

npx webpack

以上で、複数のjsファイルをまとめることができます。

jsファイルをまとめた結果

最後に、参考までに今回jsファイルをまとめた結果を下記に記載しておきます。

!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t),$(function(){alert("hoge"),alert("fuga")})}]);