Webpack2,如何从构建中排除反应和反应dom [英] Webpack2, how to exclude react and react dom from build

查看:122
本文介绍了Webpack2,如何从构建中排除反应和反应dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My goal is to create a module for a react components library made in ES6 using webpack.

我正在使用:

  • webpack:"2.1.0-beta.25"
  • 反应:"15.4.1"

我需要将reactreact-dom分配为peerDependencies,这样开发人员就不会下载它.

I need to assign react and react-dom as peerDependencies so it doesn't get downloaded by the developer.

这是我的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 #externals https://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', }

2. externals: { react: 'react', '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).(…)

所以我想知道,文档对此不是很清楚.

So I wonder, the documentation isn't very clear on that.

在2017年12月(最多2018年1月)中,如何将ReactReactDOM从捆绑中排除?

In december 2017, january 2018 at maximum, how can I exclude React and ReactDOM from being bundled ?

推荐答案

可以通过

  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首先进行反应,然后在应用程序中

So now webpack will build two files bundle.app.js and bundle.reactjs.js. Include them in your index.html first react then app.

这篇关于Webpack2,如何从构建中排除反应和反应dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆