使用Webpack实现React包 - 只有ReactOwner可以有refs

时间:2016-11-01 16:38:01

标签: node.js reactjs webpack package

我正在创建一个名为Supernova的反应包。所以,在我使用这个包的其他项目中(使用npm链接),这个错误显示在控制台中:

  

只有ReactOwner可以拥有引用。您可能正在为a添加引用   未在组件的render方法中创建的组件,   或者你有多个React加载

的副本

这是我的Supernova webpack配置:

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

module.exports = {
  entry: './src/index.js',

  output: {
    library: 'Supernova',
    libraryTarget: 'umd',
    path: __dirname + '/build',
    filename: 'index.js',
  },

  externals: [
    {
      react: {
        root: 'React',
        commonjs2: 'react',
        commonjs: 'react',
        amd: 'react'
      }
    }
  ],

  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' },
      {
        test:   /\.(scss|sass|css)$/,
        loader: ExtractTextPlugin.extract("style", "css!sass")
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        loader: 'url-loader?limit=10000&name=fonts/[hash].[ext]'
      }
    ]
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  node: {
    Buffer: false
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new ExtractTextPlugin("[name].css"),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ]
}

我的组件方法渲染是:

  render() {
    return (
      <div className="sn-search-box">
        {this.renderSelecteds()}

        <input
          ref="input"
          type="text"
          className="sn-search-box__input"
          placeholder={this.props.label} autoComplete="off"
          onFocus={this.handleInputFocus.bind(this)}
          onBlur={this.handleInputBlur.bind(this)}/>

        <span className="sn-search-box__input--icon"></span>

        {this.state.hasFocus ? this.renderResults() : null}
        {this.renderHelpMessage()}
      </div>
    )
  }

My Supernova package.json

"peerDependencies": {
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  },
  "dependencies": {
    "material-design-icons": "^2.2.3"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.7",
    "babel-cli": "^6.10.1",
    "babel-core": "^6.10.4",
    "babel-jest": "^13.2.2",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.9.0",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "jest-cli": "*",
    "node-sass": "^3.8.0",
    "react-addons-test-utils": "~15.1.0",
    "sass-loader": "^4.0.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.14",
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  },

1 个答案:

答案 0 :(得分:1)

这是因为在同一个项目中加载 React的多个副本。当您的软件包拥有自己的React副本并且您的项目消耗了您的软件包时,会发生这种情况。

当您在dependency(超新星)中将React作为package时,会发生这种情况。您需要将React设为peerDependency。通过这样做,您的包将消耗您项目中的React。如果项目中没有找到React,那么当您执行npm i supernova时,npm将抛出错误/警告。