Webpack && stylus-loader incorrectly resolve url p

2019-02-07 02:06发布

问题:

Let's say I have home.styl menu/ menu.styl image.svg

home.styl is required from an entry point or JS.

Then:

home.styl imports menu/menu.styl menu/menu.styl has url(image.svg).

The problem is that image.svg is not found.

It exists in the same folder as menu.styl, but is not resolved.

The loaders are: loaders: [{ test: /\.styl$/, loader: 'style!css!stylus' }, { test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/, loader: 'file?name=[path][name].[ext]' }]

Below are my ideas why that fails. Hope to get an answer how to fix that.

===========

If url(image.svg) is required from menu.styl, it should be looked up in the folder with menu.styl. That's because the path is relative by default.

But what's going on is the following:

  1. Stylus-loader processes all styl, joins imports into one big css
  2. CSS-loader gets css with the root context, namely the directory of home.styl
  3. Then CSS-loader resolved all url(...) paths relative to that upper context.

So the image is searched in the folder of home.styl instead of menu.styl.

How to fix that?

P.S. The example project repo is at https://github.com/iliakan/stylus-path-problem

回答1:

You want to use stylus-loader's resolve url option, which will replace the url() function inside your .styl files with a custom resolver.

{
  test:   /\.styl$/,
  loader: 'style!css!stylus?resolve url'
}

See the corresponding code. Pretty cool solution.