1
3

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 5 years have passed since last update.

webpackで既存ライブラリをbundle

Last updated at Posted at 2019-05-27

既存のプロジェクトをwebpack化するとなると、困るのは古いライブラリたちですよね。
しかも古いバージョンで固定して開発してるので、バージョン変えたくない。
新しくしてどこか動かなくなっても困るし。

一番簡単な形

npm install jquery@[バージョン]
webpack.config.js
plugin: [
    new ProvidePlugin({
         jquery: 'jquery',
         $: 'jquery'
    })
]

これだけ。

Jsファイルで
$(function(){ なんか処理 }); とか、
$('.test') とか、
;(function($){ なんか処理 })(jQuery);
しているところで、
npm install したjqueryライブラリを使えるようにprovideします。

しかし npm install したバージョンとダウンロードしたバージョンが同じかどうか確証が得られませんでした。。
jquery.jsファイルを比較してみても差分だらけ。。

bundleしたファイル以外で読み込む場合

jqueryをbundleせずに別で読み込む。
もともと読み込んでた <script type="text/javascript" src="jquery.js"></script> をそのままにして、bundleできるものだけbundleする。

OKケース

index.html
  <head>
    <meta charset="UTF-8">
	<title>Webpack Test</title>
	<script type="text/javascript" src="../js/jquery.min.js"></script>
	<script type="text/javascript" src="app.bundle.js"></script>
  </head>

NGケース

なぜかbundleしてしまうと、jsファイルは読み込んでいるのに $ is not found. と出てしまいます。

index.html
  <head>
    <meta charset="UTF-8">
	<title>Webpack Test</title>
	<!-- ↓この中にjquery.jsを含める -->
	<script type="text/javascript" src="vendor.bundle.js"></script>
	<script type="text/javascript" src="app.bundle.js"></script>
  </head>
webpack.config.js
module.exports = {
	entry: {
		vendor: 'js/jquery.min.js',
		app: 'main.js'
	},
};

bundleに含めて使う

jqueryをnpm installしないで、webpackする。

webpack.config.js
module.exports = {
	//前半略
	plugins: [
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
		}),
	],
	resolve: {
		alias: {
			jquery: "../js/jquery"
		}
	},
	module: {
		noParse: new RegExp("../js/jquery")
	}
};

ProvidePluginで設定しているjqueryに対して、
resolve.aliasでどのファイルを使うか設定してます。
パスはbundleするjsファイルのからのパスです。
parseされてしまうとダメなようなので、 noParse でも同じファイルを設定します。

jquery以外にもライブラリがたくさんある場合は、ここのように addVendor 関数作って設定すると楽かもしれませんね。
(参考)

  • ファイル構成
app/
	node_modules/
	js/
		jquery.js
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?