0

I use less, this is my config of webpack 2.

{
    test: /\.less$/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: ['css-loader','less-loader']
    })
}

It worked well but image is missing when I have background image value like this in my less file

.section-one{
    background-color: @red500;
    background-image: url(/images/landing/header.jpg);
    background-position: center;
}

I have error of

GET http://localhost:8080/images/landing/header.jpg 404 (Not Found)

in my chrome console since I used webpack dev server

Alex Yong
  • 7,425
  • 8
  • 24
  • 41
  • You need to configure webpack to copy over your static assets to the build folder. See this SO answer: https://stackoverflow.com/questions/27639005/how-to-copy-static-files-to-build-directory-with-webpack – Daniel T. Feb 19 '17 at 15:18
  • @DanielT. I used webpack dev server, why would I need to do that? my js files are fine, but not the image reference within the .less files. – Alex Yong Feb 19 '17 at 15:26
  • Do you want to manage the image through webpack or outside of it? **css-loader** will skip absolute paths like that and you will have to copy the files like Daniel said. It would help if you could include your image related configuration as there's not enough information at the moment. – Juho Vepsäläinen Feb 19 '17 at 15:48
  • @JuhoVepsäläinen here's my full webpack.config.js http://pastebin.com/JqGv7HTw Can you please point me the direction? – Alex Yong Feb 19 '17 at 15:49
  • Based on that I would say going with a relative import against the image should fix it. – Juho Vepsäläinen Feb 19 '17 at 15:56
  • @JuhoVepsäläinen that's not do able, my project is too huge to change every files. – Alex Yong Feb 19 '17 at 16:13
  • In that case copying the files as suggested above would be an option. **css-loader** skips absolute paths by design. – Juho Vepsäläinen Feb 19 '17 at 16:17

1 Answers1

2

The less loader doesn't have to do anything with your problem. The way I solved is to do it this way:

        {
            test: /\.(jpe?g|png|gif|svg)$/,
            include: helpers.root('src', 'app'),
            loader: "file-loader",
            query: {
                name: 'img/[name].[ext]'
            }
        }

This is the part where you load your images, with the query you set the path to img/. In your ts file you need to add this line:

require('./img/your-image-name.png');

After that you can use it in your less file like this: background-image: url(img/your-image-name.png);

HhK
  • 31
  • 6