jQueryなど一定Global Objectに展開したいライブラリをwebpackで扱う場合に単純に以下のように書いてしまうと、Global Objectに展開されずReferenceError
が発生してしまいます。
import "jquery"; // Uncaught ReferenceError: $ is not defined $(document).ready(function () { console.log("ready!"); console.log(jQuery().jquery); });
これはドキュメントにも記載の通りwebpackの思想によるものですが、Global Objectに展開したいケースもあるかと思います。
Warning We don't recommend using globals! The whole concept behind webpack is to allow more modular front-end development. This means writing isolated modules that are well contained and do not rely on hidden dependencies (e.g. globals). Please use these features only when necessary. Shimming | webpack
そんな時にexpose-loader
を使うといい感じに展開できたのでメモ🗒
準備
今回はjQueryをGlobal Objectに展開することを想定するため以下のようにjQueryとexpose-loaderをインストールします。
$ yarn add jquery
$ yarn add -D expose-loader
expose-loader
を使ってimportしたライブラリをGlobal Objectに展開する。
後は簡単で任意のファイルでjQueryのimportをimport "expose-loader?exposes=展開したい変数名!package名";
で記載すればOKです。jQueryを$
とjQuery
としてGlobal Objectに展開する場合には以下のような形で記載します。
import "expose-loader?exposes=$,jQuery!jquery"; $(document).ready(function () { console.log("ready!"); console.log(jQuery().jquery); });
以下のドキュメントに記載の通りConfigでも設定できるようです。
https://webpack.js.org/loaders/expose-loader/#using-configuration
仕組みとしては、global objectを取得して、設定した名前のプロパティにmoduleを展開するような仕組みとなっているようです👀
おわりに
webpackはこういうサポートが豊富なところ便利ですね✨(他のライブラリにもあるかもですが)