LoginSignup
46
49

More than 5 years have passed since last update.

Webpackで外部ライブラリを読み込む方法

Last updated at Posted at 2017-01-07

Webpackで外部ライブラリを読み込む方法

参照:https://webpack.github.io/docs/code-splitting.html

最近Webpackに興味を持ちはじめて、勉強しているのですが、外部ライブラリをうまく読み込む方法がわかったのでメモします。

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

module.exports = {
    entry: {
        // 外部ライブラリを読み込むvendorとページごとのjs作成
        'vendor': ['bootstrap-loader', 'backbone-fetch-cache'],
        'app/index': path.join(__dirname, '/src/app/index.js')
    },
    output: {
        filename: path.join(__dirname, '/build/[name].js')
    },

    /* 他の設定(ここでは省略) */

    plugins: [
        // この設定をするとvendorの中身は他のentryでは読み込まれない
        new webpack.optimize.CommonsChunkPlugin('vendor', 'build/vendor.js'),
        // webpack.ProvidePluginを使用すると、指定した変数名でライブラリを使用できるようになる
        // 以下の例だと、$, jQuery, window.jQueryでjqueryを使用することができる
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new webpack.ProvidePlugin({
            kb: 'knockback'
        }),
        new webpack.ProvidePlugin({
            moment: 'moment'
        })
    ],
    resolve: {
        extensions: ['', '.js']
    }
};

js読み込みはこんな感じ。これでライブラリ読み込み用のjsとアプリケーション用のjsとで分けることができる。

index.html
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="app/index.js"></script>
46
49
1

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
46
49