|
| 1 | +[](https://travis-ci.org/sasstools/json-importer) |
| 2 | + |
| 3 | +# json-importer |
| 4 | + |
| 5 | +>Node Sass importer for for importing JSON files as maps |
| 6 | +
|
| 7 | +## Disclaimer |
| 8 | + |
| 9 | +This is ALPHA software. |
| 10 | + |
| 11 | +It's messy. It's probably slow. It's probably buggy. |
| 12 | + |
| 13 | +Give it a shot. File bugs. Be patient. |
| 14 | + |
| 15 | +## Support |
| 16 | + |
| 17 | +- Node >= 6 |
| 18 | +- node-sass >= 4.9.0 |
| 19 | + |
| 20 | +## Install |
| 21 | + |
| 22 | +This package has a peer dependency on Node Sass for ensure import API compatibility. |
| 23 | + |
| 24 | +```sh |
| 25 | +npm install @node-sass/json-importer node-sass |
| 26 | +``` |
| 27 | + |
| 28 | +## Usage |
| 29 | + |
| 30 | +Create a JSON file you want to import. |
| 31 | +```json |
| 32 | +// config.json |
| 33 | +{ |
| 34 | + "colors": { |
| 35 | + "red": "#f00", |
| 36 | + "blue": "#00f" |
| 37 | + }, |
| 38 | + "sizes": ["16px", "20px", "24px"], |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +When Node Sass parses an `@import` for a `.json` URL it will try load the file from disk. If found the JSON object will be imported as a Sass map named after the `.json` file. |
| 43 | + |
| 44 | +```scss |
| 45 | +@import "config.json"; |
| 46 | + |
| 47 | +$colors: map-get($config, "colors"); |
| 48 | +$sizes: map-get($config, "sizes"); |
| 49 | + |
| 50 | +.button { |
| 51 | + color: map-get($color, "red"); |
| 52 | + size: nth($sizes, 2); |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +Produces the following CSS output |
| 57 | + |
| 58 | +```css |
| 59 | +.button { |
| 60 | + color: "#f00"; |
| 61 | + size: "medium"; |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +### Node Sass API |
| 66 | + |
| 67 | +```js |
| 68 | +var sass = require('node-sass'); |
| 69 | +var jsonImporter = require('@node-sass/json-importer'); |
| 70 | + |
| 71 | +sass.render({ |
| 72 | + file: 'index.scss', |
| 73 | + importer: [jsonImporter], |
| 74 | +}, function (err, result) { |
| 75 | + if (err) throw err; |
| 76 | + console.log(result.css.toString()); |
| 77 | +}); |
| 78 | +``` |
| 79 | + |
| 80 | +### Node Sass CLI |
| 81 | + |
| 82 | +```sh |
| 83 | +$ node-sass index.scss --importer node_modules/@node-sass/json-importer/index.js |
| 84 | +``` |
| 85 | + |
| 86 | +## Caveats |
| 87 | + |
| 88 | +### Everything is a String |
| 89 | + |
| 90 | +Sass has many types. `Number` which represent CSS numbers values with optional unit like `16px`. `Color` which represents CSS colour values like `red`, or `#f00`. These are structurally different from `String` like `"hello"`, `"16px"`, `"red"`, or `"#f00`. |
| 91 | + |
| 92 | +To reduce complexity the values produced by this importer are always `String`. As a result you may need to `unquote()` the values to cast them into their intended types if for example you wanted to do math on them. |
0 commit comments