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"]
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With