11

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.

Undistraction
  • 42,754
  • 56
  • 195
  • 331

2 Answers2

18

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]',
  },
  // ...
}
Nelson Yeung
  • 3,262
  • 3
  • 19
  • 29
0

Looks this plugin transpile-webpack-plugin resolves the problem. You may set it up as below:

const TranspilePlugin = require('transpile-webpack-plugin');

module.exports = {
  entry: './src/alpha/beta.js',
  output: {
    path: __dirname + '/lib',
  },
  plugins: [new TranspilePlugin({ longestCommonDir: './src' })]
};

Then, the plugin collects all the files directly or indirectly imported by ./src/alpha/beta.js and generates output files separately in lib. It is file-to-file transpiling which preserves both file names and directory structure.

Btw, if specifying multiple named entries and output filename [name] in webpack config, the output will be multiple bundles every of which contains all the direct and indirect imports and can't interact with each other. It's not the same as the babel command actually...

Neha Soni
  • 3,935
  • 2
  • 10
  • 32
Cg Lee
  • 143
  • 1
  • 1
  • 8