2

I'm trying to build a "component library" using React and Webpack (3.4.1). The idea is to have one React app, using React Cosmos, to interactively build and explore a "library" of reusable components. That repo will also have a build task, which compiles just those components into a file that can be pushed up (to Github and/or NPM). And that file/package can be imported into other projects to get access to the reusable components.

NOTE/UPDATE - For those who want to try this out on their own, I've published the (non-functional) package to NPM: https://www.npmjs.com/package/rs-components. Just yarn add it to your project to (likely) bump into the same issues.

I've got 90% of this working -- React Cosmos is displaying the components correctly, and my build task (rimraf dist && webpack --display-error-details --config config/build.config.js) is running without error. However, when I pull the repo into another project as a package from Github, I run into errors.

The errors seem to stem from Webpack not importing the dependencies of my component library correctly. When I don't minify/mangle the library on build, the first error I see on import is this:

TypeError: React.Component is not a constructor

In fact, if I throw in a debugger and inspect it, React is an empty object.

If I work around that by (cheating, and) importing React directly in the compiled/downloaded file in node_modules (const React = require('../../react/react.js')), that error doesn't occur, but then I run into a similar one, related to a failed import of the prop-types library:

TypeError: Cannot read property 'isRequired' of undefined

So it seems that while my code is getting pulled in correctly, the imports in the component-library files don't seem to be correctly bundled in.

Here are most of the relevant files:

config/build.config.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
  entry: path.resolve(__dirname, '../src/index.js'),
  devtool: false,
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].js'
  },
  resolve: {
    modules: [
      path.resolve(__dirname, '../src'),
      'node_modules'
    ],
    extensions: ['.js']
  },
  module: {
    rules: []
  }
};

// JavaScript
// ------------------------------------
config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    query: {
      cacheDirectory: true,
      plugins: [
        'babel-plugin-transform-class-properties',
        'babel-plugin-syntax-dynamic-import',
        [
          'babel-plugin-transform-runtime',
          {
            helpers: true,
            polyfill: false, // We polyfill needed features in src/normalize.js
            regenerator: true
          }
        ],
        [
          'babel-plugin-transform-object-rest-spread',
          {
            useBuiltIns: true // We polyfill Object.assign in src/normalize.js
          }
        ]
      ],
      presets: [
        'babel-preset-react',
        ['babel-preset-env', {
          targets: {
            ie9: true,
            uglify: false,
            modules: false
          }
        }]
      ]
    }
  }]
});

// Styles
// ------------------------------------
const extractStyles = new ExtractTextPlugin({
  filename: 'styles/[name].[contenthash].css',
  allChunks: true,
  disable: false
});

config.module.rules.push({
  test: /\.css$/,
  use: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]'
});

config.module.rules.push({
  test: /\.(sass|scss)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          sourceMap: false,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions']
            },
            discardComments: {
              removeAll: true
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: false
          }
        }
      },
      {
        loader: 'postcss-loader',
        options: {
          autoprefixer: {
            add: true,
            remove: true,
            browsers: ['last 2 versions']
          },
          discardComments: {
            removeAll: true
          },
          discardUnused: false,
          mergeIdents: false,
          reduceIdents: false,
          safe: true,
          sourceMap: true
        }
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: false,
          includePaths: [
            path.resolve(__dirname, '../src/styles')
          ]
        }
      }
    ]
  })
});
config.plugins = [extractStyles];

// Images
// ------------------------------------
config.module.rules.push({
  test: /\.(png|jpg|gif)$/,
  loader: 'url-loader',
  options: {
    limit: 8192
  }
});

// Bundle Splitting
// ------------------------------------
const bundles = ['normalize', 'manifest'];

bundles.unshift('vendor');
config.entry.vendor = [
  'react',
  'react-dom',
  'redux',
  'react-redux',
  'redux-thunk',
  'react-router'
];

config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: bundles }));

// Production Optimizations
// ------------------------------------
config.plugins.push(
  new webpack.LoaderOptionsPlugin({
    minimize: false,
    debug: false
  }),
  new webpack.optimize.UglifyJsPlugin({
    sourceMap: false,
    comments: false,
    compress: {
      warnings: false,
      screw_ie8: true,
      conditionals: true,
      unused: true,
      comparisons: true,
      sequences: true,
      dead_code: true,
      evaluate: true,
      if_return: true,
      join_vars: true
    }
  })
);

module.exports = config;

An example component:

Checkbox.js

import React from 'react';
import { connect } from 'react-redux';
import { map } from 'react-immutable-proptypes';
import classnames from 'classnames';

import { setCheckboxValue } from 'store/actions';

/**
 * Renders a Redux-connected Checkbox with label
 *
 * @param {string} boxID - Unique string identifier of checkbox
 * @param {string} name - Label text to display
 * @param {function} dispatch - Redux dispatch function
 * @param {Immutable.Map} checkboxes - Redux checkboxes Map
 * @param {string[]} className - Optional additional classes
 *
 * @returns {React.Component} A checkbox with globally-tracked value
 */
export function CheckboxUC ({ boxID, name, dispatch, checkboxes, className }) {
  const checked = checkboxes.get(boxID);
  return (
    <label className={ classnames('checkbox rscomp', className) } htmlFor={ boxID }>
      <input
        className="checkable__input"
        type="checkbox"
        onChange={ () => {
          dispatch(setCheckboxValue(boxID, !checked));
        } }
        name={ name }
        checked={ checked }
      />
      <span className="checkable__mark" />
      <span className="checkable__label">{ name }</span>
    </label>
  );
}

const mapStateToProps = state => ({
  checkboxes: state.checkboxes
});

const { string, func } = React.PropTypes;
CheckboxUC.propTypes = {
  boxID: string.isRequired,
  name: string.isRequired,
  checkboxes: map.isRequired,
  dispatch: func,
  className: string
};

export default connect(mapStateToProps)(CheckboxUC);

And the "entry" file for the Webpack build task (webpack --config config/build.config.js), which is meant to export only the components that should be accessible by an application importing this package:

src/index.js

import BaseForm from 'components/BaseForm';
import Checkbox from 'components/Checkbox';
import Dropdown from 'components/Dropdown';
import Link from 'components/Link';
import RadioGroup from 'components/RadioGroup';

import { validators } from 'components/BaseForm/utils';

export default {
  BaseForm,
  Checkbox,
  Dropdown,
  Link,
  RadioGroup,
  utils: {
    validators
  }
};

Lastly, here are the lines in the compiled un-uglified JS that are "importing" the variables that seem improperly undefined:

  • var React = __webpack_require__(1);
  • /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_prop_types__ = __webpack_require__(3);

Let me know if there's anything else that would help sort this out. Super confused, so I really appreciate any assistance.

Thanks!

EDIT

A bunch of things do seem to be imported correctly. When I throw a debugger in the compiled file and take a look at __webpack_require__(n) trying a whole bunch of different ns, I see different imported modules. Unfortunately, React and PropTypes don't seem to be among them.

Sasha
  • 6,224
  • 10
  • 55
  • 102

1 Answers1

0

Try changing your entry to:

entry: { 'bundle': path.resolve(__dirname, '../src/index.js')}

And the your CommonsChunkPlugin config to :

config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' }));

And then check the vendor.js file for the stuff under the vendor entry.

If your goal was to put everything under one file, just leave out CommonsChunkPlugin.

Hill
  • 781
  • 1
  • 7
  • 5