简体   繁体   English

使用Webpack将es6类​​构建为单独的文件

[英]Building es6 classes into separate files with webpack

I'm, trying to set up a repository for my commonly used react components that I could then add to my projects like component-kit and reuse these, so something like 我正在尝试为常用的React组件建立一个存储库,然后可以将其添加到诸如component-kit项目中并重复使用这些component-kit ,所以类似

import MyComponent from 'component-kit/MyComponent';

At the moment I have following project structure: 目前,我具有以下项目结构:

component-kit/
   src/
     MyComponent/
       index.js
     index.js
   package.json
   webpack.config.js

index.js file imports all components in the following way: index.js文件通过以下方式导入所有组件:

import('./MyComponent');

And I then use webpack to build each of these imports into separate files, here is my config as per code splitting docs available here 然后,我使用webpack将这些导入中的每一个构建到单独的文件中,这是根据此处提供的代码拆分文档的配置

const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'dist.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env', 'es2015', 'stage-0', 'react'],
            plugins: ['syntax-dynamic-import']
          }
        }
      }
    ]
  }
};

At the moment this outputs 2 files dist.js and 0.dist.js and I can't figure out how to set this up in a way where files outputet have component names ie MyComponent.js so I can than include it like mentioned above. 目前,这将输出2个文件dist.js0.dist.js ,我不知道如何设置输出文件具有组件名称即MyComponent.js因此我可以像上面提到的那样包含它。 ideally these would not include react into their build as it will always be present in parent components. 理想情况下,它们将不包含任何反应,因为它将始终存在于父组件中。

I think it is better to use babel for this purpose if you use a babel based language like JSX. 我认为,如果您使用像JSX这样的基于babel的语言,则最好使用babel达到此目的。
Take a look at this material-ui npm script. 看一下这个 material-ui npm脚本。
Webpack is generally good for bundling production applications I think. 我认为Webpack通常适合捆绑生产应用程序。
You can get file names using node fs and dynamically generate entries like This answer if you insist on using webpack. 如果您坚持使用webpack,则可以使用节点fs获取文件名,并动态生成类似此答案的条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM