Lodin
Lodin

Reputation: 2068

Node-sass does not understand tilde

Exploring the angular-cli for RC1 of Angular2 released recently I faced strange problem: node-sass within sass plugin in the angular-cli does not parses ~ before the package name throwing following error:

Error: File to import not found or unreadable: ~@angular2-material/core/style/theme-functions

It happens during compiling the following code:

@import "~@angular2-material/core/style/theme-functions";

If I remove tilde everything will be ok. Is it the right behavior, or there is a path to make node-sass understand ~?

P.S. I use WebStorm, and it prefers using ~ too. If tilde is omitted it complains to unability of resolving path. And after some googling I found that using code without tilde is legacy and ~ should be used as best practice. Is it right?

Upvotes: 20

Views: 15484

Answers (2)

Jules Colle
Jules Colle

Reputation: 11939

I just had to install the node-sass-tilde-importer package:

npm install node-sass-tilde-importer --save

And then change my scss script to:

node-sass --watch style.scss --importer=node_modules/node-sass-tilde-importer style.css

Here are some relevant parts of my package.json file:

{

  [...]

  "scripts": {
    "scss": "node-sass --watch style.scss --importer=node_modules/node-sass-tilde-importer style.css"
  },

  "dependencies": {
    "bootstrap": "^4.3.1",
    "bootstrap-material-design": "^4.1.2",
    "node-sass": "^4.12.0",
    "node-sass-tilde-importer": "^1.0.2"
  }
}

Upvotes: 9

nanobar
nanobar

Reputation: 66365

Tilde path resolving is something that webpack does, node-sass doesn't have such a resolver built in. sass-loader for webpack has this. You can write your own import resolution alternatively.

Just for completeness here's how you might do it without webpack/sass-loader using a custom importer:

function importer(url, prev, done) {
  if (url[0] === '~') {
    url = path.resolve('node_modules', url.substr(1));
  }

  return { file: url };
}

Upvotes: 29

Related Questions