3

I'm currently running into [SyntaxError: Invalid or unexpected token] when trying to import image and load it onto src attribute. Here's the code:

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

export class EmailHeader extends React.Component { 
    render() { 
        return ( 
            <table style={{width: "100%"}}>
                <tbody>
                    <tr>
                        <td>
                            <img src={logo}></img> //this part throws an error
                        </td>
                        
                    </tr>
                </tbody>
            </table>
        )
    }
}

Just importing "logo" works fine without error. But as soon as I add src={logo}, it throws the s yntax error message.

React SSR has been setup this way:

import * as ReactDOMServer from 'react-dom/server';
import { EmailHeader } from '../email/pages/EmailHeader';

///...
ReactDOMServer.renderToStaticMarkup(<EmailHeader/>)

I'm using Webpack 4 to bundle all my codes. Any help / idea would be extremely helpful! Thanks!

Andrew Kim
  • 41
  • 1
  • 4

4 Answers4

0

You probably have to configure your webpack. Here is an easy way to load image files. https://webpack.js.org/guides/asset-management/#loading-images

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Instead of importing image as * you can import image like this-

import logo from '../../../../assets/logo.png';

I am using the same in my project and it works.
Refer to this answer to get more details - See Hawkeye Parker answer

Sagar Darekar
  • 982
  • 9
  • 14
0

You must build another server module for ssr render, cos your image and css is packing by webpack such like this: package.json

"server": "nodemon --exec babel-node server/index.js",
"buildServer": "NODE_ENV=development webpack --config webpack.server.config.js"

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import Main from './container/main';
import fs from "fs";
let buildHtml;
export default function render(req, res) {
  const context = {};
  const appString = renderToString(
    <StaticRouter location={ req.url } context={ context }>
      <Main/>
    </StaticRouter>
  );
  if (!buildHtml) {
    buildHtml = fs.readFileSync('./build/index.html', 'utf8');
  }
  let result = buildHtml.replace('#body', appString);
  console.log(appString);
  res.send(result);
};

server side use 'render' function in the ssr.js file which build by webpack

import React from 'react';
import fs from 'fs';
import { StaticRouter } from 'react-router-dom';
import Main from '../src/container/main';

const render = require('../buildSsr/main').default;
const reactDomServer = require('react-dom/server');
console.log('server start ....');
console.log(render);
const useServerBuildFile = true;
let buildHtml;
module.exports = function(app) {
  const routerArray = ['/', '/todo', 'about'];
  routerArray.forEach((item) => {
    if (useServerBuildFile) {
      app.get(item, render);
    } else {
      app.get(item, (req, res) => {
        const context = {};
        const appHtml = reactDomServer.renderToString(
          <StaticRouter location={ req.url } context={ context }>
            <Main/>
          </StaticRouter>,
        );
        if (!buildHtml) {
          buildHtml = fs.readFileSync('./build/index.html', 'utf8');
        }
        let result = buildHtml.replace('#body', appHtml);
        res.send(result);
      });
    }
  });
};

i have an pure example from my git support all new lib in 2020, such as babel7, webpack4: https://github.com/liuxiaocong/react-self-customize-webpack-ssr

Evan liu
  • 17
  • 1
0

install "file-loader' npm package.

module.exports={
module:{
rules:  {
        test: /\.(jpg|jpeg|png|gif|ico)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "images/[name].[contenthash:4].[ext]",
              outputPath: "images/",
            },
          },
        ],
      },
}

}

this is to tell webpack how to handle with these types of image files. then you import it

 import logo from '../../../../assets/logo.png';
Yilmaz
  • 35,338
  • 10
  • 157
  • 202