使用Webpack作为独立文件传输ES6 [英] Using Webpack To Transpile ES6 as separate files

查看:152
本文介绍了使用Webpack作为独立文件传输ES6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将webpack配置为执行以下操作:

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

babel src --watch --out-dir lib

这样的目录结构如下:

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

将所有文件编译到ES5,并以相同的结构在lib目录下输出它们:

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

我绕过了所有文件路径并将它们作为单独的条目传递,但是似乎webpack在定义输出文件时会忘记"文件的位置. Output.path仅提供[hash]令牌,而Output.file具有更多选项,但仅提供[name][hash][chunk],因此至少看起来不支持这种编译.

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.

为了给我的问题一些上下文,我正在创建一个由React组件及其相关样式组成的npm模块.我正在使用CSS模块,因此我需要一种将JavaScript和CSS都编译到模块的lib目录中的方法.

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.

推荐答案

如果要输出到多个目录,可以将路径用作条目名称.

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

这篇关于使用Webpack作为独立文件传输ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆