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

邮差的信 提交于 2021-02-10 03:48:59

问题


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!


回答1:


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




回答2:


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)$/.



来源:https://stackoverflow.com/questions/48990197/webpack-how-to-bundle-require-all-files-of-a-folder-subfolder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!