webpack を使うと、 JavaScript のコードをいい感じにモジュール分割できて (CommonJS 仕様の Module 機構が使える)、複数の *.js ファイルを1つに結合してまとめることが可能。
今回の環境: Mac OS X Yosemite
$ uname -mrsv
Darwin 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64
Node.js の npm で webpack をインストール。今回はローカル環境にインストールする。
$ npm install webpack
サンプルプログラムのファイルとして foo,js, bar,js の2ファイルを準備。
foo.js が bar.js を利用するようなプログラム構造にした。
webpack では、他の JavaScript ファイルをモジュールとして読み込むための require 関数と exports が使える (CommonJSの仕様)。今回はこれを利用する。
$ cat foo.js
var bar = require('./bar');
bar.hoge('hello, world');
$ cat bar.js
function my_alert(message){
alert(message);
}
module.exports = {
hoge: my_alert
};
webpack の設定ファイル webpack.config.js に、結合後の出力ファイル名などを記述。
$ cat webpack.config.js
module.exports = {
entry: './foo.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
}
};
webpack コマンドを実行。
$ ./node_modules/.bin/webpack
Hash: 59333708fc75cba054b7
Version: webpack 1.8.10
Time: 35ms
Asset Size Chunks Chunk Names
bundle.js 1.64 kB 0 [emitted] main
[0] ./foo.js 55 bytes {0} [built]
[1] ./bar.js 89 bytes {0} [built]
foo.js, bar.js と require 機構が結合して1つのファイル bundle.js が生成される。
$ ls ./dist/
bundle.js
bundle.js の中身。
$ cat ./dist/bundle.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
(中略)
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var bar = __webpack_require__(1);
bar.hoge('hello, world');
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
function my_alert(message){
alert(message);
}
module.exports = {
hoge: my_alert
};
/***/ }
/******/ ]);
以下のような index.html ファイルを作って、ブラウザで閲覧すると、 「hello, world」とアラートダイアログに表示される。
$ cat index.html
<html>
<head>
<script type="text/javascript" charset="utf-8" src="bundle.js"></script>
</head>
<body>
</body>
</html>
-
ref.
- webpack module bundler ← webpack 公式Webサイト
- tutorials/getting-started ← webpack 公式チュートリアル
- commonjs ← webpack 公式サイトによる CommonJS の require と module.exports の解説
- WebPackを使ってJavaScriptを効率的に書くチュートリアル【入門編】 | 株式会社LIG ← 日本語による webpack のサンプル
- CommonJS: JavaScript Standard Library ← CommonJS 公式サイト (仕様ページが探しにくい)
- CommonJSの話 ← CommonJS について参考になる
tags: webpack javascript
Posted by NI-Lab. (@nilab)