为通配符条目文件创建动态命名的输出

Creating dynamically named outputs for wildcarded entry files

如何保留文件夹结构和文件名?

通配符 **/*.js 的保存很重要。我想让它保持动态,而不是手动添加新组件。

文件夹结构

|-- src
    |-- components
        |-- lightbox
            |-- index.js
        |-- carousel
            |-- index.js
        |-- modal
            |-- index.js

文件夹和文件的预期输出:
应保留文件夹结构和原始文件名!

|-- build
    |-- components
        |-- lightbox
            |-- index.js
        |-- carousel
            |-- index.js
        |-- modal
            |-- index.js   

使用当前的 webpack 配置,我得到以下结果:
所有组件都已放在一个 .js 文件中,应该 是.

|-- build
    |-- components
        |-- main.js     

我的 webpack 配置

entry: $.glob.sync('./src/components/**/*.js'),
mode: 'development',
output: {
  filename: '[name].js'
},
module: {
  rules: [{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
    }
  }]
}

webpack docs 声明:

Note this option is called filename but you are still allowed to use something like 'js/[name]/bundle.js' to create a folder structure.

所以如果你的 webpack 的输出文件名是 dirA/fileA,它将被输出到

|-- dist
    |-- dirA
         |-- fileA.js

但是你还说

The preservation of the wildcard **/*.js is important

我们可以利用您可以通过将对象传递给 webpack 的条目来命名文件这一事实。

我假设您正在使用节点的 glob$.glob.sync 让我有点困惑),它的输出是一组与 glob 模式匹配的路径。然后,我们只需要把这个数组修改成一个对象,格式如下:

//from    
["./src/dirA/fileA.js", "./src/dirB/fileB.js"]
// to
{ 
  "dirA/fileA": "./src/dirA/fileA.js",
  "dirB/fileB": "./src/dirB/fileB.js",
}

这是一个简单的例子:

const glob = require('glob');

const entry = glob.sync('./src/**/*.js').reduce((entry, path) => {
  const pathName = path.replace(/(\.\/src\/|\.js)/g, ''); // remove `./src/`, `.js`
  entry[pathName] = path;
  return entry;
}, {});

module.exports = {
  mode: 'development',
  entry,
  output: {
    filename: '[name].js'
  }
}