LoginSignup
8
5

More than 5 years have passed since last update.

JavaScriptでdynamic import 使えばオンラインエディタでもmoduleをimportできる

Last updated at Posted at 2018-02-24

背景

ブラウザで動くJavaScriptのオンラインエディタでモジュールを開発して, それを共有して作業を進められないか考えていました。オンラインエディタでJavaScriptを実行するときはFunctionコントラクタでエディタの中に書いたコードを実行します。しかし、普通のimportはJavaScriptのファイルの冒頭に書いて、静的に読み込まなくてはならないため、Functionコントラクタの中でimportはできません。JavaScriptでもpythonのようにいつでもimportできればいいのにと思っていました。

そんなある日、tonkotsuboy_comさんの記事を発見しました。

Chrome 63以降で使えるJavaScriptのdynamic import(動的読み込み)

おぉ、これでいける!!tonkotsuboy_comさんありがとうございます。
きっとこれでJavaScriptでデータ処理するコードを開発するのが加速すると思います。

方法

tonkotsuboy_comさんが書いてくださった方法そのままでいけます。複数のmoduleをインポートすることを考えると、async & awaitで書くのが良いとおもいます。
export_test1.jsとexport_test2.jsをネットから見える場所においておけば、async付けた関数の中でawait importで順番に読み込めば、moduleで読み込んだ関数を使えます。

export_test1.js
export const func1 = (value) =>{
  console.log('export_test1.js func1')
  return value*2
}

export const func2 = (value) =>{
  console.log('export_test1.js func2')
  return value**2
}
export_test2.js
export const func1 = (value) =>{
  console.log('export_test1.js func1')
  return value*2
}

export const func2 = (value) =>{
  console.log('export_test1.js func2')
  return value**2
}
import_test1.js
const main = async ()=>{
  const module1 = await import("/jsnote/sample/public/module/export_test1.js")
  const module2 = await import("/jsnote/sample/public/module/export_test2.js")
  console.log(module1.func1(3))
  console.log(module1.func2(3))
  console.log(module2.func1(3))
  console.log(module2.func2(3))
}
main()

実行の様子

jsnoteのレジスタでexport_test1.jsとexport_test2.jsを登録して、import_test1.jsで使ってみました。
Imgur

Chromeの最新版をお使いの方は、github pagesで動くこちらで試してみてください

Imgur

jsnoteでレジスタに自分のmoduleを登録してをお使いになられる方はgithubからcloneしてご自分の環境で動かしてみてください。

リポジトリへのリンク
https://github.com/Toyoharu-Nishikawa/jsnote

使い方へのリンク
https://qiita.com/Toyoharu-Nishikawa/items/044d53974c42bc635f0f

8
5
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
8
5