access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2)

后端 未结 6 1222
醉梦人生
醉梦人生 2020-11-27 05:51

In Ionic 2, I would like to access the $colors variables from the file \"[my project]\\src\\theme\\variables.scss\".

This file contains:



        
6条回答
  •  囚心锁ツ
    2020-11-27 06:11

    One possibility is to generate a .ts file from the .scss file. A simple example of this process:

    1) Install npm i --save-dev scss-to-json.

    2) Put this in your package.json:

      "scripts": {
        ...
        "scss2json": "echo \"export const SCSS_VARS = \" > src/app/scss-variables.generated.ts && scss-to-json src/variables.scss >> src/app/scss-variables.generated.ts"
      },
    

    and run it with npm run scss2json. Windows users will need to adjust the example.

    3) Access the variables:

    import {SCSS_VARS} from './scss-variables.generated';
    ...
    console.log(SCSS_VARS['$color-primary-1']);
    

    One advantage of this is, that you'll get type completion from IDE's and it's a quite simple means to achieve your goal in general.

    Of course you could make this more advanced, for example by making the generated file read only and by putting the script into it's own .js file and make it work on every OS.

提交回复
热议问题