Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Images in Module Through Webpack

I am using NodeJs, webpack & ES2015 for my app.

I cannot seem to figure out how to import an image/s in my modules. The following does not work.

import "../../css/image/t1.png";

EDIT: As per Sitian's request, here is my webpack config:

const webpack = require( "webpack" );
const path = require( "path" );
const merge = require( "webpack-merge" );
const TARGET = process.env.npm_lifecycle_event;
process.env.BABEL_ENV = TARGET;

const PATHS = {
    app : path.join( __dirname, "app" ),
    build : path.join( __dirname, "build" )
};

const common = {
    entry : {
        app : PATHS.app
    },
    resolve : { // helps us refer to .js? without ext.
        extensions : [ "", ".js", ".jsx" ]
    },
    output : {
        path : PATHS.build,
        filename : "bundle.js"
    },
    module : {
        preLoaders : [
            {
                test : /\.css$/,
                loaders : [ "postcss" ],
                include : PATHS.app
            },
            {
                test : /\.jsx?$/,
                loaders : [ "eslint" ],
                include : PATHS.app
            }
        ],
        loaders : [
            {
                test : /\.css$/,
                loaders : [ "style", "css" ],
                include : PATHS.app
            },
            {
                test : /\.jsx?$/,
                loader : 'babel',
                query : {
                    cacheDirectory : true,
                    presets : [ 'react', 'es2015' ]
                },
                include : PATHS.app
            }
        ]
    }
};

if( TARGET === "start" || !TARGET ) {
    module.exports = merge( common, {
        devtool : 'inline-source-map',
        devServer : {
            contentBase : PATHS.build,
            hot : true,
            progress : true,
            stats : 'errors-only'
        },
        plugins : [
            new webpack.HotModuleReplacementPlugin()
        ]
    } );
}
if( TARGET === "build" ) {
  module.exports = merge( common, {} );
}
like image 593
Kayote Avatar asked May 12 '16 19:05

Kayote


2 Answers

The file-loader (or url-loader, which "can return a Data Url if the file is smaller than a limit") can be used to import images into modules.

See the webpack loaders documentation for more information on how to use such loaders:

Configuration

{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
like image 195
klaasman Avatar answered Sep 20 '22 08:09

klaasman


With current versions of webpack it should work:

import t1 from "../../css/image/t1.png";

and your webpack.config (webpack 2.0):

module: {
  rules: [
    {test: /\.png$/, use: 'url-loader?mimetype=image/png'},
  ]
}
like image 43
Marcus Tanner Avatar answered Sep 21 '22 08:09

Marcus Tanner