Search code examples
node.jsreactjswebpackserver-rendering

got "Element type is invalid: expected a string" when trying to server side rendering react


I get this error:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

When trying to use ReactDOMServer.renderToStaticMarkup.

This is my react app:

"use strict";
import React from 'react'

module.exports = () => {
    return (
        <div></div>
    );
};

And this is my node server rendering code:

"use strict";
const path = require('path');
const webpack = require('webpack');
const React = require('react'), ReactDOMServer = require('react-dom/server'),
DOM = React.DOM, body = DOM.body, div = DOM.div, script = DOM.script;
webpack({
    target: "node",
    entry: [
        path.resolve(__dirname, '../js', 'app.js'),
    ],
    module: {
        loaders: [
            {
                exclude: /node_modules/,
                loader: 'babel',
                test: /\.js$/,
            },
        ]
    },
    output: {filename: 'app.bundle.js', path: __dirname},
},() => {
    const App = React.createFactory(require('./app.bundle.js'));
    let html = ReactDOMServer.renderToStaticMarkup(body(null,
        div({
            id: 'root', dangerouslySetInnerHTML: {
                __html: ReactDOMServer.renderToString(App())
            }
        })
    ));
});

Does anyone have an idea what cause this error and how to fix this?

Thanks in advance.


Solution

  • It appears that the bundle is not compatible by default with commonjs. As I read in webpack docs, you need to add libraryTarget:'commonjs2' to your output object in order to do it.

    Like this:

    output: {filename: 'app.bundle.js', path: __dirname,libraryTarget:'commonjs2'}