Angular-CLI global scss vairables

2019-07-10 04:30发布

问题:

How to add global scss variables in latest Angular-CLI (with webpack)?

Looks like global variables defined in styles.scss are not available in the component styles.

回答1:

They will need to be imported into the component's SCSS file via a relative path. This will allow the compiler to find the necessary parent file(s) for processing.



回答2:

You must import the global SCSS file in each and every component's style sheet you try to use the global variables. Just to reduce the pain and frustration of writing the import path with a relative path. You can use absolute path w.r.t root folder (src)

@import '~names.scss'

Note: Here it is assumed the global style required is placed at the top of the root directory of the NgApp. Prepend the file name with "~" to tell webpack of angular-cli that its not relative path.



回答3:

I was trying to use a variables.scss file in other global style files and found that there were 2 ways of doing it but only one worked (Angular CLI 1.0.0 21):

I added a variables.scss file and a site.scss file under the Assets folder. A property in site.scss references a variable set in variables.scss.

There are 2 ways to include global styles. 1 is putting import statements into the global styles.scss.

The 2nd way is to put them under the Styles array in angular-cli.json.

When I do the first way, I cannot get the variable in Site to work (no errors, just does not render).

However, when I moved all my global styles out into angular-cli.json then it DOES work (this took a few hours of fiddling to prove). You still need to reference the sibling files with an import so that the variables are declared. I can go into more detail if required...

@import 'variables.scss';


回答4:

You must import the file where the variable is from the component file:

@import "XX/XX/XX/_name.scss";

XX are the relative route to your file with variables



回答5:

Hey i solved by using this webpack configuration. So the sass-loader gets the option "data" where you can declare your import statement.

  {
    test: /\.scss$/,
    exclude: [/node_modules/, /styles/],
    use: ['to-string-loader', 'css-loader', {
      loader: 'sass-loader', options: {
        sourceMap: true,
        data: '@import "variables";',
        includePaths: [
          path.join(__dirname, '../styles/sass/')
        ]
      }
    }