Here’s how to bundle JS files from an array of paths in webpack:
1. Leverage the entry
property:
Webpack allows defining the entry points for bundling. You can achieve this using an array:
JavaScript
const path = require('path');
module.exports = {
entry: [
path.resolve(__dirname, 'src/file1.js'),
path.resolve(__dirname, 'src/file2.js'),
// Add more paths to your JS files here
],
// ... other configurations
};
This approach explicitly defines each entry point.
2. Utilize dynamic entry points (alternative):
For a more dynamic solution, you can use a function within the entry
property:
JavaScript
const path = require('path');
module.exports = {
entry: () => {
const entries = [
path.resolve(__dirname, 'src/file1.js'),
path.resolve(__dirname, 'src/file2.js'),
// ...
];
return entries.map(filePath => ({
// You can customize the name for each bundle here (optional)
name: '[name]',
path: filePath
}));
},
// ... other configurations
};
This function creates an object array defining entry points with paths and optional names.
Explanation:
path.resolve(__dirname, 'path/to/file.js')
: This resolves the absolute path to your JS files using thepath
module (built-in with Node.js).- In both methods, replace
'src/file1.js'
and'src/file2.js'
with the actual paths to your JS files. - The
output
configuration (not shown here) defines where the bundled file(s) will be placed.
Additional points:
- This approach bundles each file into a separate chunk by default.
- You can configure further bundling behavior using loaders, plugins, and other webpack options.
Resources:
- Webpack Entry: https://webpack.js.org/concepts/entry-points/
- Webpack Loaders: https://webpack.js.org/concepts/loaders/
- Webpack Plugins: https://webpack.js.org/plugins/