Search code examples
javascriptreactjswebpackcode-splitting

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

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:

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

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 i.e. MyComponent.js so I can than include it like mentioned above. ideally these would not include react into their build as it will always be present in parent components.


Solution

  • I think it is better to use babel for this purpose if you use a babel based language like JSX.
    Take a look at this material-ui npm script.
    Webpack is generally good for bundling production applications I think.
    You can get file names using node fs and dynamically generate entries like This answer if you insist on using webpack.