Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
Undistraction Avatar asked Mar 08 '17 11:03

Undistraction


People also ask

Does Webpack Transpile or compile?

Webpack bundles our code and outputs a transpiled version down to the target as specified in the configuration file. In our webpack configuration file, module rules allow us to specify different loaders, which is an easy way to display loaders.

What is Webpack in ES6?

Webpack is a module bundler that basically allows you to create a variety of different JavaScript files (modules) and then bundle them into a single JavaScript file that runs in the browser.


1 Answers

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]',
  },
  // ...
}
like image 136
Nelson Yeung Avatar answered Oct 06 '22 15:10

Nelson Yeung