How to load an exported function from Webpack into an express application?

I am trying to build an SSR based boilerplate for my project and I am stuck at one place.

Express application uses webpack to compile all the React components in the following way:

const webpackConfig = require('./webpack.config.js');

const app = express();

const compiler = webpack(webpackConfig);
compiler.run((err, stats) => {
    if (err) { console.log(err); return; }

    const requestFn = require(path.resolve(webpackConfig.output.path, webpackConfig.output.filename));

    app.get('*', (req, res) => { console.log(requestFn); });
});

requestFn outputs {}. Here is what my requestFn function looks like:

// src/server/index.js

import ReactDOMServer from 'react-dom/server';

import Server from './server';

import templateFn from './template';

export default (req, res) => {
    const reactString = ReactDOMServer.renderToString(<Server />);
    const template = templateFn(html);
    res.send(template);
};

Why am I getting {} instead of a callback function? What can I do to get the desired result?

EDIT: I am one step closer. I was able to expose my entry from my webpack config using library and libraryTarget. If you want to read more about it, check out this guide: https://webpack.js.org/guides/author-libraries/. In short terms, I added the following to me entry object in webpack:

entry: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'dist'),
    library: 'app',
    libraryTarget: 'commonjs'
}

This allowed me to import the object using require and accessing it like this:

const output = require(path.resolve(webpackConfig.output.path, webpackConfig.output.filename));
app.get('*', output.app.default);

This got me excited; however, there is one more problem. If anyone can help me out, I will be thankful! When I load the library, I get an error "React is not defined." Is there a way to include everything in this library?

EDIT2: Fixed the previous issue also. Forgot to import React in src/server/index.js

Posted Aug 25, 2017, 12:04 PM UTC · edited

36
Loading comments…