简体   繁体   中英

Best way to have all files in a directory be entry points in webpack?

I want to create multiple entry points for a website, which is pretty easily done in Webpack using an object for the entry property, like here .

But as the site grows (and it inevitably will) having to add each entry point seems cumbersome and prone to error. So I'd like to simply point at a directory and say "here are all the entry points."

So I've cooked this up:

var path = require('path');
var fs = require('fs');
var entryDir = path.resolve(__dirname, '../source/js');
var entries = fs.readdirSync(entryDir);
var entryMap = {};
entries.forEach(function(entry){
    var stat = fs.statSync(entryDir + '/' + entry);
    if (stat && !stat.isDirectory()) {
        var name = entry.substr(0, entry.length -1);
        entryMap[name] = entryDir + '/' + entry;
    }
});

module.exports = {
  entry: entryMap,
  output: {
    path: path.resolve(__dirname, '../static/js'),
    filename: "[name]"
  },
...

This works fine, but is there a feature or configuration option in Webpack that would handle this for me?

I think glob is the right way to go here (AFAIK webpack wont do this for you). This is what I ended up with, it will find all files in a directory and create an entry with a name matching the file:

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

module.exports = {
  entry: glob.sync('../source/js/**.js').reduce(function(obj, el){
     obj[path.parse(el).name] = el;
     return obj
  },{}),
  output: {
    path: path.resolve(__dirname, '../static/js'),
    filename: "[name]"
  },
...

adapt the search path to meet your specific needs. It might also be useful to pass in {cwd: someRoot} as the second argument to sync if you have a special scripts directory which will make this the new root of relative path searches.

I have used Glob for this.

 var path = require('path'); var glob = require('glob'); module.exports = { entry: { 'app' : glob.sync('./scripts/**/*.ts*') }, output: { path: path.join(__dirname, '/wwwroot/dist'), filename: '[name].bundle.js', sourceMapFilename: '[name].map' }, module: { rules: [ { test: /\\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, } ] }, resolve: { extensions: [".ts", ".js"] } };

In my opinion, only a little Node skill is needed, and it doesn't have to be that complicated.

const webpack = require('webpack');
const path = require('path');
const fs = require('fs');

const fileNames = fs.readdirSync('./src').reduce((acc, v) => ({ ...acc, [v]: `./src/${v}` }), {});

const config = {
  entry: fileNames,
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]',
  },
};

module.exports = config;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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