LoginSignup
14
24

More than 5 years have passed since last update.

Babelの使い方① - Babel単体での利用

Last updated at Posted at 2016-05-18

今更ですが、ES6の勉強を始めました。
備忘録として、環境構築方法や用語などをメモしていきます。
手始めに、Babel単体での環境を作ります。

Babel単体での利用

Babel built-ins -> CLI

前提として、node.jsがグローバルインストールされている状態を想定

  • 適当なディレクトリを用意
$ mkdir babel_test/cap1
$ cd babel_test/cap1
  • Babelをグローバルインストール
$ npm i -g babel
  • package.jsonを作成 $ npm initで対話的に下記のようなファイルを作成しました↓
package.json
{
  "name": "babel-test-built-ins",
  "version": "1.0.0",
  "description": "hoge",
  "repository": "piyo",
  "main": "index.js",
  "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

ミスって、descriptionとかrepositoryが空になっちゃってもsudo vi package.jsonで編集出来ます。
(自分の環境だとread-onlyなpackage.jsonが生成されました)

  • Babelのコマンドラインツールをインストール
 $ npm i -D babel-cli
  • es2015のトランスパイル用プラグインをインストール
$ npm i -D babel-preset-es2015
  • .babelrcを作成
 $ touch .babelrc
 $ echo '{ "presets": ["es2015"] }' > .babelrc
  • コンパイル元のファイルを作成 デフォルトパラメータとアローファンクションを利用。
src/sample_es6.js
 setTimeout((hoge = "ほげ") => {
        console.log(hoge);
 }, 500);
  • コンパイルする
 $ pwd # -> ~/babel_test/cap1
 $ babel src/sample_es6.js -o dest/sample.js
  • 一応、コンパイル結果
 'use strict';

 setTimeout(function () {
        var hoge = 'ほげ';
        console.log(hoge);
 }, 500);
  • ディレクトリを一括指定してコンパイルする事も可能
$ babel src -d lib

もしくは、下記を追記して↓

package.json
{
  ...略...
   "scripts": {
        "build": "babel src -d dest"
   },
}
$ npm run build 
  • watchも出来るよ٩( ‘ω’ )و
package.json
{
  ...略...
  "scripts": {
    "build": "babel src -d dest",
    "start": "babel -w src -d dest"
    }
}
$ npm run start 

スクリーンショット 2016-05-18 17.58.09.png
(背景がスケスケなのはお気になさらず)

捕捉

npm -i: installのショートカット
npm -D: --save-dev
babel -o:--out-file
babel -d:--out-dir
babel -w:--watch

14
24
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
14
24