我正在尝试使用 React 和 Webpack (3.4.1) 构建一个“组件库”。这个想法是让一个 React 应用程序使用React Cosmos以交互方式构建和探索可重用组件的“库”。该 repo 还将有一个build
任务,它将这些组件编译成一个可以推送(到 Github 和/或 NPM)的文件。并且该文件/包可以导入到其他项目中以访问可重用组件。
注意/更新- 对于那些想自己尝试的人,我已将(非功能性)包发布到 NPM:https ://www.npmjs.com/package/rs-components 。只是
yarn add
你的项目(可能)遇到同样的问题。
我已经完成了 90% 的工作——React Cosmos 正在正确显示组件,并且我的构建任务 ( rimraf dist && webpack --display-error-details --config config/build.config.js
) 正在运行且没有错误。但是,当我将 repo 作为一个包从 Github 拉入另一个项目时,我遇到了错误。
这些错误似乎源于 Webpack 没有正确导入我的组件库的依赖项。当我在构建时不缩小/破坏库时,我在导入时看到的第一个错误是:
TypeError: React.Component is not a constructor
事实上,如果我放入一个调试器并检查它,React 就是一个空对象。
如果我通过(作弊和)直接在node_modules
( const React = require('../../react/react.js')
) 中编译/下载的文件中导入 React 来解决这个问题,则不会发生该错误,但随后我遇到了与prop-types
库导入失败有关的类似错误:
TypeError: Cannot read property 'isRequired' of undefined
因此,似乎虽然我的代码被正确提取,但组件库文件中的导入似乎没有被正确捆绑。
以下是大部分相关文件:
配置/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;
一个示例组件:
复选框.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);
Webpack 构建任务的“入口”文件webpack --config config/build.config.js
(
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
}
};
最后,以下是编译后的未丑化 JS 中“导入”似乎未正确定义的变量的行:
var React = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_prop_types__ = __webpack_require__(3);
让我知道是否还有其他可以帮助解决此问题的方法。超级困惑,所以我非常感谢任何帮助。
谢谢!
编辑
一堆东西似乎是正确导入的。当我在编译文件中抛出一个调试器并__webpack_require__(n)
尝试尝试一大堆不同n
的 s 时,我看到了不同的导入模块。不幸的是,React 和 PropTypes 似乎不在其中。