SystemJSとは、ES6やAMD等の汎用的なモジュールシステム。 SystemJSを使うとどんなふうにロードされるのかを試した。
インストール
npm install --save systemjs
基本的な使い方
良い感じローディングするためには初期設定が必要。
require
で呼び出すんだけど、うーん・・・ coffee-script.register()だと思えばまぁ・・・
importの返り値はpromiseなので、exportしている場合は、 .then
で受け取れる。
index.js:
var System = require("systemjs"); System.import("./lib/example"); // ./lib/example.js を読んでくれる
ベースのパスを指定して ./lib
の指定をなくす
baseURL
にURLを指定することでそこを基点にファイルを探査してくれるらしい。
windowsではパスの先頭に file:
の指定が必要とのこと。
index.js:
var path = require("path"); var System = require("systemjs"); System.config({ baseURL: path.resolve("./lib"); }); System.import("example");
node_modulesの読み込み
これまじかよって思った。
index.js
var path = require("path"); var System = require("systemjs"); System.config({ baseURL: path.resolve("./lib"); }); System.map['lodash'] = "../node_modules/lodash/index"; // `./lib` からの相対パス System.import("example");
lib/example.js
import _ from "lodash"; // 相対パスを指定するか、mapに登録する必要がある様子 // any script
まとめ
SystemJSを使ったES6の簡単なサンプルの紹介でした。
npmライブラリはおとなしく require
使いつつ自作ライブラリに関してはimport使うとかするのがいいのかな。
issuesとか眺めながら様子みたい。