L
L
lavezzi12016-08-08 18:48:48
JavaScript
lavezzi1, 2016-08-08 18:48:48

How to import all files from subfolders of a specific extension?

Hello! Application on vue.js is multi-page. Each page has its own entry file, you need to go through and import all these files from all folders.
getEntry.js

var path = require('path');
var glob = require('glob');

module.exports = getEntry;

function getEntry(sourcePath) {
  var entrys = {};
  var basename;
  glob.sync(sourcePath).forEach(function (entry) {
    basename = path.basename(entry,path.extname(entry));
    entrys[basename] = entry;
  });
  return entrys;
}

webpack.config.js
var getEntry = require('./bin/getEntry.js');
var entrys = getEntry('./app/src/views/**/*.js');

module.exports = {
  entry: entrys,
  .....
}

Now it works if the path is like this
./app/src/views/index/index.js
or
./app/src/views/about/about.js

I would like to be able to create a 'deep' structure for example
./app/src/views/dashboard/index/index.js
./app/src/views/dashboard/control/control.js

How to decide? A sample code would be welcome. Thank you very much.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Gromov, 2016-08-09
@lavezzi1

To keep the structure, you need to specify the corresponding output.path for each set of entries. This is only possible if you export an array from configs:

var path = require('path');
var glob = require('glob');

var files = glob.sync('./app/src/views/**/*.js');
var dirs = getDirs(files);

var configs = [];

for (var dirname in dirs) {
    var files = dirs[dirname];

    configs.push({
        entry: getEntries(files),
        output: {
            path: dirname.replace('app/src/views', 'build'),
            filename: '[name].js'
        }
    });
}

module.exports = configs;



function getDirs(files) {
    var dirs = {};

    files.forEach(function (file) {
        var dirname = path.dirname(file);

        if (!dirs[dirname]) {
            dirs[dirname] = [];
        }

        dirs[dirname].push(file);
    });

    return dirs;
}

function getEntries(files) {
    var entries = {};

    files.forEach(function (file) {
        var name = path.basename(file, path.extname(file));

        entries[name] = file;
    });

    return entries;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question