S
S
shasoft2019-02-12 17:47:20
Web development
shasoft, 2019-02-12 17:47:20

How to dynamically register Vue.component components from an external directory?

I made automatic registration of components according to the documentation and this code works:

import Vue from "vue";
import kebabCase from 'lodash/kebabCase'
//
Vue.config.productionTip = false
// Подключить и зарегистрировать компоненты из директории .components
const requireComponent = require.context(
  // Относительный путь до каталога компонентов
  './components',
  // Обрабатывать или нет подкаталоги
  true,
  // Регулярное выражение для определения файлов базовых компонентов
  /\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Получение конфигурации компонента
  const componentConfig = requireComponent(fileName)

  // Получение имени компонента в PascalCase
  const componentName = kebabCase(
      // Удаление из начала `./` и расширения из имени файла
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
  )
  /* eslint-disable no-console */
  console.log('fileName',fileName,'=>',componentName);
  /* eslint-enable no-console */
  // Глобальная регистрация компонента
  Vue.component(
    componentName,
    // Поиск опций компонента в `.default`, который будет существовать,
    // если компонент экспортирован с помощью `export default`,
    // иначе будет использован корневой уровень модуля.
    componentConfig.default || componentConfig
  )
})

However, if you specify the directory './../../app/Modules/Template/vue', This directory does not work , it does not work anymore. Using the method of scientific poke, I found out that the code does not like the directory of the form ../../ , but I can’t figure out how to get around this because I can’t find what kind of restriction it is.
Maybe someone met and knows how to win it?
ps I generally need the components to be searched for in the specified directories and automatically registered. Is there a plugin or settings for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grinat, 2019-02-12
@grinat

Perhaps ../../ is already outside the folder where node_modules, package.json, etc. are. Webpack can be made to work with this configuration, but you will have to manually specify all the paths to it, plus there may be problems with third-party plugins and module loading.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question