ブラウザでES Modulesを使う

前置き

いくつかのブラウザで使えるようになっているっぽいので少し書いてみます. 詳しいことは書きません.使い方は間違っている可能性があります.使えた〜というだけなので情報量はほぼないです.

本題

HTMLに次のように書きます.type="module"がないと動きません.

<script type="module" src="./main.js"></script>

次のようにmain.jshello.jsを定義します.

// main.js
import hello from './hello.js'

hello('ESM')
// hello.js
const hello = (name) => {
  const box = document.getElementById('box')
  box.textContent = `Hello ${name}!`
}

export default hello

↓で動作確認できます.
https://nimiusrd.github.io/ESM/

ソース github.com

まとめ?

Safariは何も設定しなくても動いたのが驚き(?) 使い始めるのはいつからがいいんですかね?

ref

Can I use... Support tables for HTML5, CSS3, etc

Native ECMAScript modules - the first overview