Using Webpack To Transpile ES6 as separate files

断了今生、忘了曾经 提交于 2019-12-03 09:45:17

问题


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.


回答1:


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]',
  },
  // ...
}


来源:https://stackoverflow.com/questions/42670633/using-webpack-to-transpile-es6-as-separate-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!