LoginSignup
12
12

More than 5 years have passed since last update.

Babel環境を構築

Last updated at Posted at 2017-07-11

備忘録のため投稿します。
(Babel単独で使用するときのもの)

※gulpでBabelを使用するときの手順はこちらにまとめてます。
gulp入門と備忘録から作業前の環境構築のパターンまで

Babelとは

次世代のJavaScriptの標準機能を、ブラウザのサポートを待たずに使えるようにするNode.js製のツールです。次世代の標準機能を使って書かれたコードを、それらの機能をサポートしていないブラウザでも動くコードに変換(トランスパイル)します。
「次世代のJavaScriptの標準機能」というのはECMAScript(以降、ESと呼びます)のバージョン6や7で追加された(る)機能、そしてさらにその先の標準機能です。

引用元:Babelの手ほどき

手順

  • ローカルにインストール
  • package.json生成
  • .babelrcを生成
  • es6でjsファイルを書く
  • コンパイル作業
  • ファイルの監視(watch適用)

ローカルにインストール

command
$ npm install --save-dev babel-cli
$ export PATH=$PATH:./node_modules/.bin

package.json生成

公式サイトを参考
http://babeljs.io/docs/usage/cli/

.babelrcを生成

「babel-preset-es2015」をインストール

command
$ npm install --save-dev babel-preset-es2015
$ echo '{ "presets": ["es2015"] }' > .babelrc

es6でjsファイルを書く

input.js
class App {
  constructor() {
    console.log('class syntax');
  }
}

const func = () => {
  console.log('arrow function');
};

コンパイル作業

command
$ babel input.js --out-file output.js

es6以前のコードにコンパイルされる

output.js
'use strict';

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var App = function App() {
  _classCallCheck(this, App);

  console.log('class syntax');
};

var func = function func() {
  console.log('arrow function');
};

ファイルの監視(watch適用)

command
$ babel input.js --watch --out-file output.js

参考サイト

12
12
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
12
12