それが僕には楽しかったんです。

僕と MySQL と時々 MariaDB

yarn + webpack を感覚で使っていたので勉強がてら手元に環境を構築してみる

はじめに

今までJavaScala、Cなど型が割としっかりしている言語を使って開発を続けてきた。
しかし、その経験がweb系の開発を行うときに思わぬ障害になった。
PHPとJSがわからない、あいつら抽象的過ぎてわからないという現象にぶち当たった。

そしてなんだ、こいつらwebpackとyarnってなんや!!ってなったからしっかりやっていく。

yarnとは

yarn はパッケージマネージャの npm の上位互換のようなツールと言われている。
だったら npm でいいじゃん!と思うかも知れないけど npm は色々な問題を抱えているため、 yarn が使われることが多いみたい。

yarn ではダウンロードしたパッケージをキャッシュしているので、一度使ったパッケージはすぐに再利用することができる。
このあたりは composer に似ている。

yarn は npm で管理されているけど、その方法でUbuntuにインストールするのは推奨されていない。

また package.json に対応しているから npm で package.json を使っている場合はすぐに移行できるらしい。

webpackとは

webpack はWebアプリケーションで使用しているリソースの依存関係を解決し、js や css などのアセットを生成するビルドツール。
つまり、1つ以上のモジュールをひとつにまとめたファイルを吐ける。

yarn の導入

Ubuntu 16.04に突っ込むことを前提にする。
しかし apt では入らないので、公式にかいてあるようにコマンドを叩いて突っ込む

$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt-get update
$ sudo apt-get install yarn

version 1.7.0の安定版を入れるので

$ yarn --version
1.7.0

と、でればok

webpack の導入

をやろうとしたら、nodejsのバージョンが低いっぽいので先に nvm を入れる。

nvm の導入

次のコマンドを叩いて導入する

$ git clone https://github.com/creationix/nvm.git ~/.nvm
$ source ~/.nvm/nvm.sh

それが終わったら、雑に node のバージョンを指定して突っ込む。

$ nvm install 8.11.3
Downloading and installing node v8.11.3...
Downloading https://nodejs.org/dist/v8.11.3/node-v8.11.3-linux-x64.tar.xz...
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v8.11.3 (npm v5.6.0)
Creating default alias: default -> 8.11.3 (-> v8.11.3)

webpackの導入をやる

適当にディレクトリを作ってそれをプロジェクトとする。
その前に、yarn を使って以下のことをする必要がある。

$ yarn init

これで例の package.json が生成される。

{
  "name": "SampleWebpack",
  "version": "1.0.0",
  "main": "index.js",
  "author": "lrf141",
  "license": "MIT"
}


ここまできたら、いよいよ webpack を導入する。

$ yarn add webpack webpack-dev-server --dev
yarn add v1.7.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "linux" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Saved 2 new dependencies.
info Direct dependencies
├─ webpack-dev-server@3.1.4
└─ webpack@4.12.0
info All dependencies
├─ webpack-dev-server@3.1.4
└─ webpack@4.12.0
Done in 3.31s.

これで導入は完了。

{
  "name": "SampleWebpack",
  "version": "1.0.0",
  "main": "index.js",
  "author": "lrf141",
  "license": "MIT",
  "devDependencies": {
    "webpack": "^4.12.0",
    "webpack-dev-server": "^3.1.4"
  }
}

package.json も上記の様に変化している。

次に webpack.config.js という webpack の設定ファイルを書く。

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "index.bundle.js",
        path: __dirname + "/build"
    }
}

サンプルのjsファイルを作る。

window.onload = function()
{
    var elem = document.getElementById('sample');
    elem.innerHTML = 'I love Jason Statham.';
}
<script src="index.bundle.js"></script>
<body>
    <div id="sample"></div>
</body>

実際にビルドしてみる。

$ yarn run webpack-dev-server -- --inline

と、失敗するので yarn を使って webpack-cli を導入する

$ yarn add webpack-cli
{
  "name": "SampleWebpack",
  "version": "1.0.0",
  "main": "index.js",
  "author": "lrf141",
  "license": "MIT",
  "devDependencies": {
    "webpack": "^4.12.0",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {
    "webpack-cli": "^3.0.8"
  }
}

もう一回やってみる。

$ yarn run webpack-dev-server -- --inline
yarn run v1.7.0
warning From Yarn 1.0 onwards, scripts don't require "--" for options to be forwarded. In a future version, any explicit "--" will be forwarded as-is to the scripts.
$ /home/rabbitfoot/webProject/SampleWebpack/node_modules/.bin/webpack-dev-server --inline
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
⚠ 「wdm」: Hash: 485e1d2511df65a321f5
Version: webpack 4.12.0
Time: 427ms
Built at: 2018-06-24 01:12:22
          Asset     Size  Chunks             Chunk Names
index.bundle.js  139 KiB       0  [emitted]  main
Entrypoint main = index.bundle.js
 [2] ./src/index.js 127 bytes {0} [built]
 [4] (webpack)/hot/emitter.js 77 bytes {0} [built]
 [6] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {0} [built]
 [9] ./node_modules/html-entities/index.js 231 bytes {0} [built]
[10] ./node_modules/ansi-html/index.js 4.16 KiB {0} [built]
[11] (webpack)-dev-server/client/overlay.js 3.58 KiB {0} [built]
[12] ./node_modules/sockjs-client/dist/sockjs.js 176 KiB {0} [built]
[13] (webpack)-dev-server/client/socket.js 1.05 KiB {0} [built]
[14] ./node_modules/loglevel/lib/loglevel.js 7.68 KiB {0} [built]
[15] ./node_modules/ansi-regex/index.js 135 bytes {0} [built]
[16] ./node_modules/strip-ansi/index.js 161 bytes {0} [built]
[19] ./node_modules/querystring-es3/index.js 127 bytes {0} [built]
[23] ./node_modules/url/url.js 22.8 KiB {0} [built]
[24] (webpack)-dev-server/client?http://localhost:8080 7.75 KiB {0} [built]
[25] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {0} [built]
    + 11 hidden modules

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
ℹ 「wdm」: Compiled with warnings.

これで画面に文字列が無事に表示された。

このあと、webpack の設定をいじってビルド周りのコマンドを登録したりして
効率化するべきなんだろうけど、そこら辺は必要になったときに追ってやっていく