简体   繁体   中英

Webpack - How to bundle/require all files of a folder (subfolder)

I am trying to see if there is a shorter way of running webpack bundles, and also why my loaders do not work.

Here is my code:

module.exports = {
context: path.join(__dirname, 'dist'),
entry: ['./ES6bundle.js', './jQuery.js'],
output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'dist')
}
};
// module: {
//     loaders: [{
//         test: /\.js?$/,
//         exclude: /node_modules/,
//         loader: 'babel-loader',
//         query: {
//             presets: ['env']
//         }
//     }]
// };

The module.exports works but when I run the loaders I get errors.

My other question is about consolidating multiple entries into one file.
The project I am working on has many JS files, and I was wondering if there was a shortcut for multiple entries. Instead of typing out multiple entries' filenames, can I grab all JS files in the same folder or have a JS file to require them all?

Let me know if this makes sense or not. I am relatively new to programming. Thanks!

Regarding the second part of your question:

can I grab all JS files in the same folder or have a JS file to require them all

You can have one entry file and in there you do:

module.exports = {
    context: path.join(__dirname, 'dist'),
    entry: ['./jQuery.js', './allJsFilesOfFolder.js'],

allJsFilesOfFolder.js:

require.context("../scripts/", true, /\.js$/);

This will bundle all scripts inside scripts and all its subfolders .

You need to install @types/webpack-env to have context at your hand.

Specify false if you want to bundle only the scripts in the scripts folder.

You can do the same with other resources like images, you only have to adapt the regex

Copy @Legends comment as answer here.

have no experience with vue files, but as I said you can bundle not only js files, but also image files, for example the regex for image files would be: /.(png|ico|svg|jpg|gif)$/.

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