LoginSignup
9
4

More than 5 years have passed since last update.

[ES6] import でディレクトリー内すべてのファイルを読み込む

Posted at

課題

export default しているファイルを読み込むときに以下の書き方をしてたけどhogeディレクトリ全体を一括で読み込みたいと思った。

import hoge1 from './hoge/hoge1.js'
import hoge2 from './hoge/hoge2.js'

hoge/index.js で import 書いてまとめるのもめんどくさい。

方法

これでいいのかわからないけど、以下の方法でやってみたら動いた。

import fs from "fs"
const hoges = {}
fs.readdirSync("./hoge").forEach(async file => {
  const module = await import(`./hoge/${file}`)
  hoges[file] = module.default
})
hoges.hoge1.hogeFunction()

ファイル形式を選択したいときはフィルタリングすればいけるし、サブディレクトリ読み込みたいときは再帰的に読めばいいと思う。

9
4
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
9
4