Попробуйте создать плагин для автоматической загрузки всех компонентов в nuxt. js - PullRequest
0 голосов
/ 17 февраля 2020

Я пытаюсь загрузить и определить все мои компоненты глобально в nuxt. js.

Когда я пытаюсь загрузить файл *. vue, я получаю следующую ошибку: «Не удается найти модуль. ... ".

Но файл присутствует в указанном месте ...

Вот плагин загрузки:

import Vue from 'vue'
import fs from 'fs'
import path from 'path'

const componentDirectory = `.${path.sep}src${path.sep}components`;
const componentTypes = ['atom','molecule','organism'];

function getComponentType(componentName) {

    let compGroup = ( componentName || '' ).toLowerCase().split('.');

    if (compGroup.length < 3 || compGroup[ compGroup.length - 1 ] !== 'vue' ) {
        return null;
    }

    return compGroup[ compGroup.length - 2 ];
}

function allowedComponentType(componentFileName) {
    return componentTypes.indexOf(getComponentType(componentFileName)) !== -1;
}

// List all files in a directory in Node.js recursively in a synchronous fashion
var walkSync = function(dir, filelist) {
    var files = fs.readdirSync(dir);
    filelist = filelist || [];

    files.forEach(function (file) {        
        if (fs.statSync(dir + path.sep + file).isDirectory()) {
            filelist = walkSync(dir + path.sep + file, filelist);
        } else if (allowedComponentType(file) ) {
            filelist.push(dir + path.sep + file);
        }
    });

    return filelist;
};

walkSync(componentDirectory).forEach(componentFileName => {
    try {
        let componentPath = path.resolve(path.resolve(), componentFileName);

        console.log('Component name : ', componentPath)
        const component = require(componentPath).default;
        Vue.component(component.name, component);
    }
    catch (e) {
        console.log('Error : ' , e )
    }
});

PS.: Я заменю функции регулярным выражением, как только проблема решена.

1 Ответ

0 голосов
/ 17 февраля 2020

Создайте файл js с этим содержимым в папке компонентов:

import Vue from 'vue'

const requireComponent = require.context('@/components', true, /\.vue$/)

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)
  const componentName = fileName
    .replace(/^\.\//, '')
    .replace(/\.\w+$/, '')
    .replace(/\//g, '-')
    .toLowerCase()
  Vue.component(componentName, componentConfig.default || componentConfig)
})

, затем просто импортируйте его в свой макет. vue файл.

...