Kayote Kayote - 5 months ago 54
Javascript Question

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, {} );
}

Answer

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" }
Comments