Webpack not rewriting asset urls (stylus)

Viewed 1060

I am trying to rewrite my assets paths from a certain path (~assets/myimage.png) to the correct directory (in my case /assets/).

I told my webpack to write all images to a folder inside public. The images are correctly written, however the url in the build css is not adjusted accordingly.

This is the rule i am using for my stylus files

use: ExtractTextPlugin.extract({
  fallback: {
    loader: require.resolve("style-loader"),
    options: {
      hmr: false
    }
  },
  use: [
    {
      loader: require.resolve("css-loader")
    },
    {
      loader: require.resolve("stylus-loader")
    }
  ]
})

and the one i am using for the assets

{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve("url-loader"),
    options: {
      limit: 100,
      name: "static/media/[name].[hash:8].[ext]"
    }
},

My alias that resolves to the correct directory:

assets: path.resolve(__dirname, "../public")

and the public path is set as /assets/

publicPath: publicPath + "assets/",

Since i use ExtractTextPlugin, the style loader can not be used. When using style loader only it works, however in my use case i need a css file as /style.css

Any ideas on this?

3 Answers

Use file-loader for images.

test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}  
          }
        ]
      }
    ]

Before passing your CSS to file-loader/url-loader, it might be necessary to resolve relative assets urls.

I never used stylus-loader, but I would try the trying approach as any other CSS preprocessor and use resolve-url-loader:

module.exports = {
  module: {
    loaders: [
      {
        test   : /\.css$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader']
      }, {
        test   : /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader', 'stylus-loader?sourceMap']
      }
    ]
  }
};

It's just a thought, but might your alias be wrong? You wrote

assets: path.resolve(__dirname, "../public")

but regarding that your project structure looks something like this

--project_root/
 |--public
 |--src
 |--webpack.conf.js

it should be

assets: path.resolve(__dirname, "public") //without the "folder up" operator
Related