LoginSignup
18
19

More than 5 years have passed since last update.

ブラウザでES6のJavaScriptを実行する

Posted at

babelで変換せずに、ES6で書いたJSをブラウザで実行したい。

ここに書いてある方法を使う。
Browser · Babel

babel-coreの導入

$ npm install babel-core

es6で書く

Chromeで確認するため、
敢えてChromeでサポートされていない引数のデフォルト値を使ってみる。

ECMAScript 6 compatibility table

app.es6.js
class Foo {
  constructor(x, y) {
    this._x = x;
    this._y = y;
  }

  sum() {
    return this._x + this._y;
  }
}

class Bar extends Foo {
  constructor(x, y, z=8) {
    super(x, y);
    this._z = z;
  }

  sum() {
    return super.sum() + this._z;
  }
}

var foo = new Foo(1, 2);
var bar = new Bar(2, 4);
console.log(foo.sum());
console.log(bar.sum());

browser.js をロードする

  • browser.min.js があるのでそれを使う
  • ES6で書いたjsは type="text/ecmascript-6" を指定してロードする
index.html
  <script src="node_modules/babel-core/browser.min.js"></script>
  <script src="app.es6.js" type="text/ecmascript-6"></script>

ブラウザで実行する

browser.js をロードしたHTMLでES6が実行されているのがわかる。

localhost_5002.jpg

意図したとおりの動作をしているが、
本当にbrowser.jsのおかげなのかがわからないため、
browser.jsをロードしないで確認してみる。

browser.jsをロードしない場合

index.html
<!--
  <script src="node_modules/babel-core/browser.min.js"></script>
--->
  <script src="app.es6.js" type="text/ecmascript-6"></script>

app.es6.jsは text/ecmascript-6 なのでそもそも実行されない。

browser.jsなしで無理矢理実行した場合

さらに type="text/ecmascript-6" を外し、
app.es6.jsをJavaScriptとして実行してみる。

index.html
  <script src="app.es6.js"></script>

結果:
syntax error

シンタックスエラーになる。
class はstrict modeであれば利用できるので use strict をつけると…

app.es6.js
"use strict";

class Foo {
  constructor(x, y) {
    this._x = x;
    this._y = y;
  }

結果:
syntax error

引数のデフォルト指定をしている箇所でシンタックスエラーが発生するので、
browser.js が仕事をしていたことがわかる。

ただし…

Not intended for serious use
Compiling in the browser has a fairly limited use case...

とあるので、ちょっとES6を試したいときに使う程度にとどめるのがよさそう。

18
19
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
18
19