Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack && stylus-loader incorrectly resolve url paths

Tags:

webpack

stylus

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

like image 763
Ilya Kantor Avatar asked Oct 31 '15 11:10

Ilya Kantor


People also ask

What is the role of webpack?

This is why webpack exists. It's a tool that lets you bundle your JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts and stylesheets.

What is webpack in react?

Like create-React-app, React Webpack is also a command-line tool used to create a bundle of assets (files and code). It doesn't run on the browser or the server. It takes all the JS files and other assets, transforming them into one large file.

Is webpack still used?

Loved by many, hated by some, known to all. And still the most popular bundler in 2021. With more than 15 million weekly downloads (at the time of writing this post), there's no doubt that Webpack is still the bundler par excellence in 2021.

Is webpack and npm same?

npm and Webpack are two completely different tools that do completely different things. npm is the default package manager for JavaScript. It is a huge registry of packages for all kind of JS development. It is highly unlikely that you will not need it.


1 Answers

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.

like image 152
Alexandre Kirszenberg Avatar answered Sep 23 '22 04:09

Alexandre Kirszenberg