簡體   English   中英

嘗試創建一個插件來自動加載 nuxt.js 中的所有組件

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

我嘗試在 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 .: 一旦問題解決,我將用正則表達式替換函數。

在您的 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)
})

然后只需將其導入您的布局 .vue 文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM