乐闻世界logo
搜索文章和话题

How to add wildcard mapping in entry of webpack

1个答案

1

Using wildcards in Webpack to automatically resolve multiple entry files is a common requirement, especially in large projects where manually adding each file becomes cumbersome. We can achieve this functionality by using the glob library to match file paths with specific patterns.

First, you need to install glob, which can be done via npm or yarn:

bash
npm install glob --save-dev

or

bash
yarn add glob --dev

Next, you can use glob in your webpack.config.js file to search and generate entry points. Here is an example of how to do it:

javascript
const glob = require('glob'); const path = require('path'); module.exports = { entry: glob.sync('./src/**/*.js').reduce((acc, path) => { const entry = path.replace(/^.*[\/]/, '').replace('.js', ''); acc[entry] = path; return acc; }, {}), output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), }, // Other configurations... };

This code does the following:

  1. Use glob.sync('./src/**/*.js') to search for all .js files under the src folder.
  2. Use the reduce function to convert these file paths into an object where each file path becomes a separate entry point.
  3. The entry variable is generated based on the file path, removing the path and .js extension to serve as the filename for Webpack output.
  4. In the output configuration, the [name] placeholder represents the name of each entry, resulting in filenames such as entryName.bundle.js.

Using this approach, you can manage a large number of entry files flexibly without having to add them one by one manually. This can significantly improve efficiency in real-world work, especially when dealing with large and complex projects.

2024年7月23日 12:50 回复

你的答案