Webpack2,如何排除反应并从构建中做出反应

时间:2016-12-27 17:29:29

标签: reactjs webpack webpack-dev-server jsx react-dom

我的目标是使用webpack为ES6中的反应组件库创建一个模块。

我正在使用:

  • webpack:“2.1.0-beta.25”
  • 反应:“15.4.1”

我需要将reactreact-dom指定为peerDependencies,以便开发人员不会下载它。

这是我package.json的相关部分:

"peerDependencies": {
  "react": "15.4.1"
},
"dependencies": {
  "chalk": "1.1.3",
  "compression": "1.6.2",
  "cross-env": "3.1.3",
  "immutable": "3.8.1",
  "invariant": "2.2.1",
  "lodash": "4.16.4",
  "minimist": "1.2.0",
  "sanitize.css": "4.1.0",
  "warning": "3.0.0",
  "react-onclickoutside": "5.8.3",
  "styled-components": "1.1.2",
  "classnames": "2.2.5"
},
"devDependencies": {
  "react": "15.4.1",
  "react-dom": "15.4.1",

根据https://webpack.github.io/docs/configuration.html#externalshttps://webpack.github.io/docs/library-and-externals.html

我尝试过以下配置:

1

externals: {
  react: {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react'
  },
  'react-dom': {
    root: 'ReactDOM',
    commonjs2: 'react-dom',
    commonjs: 'react-dom',
    amd: 'react-dom'
  }
},

2。     外部:{       反应:'反应',       'react-dom':'react-dom',     }

3

 externals: {
  react: 'React',
  'react-dom' : 'ReactDOM',
 }

4

externals: {
  react: 'umd react',
  'react-dom' : 'umd react-dom'
}

5

    externals: {
        // Use external version of React
        "react": "React",
        "react-dom": "ReactDOM"
    },

我总是有这个错误:

 Dynamic page loading failed Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://bf.me/react-refs-must-have-owner).(…)

所以我想知道,文档不是很清楚。

2017年12月,即2018年1月,我如何排除ReactReactDOM被捆绑?

3 个答案:

答案 0 :(得分:2)

这里是我的webpack配置,它只是基础,因为我正在处理一个较小的项目

const {resolve} = require('path');

module.exports = {
  entry: './demo/react/main.jsx',
  output: {
    filename: 'bundle.js',
    path: resolve(__dirname, 'demo/react/dist')
  }
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]

      }
    ]
  },
  externals: {
    // Use external version of React
    'react': 'React',
    'react-dom': 'ReactDOM'
  }
};

答案 1 :(得分:0)

编辑:

在你试过的例子中没有看到这个。正如OP所提到的,以下JSON配置对它们不起作用。

GitHub issue #1275开始,试试这个:

{
    externals: {
        // Use external version of React
        "react": "React",
        "react-dom": "ReactDOM"
    }
}

如果这不起作用,请尝试阅读整个问题页面。有一些建议可能会最终为你效劳。

答案 2 :(得分:0)

可以将一种方式放入单独的文件中,例如reactjs通过

  entry: {
      app:'./src/app.jsx',
      reactjs:[
          'react','react-dom'               ,
      ]
  }

  output: {
    path       : path.join(__dirname, 'public'),
    filename   : 'bundle.[name].js',
    publicPath : '/public/'
  },

 plugins : [
     new webpack.optimize.CommonsChunkPlugin({
        name: 'reactjs',
     })
 ]

现在webpack将构建两个文件bundle.app.jsbundle.reactjs.js。 将它们包含在index.html首先做出反应的应用中。