What does a `~` tilde in a CSS `url()` do?

CssWebpackWebpack Style-Loader

Css Problem Overview


E.g. @import url("~./foobar");

Saw it here, not sure if it's some package specific thing or if it's actual CSS syntax.

Css Solutions


Solution 1 - Css

The CSS @import path <url> is usually relative to the current working directory.

So using the prefix ~ at the start of the path tells Webpack's css-loader to resolve the import "like a module", starting from the node_modules directory.

What that means is that if you have a node module called normalize installed, and you need to import a css file from within it named /normalize.css, you can do that with:

@import "~normalize/normalize.css";

In your linked example, inside font-loader/example/test.js there is an import of a module called font-boon.

var boon = require('./font-boon');

Inside of font-loader/example/test.css the font-boon module is @imported so that it is available in text.css.

@import url("~./font-boon");

Solution 2 - Css

UPDATE March 2021

From sass-loader tilde '~' imports are deprecated and is recommended to be removed.

Solution 3 - Css

Using an @import statement assumes you're importing from the node_modules folder. So for example if you're trying to import bootstrap.css, you'd use

@import "~bootstrap/dist/css/bootstrap.css"

That is, you're putting the path relative to the node_modules folder.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionahstroView Question on Stackoverflow
Solution 1 - CssksavView Answer on Stackoverflow
Solution 2 - CssTheBostiView Answer on Stackoverflow
Solution 3 - CssKalCView Answer on Stackoverflow