M
M
Maxim Ivanov2016-10-26 14:06:17
webpack
Maxim Ivanov, 2016-10-26 14:06:17

How to fix webpack relative path issues with sass-loader?

I have a problem when there are styles in sass files with this code:
app.scss

body {
 background: url(/img/test.png) no-repeat;
}

app.js
import './body.scss';
/*
.. js code
*/

Then he is looking for this picture relative to app.js, but I don’t need this, and I want to prohibit
Found this solution (put a tilde):
app.scss
body {
 background: url(~/img/test.png) no-repeat;
}

But then, the problem is different.
If we have a project in the root directory
and we run index.html like this localhost:8080
Then everything is fine
And if we move the project to the context folder and connect to our index.html like this localhost:8080/context
Now the problem is that webpack substitutes css styles like this:
body {
 background: url(img/test.png) no-repeat;
}

And the browser writes an error, because it tries to find an image at this address localhost:8080/img/test.png
Although I loaded the page like this localhost:8080/context
Here is the webpack config:
module.exports = {

  context: __dirname, // точка входа в приложение

  entry: { // точки входа
    core: './angular/vendor.js',
    app: './angular/app.module.js'
  },

  output: { // выходные файлы
    path: '../webapp/js/',
    publicPath: '/js/',
    filename: '[name].js',
    library: '[name]'
  },

  module: {

    loaders: [
        { // используем ES6 to ES5
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'babel', // 'babel-loader' is also a legal name to reference
          query: {
            presets: ['es2015'],
            compact : false
          }
        },
        {
            test: /\.html$/,
            loader: 'html'
          },
        {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        },
        {
          test: /\.scss$/,
          loaders: ['style', 'css', 'resolve-url', 'sass?sourceMap']
        }

        
    ]
  },

};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
qtuz, 2016-10-29
@qtuz

The sass-loader page recommends using resolve-url-loader . I used, great solution to the problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question