Using multiple entry points in Webpack

If you’re looking to add multiple entry points in React, it’s likely you’re maintaining multiple pages or applications (this is the intent of the feature).

To do this, you need to change the syntax you use in the “entry” part of the webpack.config a bit, as well as the filenames you make (output/filename):

var path = require("path");
var webpack = require("webpack");
 
module.exports = {   
  entry: { 
    ssl_search: "./src/ssl_search/Entry.js",
    lecture_search: "./src/lecture_search/Entry.js"
  },
  output: {
    path: __dirname,
    filename: "public/search/[name].bundle.js"
  },
  devtool: "#source-map",
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },     
      {
        test: /\.jsx|\.js$/,
        loaders: ["babel"],
        include: path.join(__dirname, "src")
      }
    ]
  }
};

Then, to use these, you need to change the filenames you import in your HTML pages, to reference each entry point directly:

<script type="text/javascript" src="/public/search/lecture_search.bundle.js"></script>

When I set this up, I make a simple Entry.js file that is a stub into each application (each page is similar, but with different configuration). For instance, for one application, this is what it looks like:

"use strict";
 
let start = require("../SearchClient.js").start;
let App = require("./SSLSearchApp.jsx").App;
 
start(App);

The App page is the React component that renders the page. The “start” function looks like the below. Note this is specific to my application, and needs to work both server and client side, if you’re doing server side rendering (I’m using feature detection to swap methods). The “object.assign” bit gets you around a V8 defect that surfaces in React 15.

"use strict";
 
delete Object.assign;
Object.assign = require("object.assign").shim();
 
let searchEvents = require("./SearchEvents.js");
let ReactDOM = require("react-dom");
let React = require("react");
 
function start(App) {
  if (!!window.initialUrl) {
    searchEvents.initialRender(
      window.initialUrl,
      (searchResults) => {
        let AppWrapper = React.createClass({
          render: function () {
            return (
              <App 
                server={false}
                routeParams={window.routeParams} 
                searchResults={searchResults} />);
          }
        });
 
        let domNode = document.getElementById("container");
 
        ReactDOM.render(
          React.createElement(AppWrapper),
          domNode
        );
      }    
    );    
  } else {
    render();
  }
}
 
exports.start = start;

One Reply to “Using multiple entry points in Webpack”

Leave a Reply

Your email address will not be published. Required fields are marked *