Webpack: Loading images from html templates
If you are using HTML templates in Webpack 2, in addition to use the file-loader you need to change in your HTML:
<img src="../images/foo.png" />
to this
<img src=<%=require("../images/foo.png")%> />
- Yes, you will have to do so for loading images from different path.
- I had similar issue and I resolved this using
file
loader:
.
loaders: [{ // JS LOADER test: /\.js$/, loader: 'babel-loader?optional[]=runtime', exclude: /node_modules/}, { // ASSET LOADER test: /\.(woff|woff2|ttf|eot)$/, loader: 'file-loader'},{ //IMAGE LOADER test: /\.(jpe?g|png|gif|svg)$/i, loader:'file-loader'},{ // HTML LOADER test: /\.html$/, loader: 'html-loader'},{ //SCSS LOADER test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader?indentedSyntax"]}]
Good Luck
With Webpack 4, I was able to solve this problem by updating by html-loader
to specify the root
for my files. So given @syko's original structure; in webpack.config.js
...
module: { rules: [ // other stuff above..... { test: /\.html$/, use: [ // ...The other file-loader and extract-loader go here. { loader: 'html-loader' options: { // THIS will resolve relative URLs to reference from the app/ directory root: path.resolve(__dirname, 'app') } } ] } ]}
This tells the html-loader
to interpret all absolute urls from the /app
folder. So in our app/templates/foo.html
, you can then use the following...
<img src="/images/foo.png" />
This then tells html-loader
to see the above as path.resolve(__dirname, 'app', 'images', 'foo.png')
. Then if you have extract-loader
and/or file-loader
, all the paths should be correct.
Managed to get this solution after hammering away at it for a while. The biggest confusion is where about in the loader stack the /images/foo.png
is interpreted, in this case it starts at the html-loader
plugin. Everything else after that, is more about how the image files are to be published.
Hope that helps.