Import image into React component fails on server-side render #1283

Closed
opened 2025-08-09 17:19:33 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @mattburrell on 11/2/2016

I'm using the ReactRedux template but I'm using ES6 not TypeScript.

I'm trying to import an image into a React component but when I run webpack I get a module parse failure:

ERROR in ./ClientApp/components/logo.gif                                                                                               
Module parse failed: C:\Users\user\Documents\lms_v2\ClientApp\components\logo.gif Unexpected character '�' (1:6)             
You may need an appropriate loader to handle this file type.                                                                           
SyntaxError: Unexpected character '�' (1:6) 

My component looks like this:

import React from 'react';
import NavMenu from './NavMenu';
import logo from './logo.gif';

export default class Layout extends React.Component {
    render() {
        return (
            <div>
                <div className="row main">
                    <div className="col-md-2">
                        <a className="navbar-brand" href="#">
                            <img alt="Logo" src={logo} />
                        </a>
                        <NavMenu />
                    </div>
                    <div className="col-md-3">
                        {this.props.left}
                    </div>
                    <div className="col-md-4">
                        {this.props.body}
                    </div>
                    <div className="col-md-3">
                        {this.props.right}
                    </div>
                </div>
            </div>
        );
    }
}

Here is my webpack.config.js:

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;

// Configuration in common to both client-side and server-side bundles
var sharedConfig = () => ({
    resolve: { extensions: [ '', '.js' ] },
    output: {
        filename: '[name].js',
        publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        loaders: [
            { test: /\.js?$/, include: /ClientApp/, loader: 'babel-loader' }
        ]
    }
});

// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig(), {
    entry: { 'main-client': './ClientApp/boot-client.js' },
    module: {
        loaders: [
            { test: /\.css$/, loader: ExtractTextPlugin.extract(['css']) },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
        ]
    },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    devtool: isDevBuild ? 'inline-source-map' : null,
    plugins: [
        new ExtractTextPlugin('core.css'),
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [
        // Plugins that apply in development builds only
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', // Remove this line if you prefer inline source maps
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
        })
    ] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
    ])
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig(), {
    entry: { 'main-server': './ClientApp/boot-server.js' },
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientApp/dist')
    },
    target: 'node',
    devtool: 'inline-source-map',
    externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});

module.exports = [clientBundleConfig, serverBundleConfig];

Any pointers you could give would be much appreciated.

*Originally created by @mattburrell on 11/2/2016* I'm using the ReactRedux template but I'm using ES6 not TypeScript. I'm trying to import an image into a React component but when I run ``webpack`` I get a module parse failure: ``` ERROR in ./ClientApp/components/logo.gif Module parse failed: C:\Users\user\Documents\lms_v2\ClientApp\components\logo.gif Unexpected character '�' (1:6) You may need an appropriate loader to handle this file type. SyntaxError: Unexpected character '�' (1:6) ``` My component looks like this: ``` import React from 'react'; import NavMenu from './NavMenu'; import logo from './logo.gif'; export default class Layout extends React.Component { render() { return ( <div> <div className="row main"> <div className="col-md-2"> <a className="navbar-brand" href="#"> <img alt="Logo" src={logo} /> </a> <NavMenu /> </div> <div className="col-md-3"> {this.props.left} </div> <div className="col-md-4"> {this.props.body} </div> <div className="col-md-3"> {this.props.right} </div> </div> </div> ); } } ``` Here is my ``webpack.config.js``: ``` var isDevBuild = process.argv.indexOf('--env.prod') < 0; var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var nodeExternals = require('webpack-node-externals'); var merge = require('webpack-merge'); var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/; // Configuration in common to both client-side and server-side bundles var sharedConfig = () => ({ resolve: { extensions: [ '', '.js' ] }, output: { filename: '[name].js', publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix }, module: { loaders: [ { test: /\.js?$/, include: /ClientApp/, loader: 'babel-loader' } ] } }); // Configuration for client-side bundle suitable for running in browsers var clientBundleOutputDir = './wwwroot/dist'; var clientBundleConfig = merge(sharedConfig(), { entry: { 'main-client': './ClientApp/boot-client.js' }, module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract(['css']) }, { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } } ] }, output: { path: path.join(__dirname, clientBundleOutputDir) }, devtool: isDevBuild ? 'inline-source-map' : null, plugins: [ new ExtractTextPlugin('core.css'), new webpack.DllReferencePlugin({ context: __dirname, manifest: require('./wwwroot/dist/vendor-manifest.json') }) ].concat(isDevBuild ? [ // Plugins that apply in development builds only new webpack.SourceMapDevToolPlugin({ filename: '[file].map', // Remove this line if you prefer inline source maps moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk }) ] : [ // Plugins that apply in production builds only new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }); // Configuration for server-side (prerendering) bundle suitable for running in Node var serverBundleConfig = merge(sharedConfig(), { entry: { 'main-server': './ClientApp/boot-server.js' }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, './ClientApp/dist') }, target: 'node', devtool: 'inline-source-map', externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules }); module.exports = [clientBundleConfig, serverBundleConfig]; ``` Any pointers you could give would be much appreciated.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#1283
No description provided.