LoginSignup
0
1

More than 1 year has passed since last update.

複数のモジュールをfor文によって一括で動的にimportする(JavaScript)

Posted at
script.js
const moduleNames = ['module1', 'module2', 'module3'];
const modules = {};

for(let i=0;i<moduleNames.length;i++){
  import('./modules/' + moduleNames[i] + '.js')
    .then((module)=>{
      modules[moduleNames[i]] = module.default;
    });
}

ただしフォルダ構成が次のようになっているとする。
module1.js, module2.js, module3.jsたちはexport defaultしている。

root/
  ┣ script.js
  ┗ modules/
      ┠ module1.js
      ┠ module2.js
      ┗ module3.js

動的インポートと呼ばれるものを使う。
静的インポートとの違いは、Promiseで返って来るところ。

静的インポートはトップレベルのスコープでしか使えない。
for文の中で静的インポートをしようとするとUncaught SyntaxError: Unexpected identifierのエラーが出る。
なんとかforで回せないかとこねくり回したらできた。

ただし参考ページ import - JavaScript - MDN Web Docs
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/import
には、

動的インポートは必要な場合にのみ使用してください。

とある。こういう使い方は非推奨なのかな。

0
1
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
0
1