javascriptwebpackbabeljstranspilerbabel-loader

Using Webpack To Transpile ES6 as separate files


Is it possible to configure webpack to do the equivalent of:

babel src --watch --out-dir lib

So that a directory structure that looks like this:

- src
  - alpha
    - beta.js
    - charlie
       - delta.js
    - echo.js
    - foxtrot
      - golf
        - hotel.js

Would compile all the files to ES5 and output them in an identical structure under a lib directory:

- lib
  - alpha
    - beta.js
    - charlie
       - delta.js
    - echo.js
    - foxtrot
      - golf
        - hotel.js

I took a pass at globbing all the filepaths and passing them in as separate entries, but it seems that webpack 'forgets' the locations of the files when it comes to defining the output files. Output.path only offers the [hash] token, while Output.file has more options, but only offers [name], [hash] and [chunk], so it appears at least, that this kind of compilation isn't supported.

To give my question some context, I am creating an npm module consisting of React components and their related styles. I am using CSS modules, so I need a way to compile both JavaScript and CSS into the module's lib dir.


Solution

  • If you want to output to multiple directories, you can use the path as the entry name.

    entry: {
      'foo/f.js': __dirname + '/src/foo/f.js',
      'bar/b.js': __dirname + '/src/bar/b.js',
    },
    output: {
      path: path.resolve(__dirname, 'lib'),
      filename: '[name]',
    },
    

    Therefore you can use a function to generate a list of entries for you that satisfy the above:

    const glob = require('glob');
    
    function getEntries(pattern) {
      const entries = {};
    
      glob.sync(pattern).forEach((file) => {
        entries[file.replace('src/', '')] = path.join(__dirname, file);
      });
    
      return entries;
    }
    
    module.exports = {
      entry: getEntries('src/**/*.js'),
      output: {
        path: path.resolve(__dirname, 'lib'),
        filename: '[name]',
      },
      // ...
    }