LoginSignup
2
1

More than 1 year has passed since last update.

はじめに

最近、create react appで作ったアプリケーションではjsファイルへのリクエストが1つしかないことに気づきました。
それについて調べたところWebpackに出会ったので、Webpackについて書きます。

Webpackとは

javascriptのモジュールをいい感じにまとめてくれるやつです。

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.

Webpackを使わなかった場合

    .
    ├── index.html
    ├── sample
        ├── index.js
        ├── sample1.js
        ├── sample2.js
        └── sample3.js

上記のディレクトリ構造で、index.jssampleがつくjsファイルをインポートして、index.htmlscriptタグにindex.jsを指定します。

アクセスした際に検証ツールのNetworkタブをみると、3つのファイルそれぞれにリクエストがあることがわかります。

スクリーンショット 2022-12-02 21.26.06.png

Cannot use import statement outside a moduleエラーが出る方はこちら(僕はrails環境を使って実行しました。)

Webpackを使った場合

セットアップ

    npm init -y
    npm install webpack webpack-cli --save-dev
    touch webpack.config.js

webpack.config.jsではwebpackでどのようにモジュールをまとめるかの設定をします。
entrypointをindex.js、bundleするディレクトリをsampleディレクトリ、bundleされた結果の出力先を./sample/bundle.jsにします。

webpack.config.js
    const path = require('path');
    
    module.exports = {
        entry: "./sample/index.js",
        output: {
            path: path.resolve(__dirname, 'sample'),
            filename: "bundle.js"
        }
    }

設定が終わったら以下のコマンドを実行します。

    npx webpack --config webpack.config.js

実行が終わると、.sample/bundle.jsに結果が出力されます。
これをindex.htmlscriptタグで読み込みます。

結果

スクリーンショット 2022-12-02 22.32.12.png

以上のように、リクエストがbundle.jsへの1回になっていることがわかります。
リクエストが少なくなるので、パフォーマンスは向上するのかなと思いました(傾向があるだけで絶対そうとは限らないらしい)。

2
1
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
2
1