简体   繁体   中英

Split react code into react library bundle and components bundle

I have the following configuration for webpack (integrated with grunt):

var path = require('path');
var webpack = require('webpack');

module.exports = {
  run_webpack: {
    entry: {
      react: "./static/src/jsx/react.jsx",
      index: "./static/src/jsx/index.jsx"
    },
    output:{
        path: "./static/js/",
        filename: "[name].bundle.js",
    },
    module: {
      loaders: [
        {
          test: /.jsx?$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: {
            presets: ['es2015', 'react']
          }
        }
      ]
    },
  },
};

My react.jsx and index.jsx:

// react.jsx
var React = require('react');
var ReactDOM = require('react-dom');

// index.jsx
ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('app')
);

And then I embed those bundles into html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Kanban app</title>
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type="text/javascript" src="{% static 'js/react.bundle.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/index.bundle.js' %}"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

My problem that it doesn't render <h1>Hello, world!</h1> . The error is 'ReactDOM is not defined'. How can I overcome that issue? It works when I merge react.jsx and index.jsx , but still would like to keep them separately to accelerate code compiling.

Your index.jsx simply has to depend on react and react-dom for the code to work. To achieve what you want, you can load them using externals , though. You could set up something like this for the target generating index :

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

This way webpack won't bundle react and react-dom to your index bundle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM