141

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

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

dontexist
  • 5,252
  • 4
  • 27
  • 51

3 Answers3

184

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");

ksav
  • 20,015
  • 6
  • 46
  • 66
  • 9
    so.. basically, is `~` contain `node_module` path? – adrianriyadi Jan 28 '20 at 04:40
  • 5
    `~` is apparently [handled by webpack `css-loader`](https://webpack.js.org/loaders/css-loader/#import), the [raw postcss-import doesn't support it](https://github.com/postcss/postcss-loader/issues/166#issuecomment-275169151). – Nickolay May 30 '20 at 19:06
38

UPDATE March 2021

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

TheBosti
  • 1,354
  • 13
  • 19
  • 8
    Note that the `~` imports are deprecated in `sass-loader`, but not in `css-loader`. https://webpack.js.org/loaders/css-loader/#url – Andrew Jul 28 '21 at 20:59
5

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.

KalC
  • 1,530
  • 3
  • 22
  • 33