简体   繁体   English

尝试创建一个插件来自动加载 nuxt.js 中的所有组件

[英]Try to create a plugin to auto load all components in nuxt.js

I try to load and define globally all my components under nuxt.js.我尝试在 nuxt.js 下全局加载和定义我的所有组件。

When I try to load the *.vue file, I get the following error: "Cannot find module ....".当我尝试加载 *.vue 文件时,出现以下错误:“找不到模块 ....”。

But the file is present in the specified location...但是该文件存在于指定位置...

Here is the loading plugin :这是加载插件:

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 .: I will replace functions by a regular expression once the problem is solved. PS .: 一旦问题解决,我将用正则表达式替换函数。

Make a js file with this content in your components folder:在您的 components 文件夹中使用此内容制作一个 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)
})

then simply import that in your layout .vue file.然后只需将其导入您的布局 .vue 文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM