Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render images with react on server side?

How can I render images and css files on server side with React?

Here is my server code:

const express = require('express')
const router = express.Router()
const ReactDOM = require('react-dom/server');

import Master from '../../../client/Master'

router.get('/', (req, res) => {
    res.render('test.html', {reactOutput: ReactDOM.renderToString(<Master/>)});
});

Master component:

import React from "react";
import Intro from "./pages/Intro";
import Footer from "./components/Footer";
import Header from "./components/Header";

export default class Master extends React.Component {
    constructor() {
        super();
        this.state = {appStatus: 'INTRO'}
    }

    render() {
        let layout;
        switch (this.state.appStatus) {
            case "INTRO":
                layout = <Intro/>;
        }

        return (
            <div>
                <Header/>
                {layout}
                <Footer/>
            </div>
        )
    }
}

But when I run server with babel I got this error:

/assets/img/logo.png: Unexpected character '?' (1:0)

And this is the Header component which tries to require logo.

import React from "react";
**import logo  from '../../assets/img/logo.png';**

export default class Header extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <nav class="navbar navbar-default">
                <div class="container-fluid">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#">**<img width="250" src={logo} alt=""/></a>**
                    </div>


                </div>
            </nav>
        );
    }
}

But it works fine with webpack for client side..

like image 409
Emre Tekince Avatar asked Feb 26 '16 19:02

Emre Tekince


People also ask

Can you React to server-side rendering?

Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.

How do I server-side render?

Server-side rendering (SSR) is an application's ability to convert HTML files on the server into a fully rendered HTML page for the client. The web browser submits a request for information from the server, which instantly responds by sending a fully rendered page to the client.

Is React rendered on the server?

Server-side rendering with JavaScript libraries like React is where the server returns a ready-to-render HTML page and the JS scripts required to make the page interactive. The HTML is rendered immediately with all the static elements.

Is React rendered server-side or client-side?

Client-Side Rendering By default, your React app will be client-side rendered. This means basically, all of the source code will live in JavaScript files referenced in a single HTML file that initializes your app.


1 Answers

You need a separate webpack config for your server

  1. Install this module to exclude node_modules:

    npm install --save webpack-node-externals 
    
  2. Create a separate webpack config for your server:

    module.exports = {    
      const path = require('path')
      const nodeExternals = require('webpack-node-externals')
    
      context: path.resolve(__dirname, 'directory of your server file'),
      entry: ['./filename of your server file'],
      output: {
        path: path.join(__dirname, 'directory of your bundled file'),
        filename: 'filename of your bundled file'
      },
      target: 'node',
      externals: [nodeExternals()],
      module: {
        rules: [
          {
            test: /\.(jpe?g|png|gif|svg|ico)$/i,
            use: 'url-loader?limit=8192'
          }
        ]
      }
    }
    
  3. Here's an example server webpack.config.js:

    module.exports = {    
      const path = require('path')
      const nodeExternals = require('webpack-node-externals')
    
      context: path.resolve(__dirname, 'src'),
      entry: ['./index.js'],
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      },
      target: 'node',
      externals: [nodeExternals()],
      module: {
        rules: [
          {
            test: /\.(jpe?g|png|gif|svg|ico)$/i,
            use: 'url-loader?limit=8192'
          }
        ]
      }
    }
    
  4. If using the above webpack.config.js example, run webpack then the compiled server file:

    webpack
    node dist/bundle.js
    
like image 199
Isaac Pak Avatar answered Sep 21 '22 23:09

Isaac Pak