Skip to content
This repository was archived by the owner on Apr 8, 2020. It is now read-only.
This repository was archived by the owner on Apr 8, 2020. It is now read-only.

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

Closed

Description

@mattburrell

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.

Activity

  1. MarkPieszak commented on Nov 2, 2016

    @MarkPieszak
    Contributor

    Matt, try something like:

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

    This way the loader might handle it properly. Don't remember if that will work, I'm not by a computer at the moment.

    The best alternative is using CSS, and putting the image in the regular background-image property there, the loader will handle that correctly as well.

    Hope that helps!

  2. mattburrell commented on Nov 2, 2016

    @mattburrell
    Author

    Thanks @MarkPieszak. I tried using require but got the same error.

    Will have to go down the CSS route as you suggest!

  3. mattburrell commented on Nov 2, 2016

    @mattburrell
    Author

    Ah it works when I move the loaders from the clientBundleConfig to the sharedConfig. Doh.

  4. MarkPieszak commented on Nov 2, 2016

    @MarkPieszak
    Contributor

    There it is 🙈😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions