简体   繁体   中英

Using images in templates with webpack

Hi I try to setup Webpack to process templates (Mustache or Handlebars) correctly. Everything's working fine with one exception: img src atributes in templates are not processed by file-loader. Probably I don't understand something fundamental about the workflow but I would like it to work the way it's resolved in css files.

Here's my webpack config concerning loaders:

loaders: [
        {
            test:   /\.js/,
            loader: 'babel',
            include: [__dirname + '/src', __dirname + '/tests'],
            exclude: /node_modules/,
            query: {
                plugins: ['transform-runtime'],
                presets: ['es2015']
                //presets: ['es2015-native-modules']
            }
        },
        {
            test:   /\.scss/,
             loader: 'style!css!postcss-loader!sass',
            // Or
            //loaders: ['style', 'css', 'sass'],
        },
        {
            test:   /\.html/,
            loader: 'html',
        },
        {
            test: /\.modernizrrc$/,
            loader: "modernizr"
        },
        {
            test: /\.(jpe?g|png|gif|svg)$/i,
            loader:'file-loader'
        },
        {
            test: /\.mustache$/i,
            loader:'handlebars-loader'
        },
    ],

Here's a sample template:

<div style="border: solid 2px blue;">
<h2>Template fragment</h2>
<p>{{text}}</p>
<img id="img1" src="{{img}}" alt="">
<img id="img2" src="../img/btn_bubble.png" alt="">

When I load the template from js, I can insert img properly into #img1 , but #img2 stays untouched and obviously doesn't work after being included.

EDIT

Seems like it depends on template loader package. Some can manage images some don't. Eg. with Handlebars it seems like handlebars-template-loader can and handlebars-loader can't. Don't know about others though and if the topic ends here.

I'll promote my edit to an answer because (sadly) it seems to be correct.

There seems to be no general Webpack-level answer to that, therefore it depends on a template loader package in question. Some can manage images some don't. You'd may think it should be easy to chain loaders to get the template and images processed but it's not that straightforward - the inputs and outputs tend to be incompatible.

I for example had to switch from Mustache to Handlebars to solve the task, but mustache-loader guys seem to be working on the image loading as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM