Require SVG cause react-server error: "React is not defined"
Asked Answered
L

0

6

In a react-server project generated using generator-react-server loading SVG file like follow triggers a react error.

const fmc = require('../images/logo.svg');

Gives Error

Failed to load page at "../pages/home.js" ReferenceError: React is not defined
at Object.<anonymous> (/Users/me/Projects/myProject/dev/images/logo.svg:1:1)
at Module._compile (module.js:541:32)
at loader (/Users/svasseur/Projects/delateurs/dev/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/Users/svasseur/Projects/delateurs/dev/node_modules/babel-register/lib/node.js:154:7)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/me/Projects/myProject/dev/components/footer.js:5:13)

I tried to specify webpack file-loader for SVG loader like I did in previous project but it didn't work. Here is my webpack.conf.js file targeted in .reactserverrc as "webpack-config": "./webpack.config.js"

export default (webpackConfig) => {
  webpackConfig.module.loaders.splice(0, 0,
    { test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
    { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
    { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
    { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=image/svg+xml" },
    {
      test: /\.(png|jpg|gif)$/,
      loader: 'url-loader?limit=8192'
    },
    {
      test: /\.(mp4|ogg)$/,
      loader: 'file-loader'
    }
  )
  return webpackConfig
}

Here is my React Component:

import React from 'react';
require('../styles/footer.scss');

const myLogo = require('../images/logo.svg');

export default class Footer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
        <div>
            <nav className="flexcontainer">
                <div className="flexitem"><img src={myLogo} className="footer-logo"/></div>
            </nav>
        </div>
    );
  }
}

That said, requiring SVG in jsx like this works though:

<img src={require('../images/logo.svg')} />

I'm using node v6.2.2 and the following modules

└── [email protected]
└── [email protected] 
└─┬ [email protected]
  └── [email protected] 
Lempira answered 28/10, 2016 at 19:46 Comment(2)
You have to require('react') in your file to use JSX even if you don't use a React component.Seagrave
Actually I do import React from 'react' . I use those SVG in a React Component export default class Footer extends React.Component.Lempira

© 2022 - 2024 — McMap. All rights reserved.