LoginSignup
43
28

More than 5 years have passed since last update.

ES6でクラス定数を使う

Last updated at Posted at 2016-02-18

Class.CONSTのかたちで呼び出せる、クラス定数をES6のクラス構文で書いてみました。

index.js
class Qiita {
  static get API_ENDPOINT() {
    return "http://qiita.com/api/v2/";
  }
}

console.log("Qiita API Endpoint:", Qiita.API_ENDPOINT);
package.json
{
  "name": "es6-class-const",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.5.1",
    "babel-preset-es2015": "^6.5.0"
  },
  "babel": { "presets": [ "es2015" ] }
}

試してみるには、上記の2ファイル(index.jspackage.json)を置き、同じディレクトリで以下のコマンドを実行してください。

コマンドライン
$ npm install
$ node_modules/.bin/babel-node index.js
実行結果
Qiita API Endpoint: http://qiita.com/api/v2/

また、結果的にES6のコマンドライン実行の最小環境サンプルにもなりました。

各種バージョンは以下の通りです。

コマンドライン
$ node --version
v5.5.0
$ npm --version
3.7.1
$ node_modules/.bin/babel-node --version
6.5.1

それでは良いES6開発ライフをお過ごしください。


追記:Githubにリポジトリも作ったのでそちらから動作を試すこともできます。
https://github.com/noriaki/es6-class-const-example


追記:@ykztsさんから編集リクエストをいただき、固定値を返すのであれば getを使う必要はありませんと教えていただきました。ありがとうございます。

調べてみた感じだと、以下の構文はES7の仕様として検討されている構文でのようです。

index.js
class Qiita {
  static API_ENDPOINT = "http://qiita.com/api/v2/";
}

console.log("Qiita API Endpoint:", Qiita.API_ENDPOINT);

この構文をBabelで有効にする場合は、package.jsonを以下のようにすると利用可能になります(transform-class-propertiesプラグインを追加)。

package.json
{
  "name": "es6-class-const-sample",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.5.1",
    "babel-plugin-transform-class-properties": "^6.5.2",
    "babel-preset-es2015": "^6.5.0"
  },
  "babel": {
    "presets": [ "es2015" ],
    "plugins": [ "transform-class-properties" ]
  }
}

こちらのケースは、noriaki/es6-class-const-example#es7-transform-class-propertiesブランチとしてGithubリポジトリに反映しておきました。

43
28
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
43
28