4

I'm new in server-side React rendering, and I can make simple isomorphic React applications with webpack for client side and Express for server side (through React of course). But now I have some trouble - I decided to use images in my project:

export default class JustImage extends Component {
  render() {
    return (
      <div>
        <img src={require("just_image.png")} />
      </div>
    );
  }
}

It code works like a charm for client, but my server side code when I try to render tell me this error:

just_image.png: Unexpected character '�'

As I understand, Node.js doesn't know anything about webpack loaders, so can't load image right. Because I'm new in React and server-side rendering at all I want to know if there are any standard ways to fix this problem - not images only, I use images(PNG/JPEG/JPG/ICO), SVG, SASS/LESS/CSS. Thanks in advance.

2 Answers 2

3

There are two ways to solve the problem, AFAIK:

  1. Use the webpack for your server code as well. In your webpack configuration for server, you can use the same loader you did for your client. For example, you can use url-loader or file-loader for image files.

    {
      test: /\.(jpe?g|png|gif|svg)$/i,
      loader: 'url-loader',
      options: {
        limit: 8192,
      },
    }
    
  2. You can hack the require.extensions at the top of your server code.

    if (process.env === 'development') {
      require.extensions['.png'] = () => {}
    }
    

I posted a similar question here not getting an answer :)

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for answer. But I don't understand how I can use webpack for server code as well. Please, give me some example.
The start script can be webpack --watch --config config/your-server-config.js && babel-node dist/server.js. For my personal project, I opted to go with the second option, because re-bundling the server code every time code changes takes some time and not suitable for development, I think. For sample code/configuration: github.com/ming-soon/mern-starter
But if you will use 2 option, your server-side code will be broken right?
No, it has no side effects, besides that you have add the above code at the very beginning of your server code.
Try googling for a react starter kit that uses SSR, and investigate the webpack configs, it's usually done this way.
|
0

I learned a lot about this by reading the react-starter-kit code, it is basically what Ming Soon told you, you have to compile your server side code with webpack, you will need multiple webpack configs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.