かえるの井戸端雑記

開発日誌的な記事だったり備忘録だったり。まとめ記事と言うよりは、七転八倒の様子を小説みたいに読んで眺めてもらえればと。

ES6での開発環境を作る

もとをただせば

基本的に僕は作業日誌的にblogを書いていくのであんまりまとめっぽいものがない。

それはそれでいいのだけれど、時折一区切り着いたらまとめたくなる時もある。あるのです。ということで今回はES6でのjs開発環境を作る記事をまとめてみた。

実質的な内容は以下のpageと同じ。

frogwell.hatenablog.jp

そのうちQiitaにでもあげようかな。

最近のjsの開発環境

ある意味gccで言うところの以下の部分に対応している。

source compiler linker binary
es6 babel webpack bundle.js
typescript tsc webpack bundle.js

最終的な成果物であるbundle.jsをindex.htmlなど適当なhtmlが呼び出して使用する、という感覚。別にbundle.jsはどんな名前でもいい。深く気にしてはならぬ。

で、これを統合開発環境みたいなものであるNodeの中で整えることになる。この際に設定が大量に必要なのがwebpackで、ここが理解できると話が早い。

ES6とTypeScript、どちらを使うか

特にこだわりがなければどちらでも良さそう。強いて言うならWeb Interfaceを組むときにReact+Reduxを使うならES6、Angular2を使うならTypeScriptというくらいの基準しかまだ覚えにない。

今回はなんとなくES6にする。

Node

JSの開発環境。Nodeでprojectを作り、管理し、npmで関連libraryをinstallしていく。

この際projectの設定はprojectのroot directoryにproject.jsonとして保存され、libraryはprojectのroot directoryに/node_modulesといdirが作られ、その中に保存される。

作り方

brewで入れている場合は紛らわしいので削除

$ brew uninstall nodebrew
$ brew uninstall node

Install

$ curl -L git.io/nodebrew | perl - setup

consoleが起動するときのscript(.bashrcなり.zshenvなり)に以下を追記。

export PATH=$HOME/.nodebrew/current/bin:$PATH

次に公式推奨版のnodeをいれる。

https://nodejs.org/ja/ ここを見ると執筆時点での推奨版はv6.10.1らしいのでそれを使うことにする。

$ nodebrew install-binary v6.10.1
$ nodebrew use v6.10.1

これでおわり。installされたかはnode -vで確認できる。

Module Install時にerrorが出た場合

たまに以下のような文句を言われることがある。proxy使っているとかsquid的なものがいるとよくある。

npm ERR! code SELF_SIGNED_CERT_IN_CHAIN

npm ERR! self signed certificate in certificate chain
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/kuboki/Public/working/switch/dashboard/node/npm-debug.log

この場合npm set strict-ssl falseを実行すると通るようになる。

Projectの作成

適当なdirectoryでnpm initと入力し、質問に答えていくとそこにprojectが作られる。

他にdirをいくつか作り、以下のようなdir構成にする。

.
├── .gitignore
├── config
├── package.json
├── pages
├── node_modules
└── src

ES6

BabelでJSにTranspileするための記法。Reactなどで使われている。よりjsっぽい。

環境構築

まずnodeでprojectを作成。

以下のcommandで開発環境を入れる。

$ npm install --save-dev webpack path
$ npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015 babel-root-slash-import

次にprojectのroot directoryに.babelrcを以下の内容で作成する。

{
    "presets": ["es2015"]
    "plugins": [
    ["babel-root-slash-import", {
        "rootPathSuffix": "src/"
    }]
    ]
}

babel-root-slash-importを使うことで/src以下に配置したsourceのimport記述を相対pathを利用せずに定義できるようになる。

最後にcommandをpackage.jsonに登録する。

  "scripts": {
    "build": "webpack --config config/webpack-production.config.js --progress",
    "build:debug": "webpack --config config/webpack.config.js --progress",
  },

これでnpm run buildとすれば本番fileのjsが、npm run build:debugとすればdebug用のjsが生成されるようになる。

まあそのためにはwebpackのconfigが必要なわけで。次にwebpackの設定をする。

Webpack

ここだけで割とたくさん設定があるので最小限の準備だけする。

最小限の準備とは/src/webpack.config.jswebpack-production.config.js/src/entry.jsの作成である。

/src/webpack.config.js

const path = require('path');
const entry = require('./entry');
module.exports = {
  entry: entry,
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].js'
  },
  devtool: 'inline-source-map',
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
    test: /\.jsx*$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
      }
    ]
  }
};

webpack-production.config.js

var webpack = require('webpack');
const path = require('path');
const entry = require('./entry');
module.exports = {
  entry: entry,
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].min.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.jsx*$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
    warnings: false
      }
    })
  ]
};

/src/entry.js

const path = require('path');
const entry = {
      test: path.resolve(__dirname, '../src/route', 'test', "index.jsx"),
};

module.exports = entry;

Local Server

webpack-dev-serverというlibraryをいれるとlocalでserverが起動し、webpackと連携して動作確認できるようになる。

環境構築

以下のcommandでlibraryをinstall。

$ npm install --save-dev webpack-dev-server

webpackのconfigを以下の内容で作成する。file pathはconfig/webpack-dev.config.jsとした。この内容だと/pages以下に配置したhtmlにroutingが発生する。

const path = require('path');
const entry = require('./entry');
module.exports = {
  entry: entry,
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].js',
    publicPath: "/js/"
  },
  devtool: 'source-map',
  devServer: {
    contentBase: path.resolve(__dirname, '../pages'),
    port: 3000
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
    test: /\.jsx*$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
      }
    ]
  }
};

package.jsonにcommandを登録する。今回はstartで登録した。

  "scripts": {
    "start": "webpack-dev-server --config config/webpack-dev.config.js --watch --progress --inline"
  },

これでnpm run startで実行される。