フロント歴がもうすぐ2年になるのに
webpackってなんぞ・・・?
状態だった僕が業務で導入しなければいけなくなったので
少し実装記録を残したいと思いたった。
webpackのインストール
グローバルにはインストールしていません。
npm install webpack webpack webpack-cli
やりたきこと
ディレクトリ構造を変えず、一つのjsファイルにバンドルする
現構造は
src
├ dir1
│ └ dir1-1
│ ├ pc
│ │ └ common.js
│ └ sp
├ dir2
│ └ dir2-1
├ dir3
└ ・・・
common.js内に
名前空間から関数処理、実行まですべてが書かれている。とてつもない行数だ。
改善①
src
├ dir1
│ └ dir1-1
│ ├ pc
│ │ ├ aaa.js
│ │ ├ bbb.js
│ │ └ ccc.js
│ │ └ main.js
│ └ sp
├ dir2
│ └ dir2-1
├ dir3
└ ・・・
aaa.js、bbb.jsは
元common.js内のオブジェクト。
機能ごとにモジュール化した。
exportやimportを使い、main.jsに読み込ませる。
webpackのおかげでie11でも動いた。
// aaa.js
var CHANGE_LANGUAGE = { // 適当
init: function() {
・・・
}
}
export default CHANGE_LANGUAGE {
return CHANGE_LANGUAGE();
}
// main.js
var NAMESPACE = NAMESPACE || {};
・・・
import CHANGE_LANGUAGE from "./aaa.js";
NAMESPACE.CHANGE_LANGUAGE = CHANGE_LANGUAGE();
・・・
// 実行する
if(NAMESPACE.DETECT.isActive) { // 適当な時に実行
NAMESPACE.CHANGE_LANGUAGE.init();
}
main.js内を実質common.jsと同じ内容にする。
main.jsをwebpackでビルドして吐き出す。
webpack.config.js
ニュアンスコード。
const glob = require('glob');
const path = require('path');
const dir_path = '/js/';
const entry_point = path.resolve(__dirname, dir_path + 'src'); // src内対象
const dir = ['dir1', 'dir2', 'dir3'];
const separation = ['pc', 'sp'];
const targets = glob.sync(`${entry_point}/+(${dir.join('|')})` + "/**/" + `+(${separation.join('|')})/main.js`); // main.jsのみ
const entries = {};
const keys = [];
function findSeparation(element) {
for(var i=0; i<=separation.length; i++) {
if(element === separation[i]) {
return separation[i];
}
}
}
targets.forEach(value => {
const re = new RegExp(`${entry_point.replace(/\\/g, '/')}/`); // Windowsで'\'を'/'に直す処理
const path = value.replace(re, '');
const split_array = path.split('/'); // pathを/区切りで配列化
const separation_point_num = split_array.findIndex(findSeparation) + 1; // separationの次の位置
split_array.splice(separation_point_num, split_array.length);
const newPath = split_array.join('/') + '/common';
var matchPath = keys.find(function(element) {
return element === newPath;
});
if(matchPath) {
entries[matchPath].push(value);
}
else {
keys.push(newPath);
entries[newPath] = [value];
}
});
module.exports = {
mode: 'production', // モードの指定([development],[production],[none])
entry: entries,
output: {
path: path.join(__dirname, dir_path + '/public/'),
filename: '[name].js'
},
}
やっていることは結局
key:生成したい構造のpathとファイル名
value:対象ファイルのpathが入る配列
という形のentriesというオブジェクトを生成している。
この組み合わせでディレクトリ構造およびバンドルされたjsファイルが生成される。
ちなみにwindowsだと/は\にしないといけないようのでdir_pathに文字列で/と書いてしまっているのは改善したほうがいいかもしれない。一応途中で変換処理をしているので動く。
お世話になったサイト
https://codogue.com/asciitree/
ディレクトリ構造を生成してくれる。
メンバーや環境を共有している他領域に共有する上でとても役立ちました。
treeコマンドでわざわざディレクトリを生成するなんてことはしたくなかったので。