0
0

More than 3 years have passed since last update.

vue + webpack の非nuxt環境でコンポーネントをまるっとrequireする

Posted at

タイトルのまんまです。 require.context を利用して、或るディレクトリ配下にあるコンポーネントファイル(.vue)をまるっとrequireしたい。

エントリーファイル(main.js)に次のように記述します。

function requireAll (context) {
  const components = {}
  context.keys().forEach((_path) => {
    const name = _path.split('/')
      .filter((s) => !/^\./.test(s))
      .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
      .join('')
      .replace(/\.vue$/, '')
    components[name] = context(_path).default
  })
  return components
}

const components = requireAll(require.context('./pages', true, /\.vue$/))

components にはパス名がPascalCaseされた名前をキーにしたコンポーネントが格納されるので、あとは環境にあわせて煮るなり焼くなり好きにしましょう。

new Vue({
  el: '#app',
  components
})

プロジェクトの都合でnuxtを導入できなかったりする時などに出番があるやもしれません。

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