Node.js不要。古いブラウザでもここまでモジュール化できる!
成果物
要点
- require.jsでモジュール化(JSファイル分割)
- BabelでES6(ES2015)のコードをトランスパイル(class構文)
- require.js, Babel, はCDNのURLを設定して入手する(要ネット接続)
コード
構成
- index.html
- app.js
- js/app
- main.js
- Display.js <---こいつがクラス
ファイル
index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Babel + require.js</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js"></script> <script data-main="app.js" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script> </head> <body></body> </html>
app.js
requirejs(['js/app/main.js']);
js/app/main.js
define(function(require, exports, module) { var Display = require('js/app/Display'); let d = new Display(); console.log('class:', Display); console.log('instance:', d); d.print() });
Display
はclass
(後述)let
は{}
スコープ修飾子。これまで使っていたvar
は関数スコープだが、それより限定できる
js/app/Display.js
define(function() { class Display { constructor() { this.msg = "Babel, require.js, class !!" } print() { alert(this.msg); } } return Display; });
ES6(ES2015)から使えるclass
構文。もう{}
やfunction(){}
のようなobjectでクラス風にするなんて小細工は不要!
開発環境
- Raspberry Pi 3 Model B
2018-04-21時点。
所感
モジュールとクラスでかなり保守性が上がりそう。しばらくはこれをテンプレになるかも。できれば早くimport
構文を使いたいのだが。
Node.jsは環境構築と運用で心が折れるので嫌。Electronは興味深いがWeb上で使えないしインストールと学習が必要なので嫌。