csscss-variablesstenciljsstencil-component

Stenciljs CSS global variables


I am unable to get global css variables working as described in the ionic stencil docs.

I created a 'variables.css' file in 'src/global/', then put "globalStyle: 'src/global/variables.css'" into the "stencil.config.ts" file.

I then created a set of css variables in the variables.css and attempted to use them in my component's css file; however, the defaults are used since it fails to load the global variables.

// stencil.config.ts
import { Config } from '@stencil/core';

export const config: Config = {
    namespace: 'mycomponent',
    outputTargets:[
        {
            type: 'dist'
        },
        {
            type: 'www',
            serviceWorker: null
        }
    ],
    globalStyle: 'src/global/variables.css'
}


// src/global/variables.css
:root {
    --qa-primary-color: #2169e7;
    --qa-secondary-color: #fcd92b;
    --qa-dark-color: #0000;
    --qa-light-color: #ffff;
    --qa-font-family: Arial, Helvetica, sans-serif;
    --qa-font-size: 12px;
}


// src/components/my-component.css
.main {
    background: var(--qa-dark-color, yellow);
}
.first {
    color: var(--qa-primary-color, pink);
}
.last {
    color: var(--qa-secondary-color, green);
}

Feel free to take a look at the test repo.


Solution

  • I implemented the functionality myself using the copy config to copy my global/variables.css from the src/ directory to www/ and dist/. Additionally, for testing I add a stylesheet link tag for global/variables.css in the index.html file. There is no need to set the globalStyle config if you follow this process.

    While this doesn't address the fact that the process described in the docs seems to be incorrect, it does provide the desired effect.

    // stencil.config.ts
    import { Config } from '@stencil/core';
    
    export const config: Config = {
      namespace: 'mycomponent',
      outputTargets:[
        {
          type: 'dist'
        },
        {
          type: 'www',
          serviceWorker: null
        }
      ],
      copy: [
        { src: 'global' }
      ]
    }
    
    // html.index
    <!DOCTYPE html>
    <html dir="ltr" lang="en">
        <head>
            ...
            <link rel="stylesheet" type="text/css" href="global/variables.css">
        </head>
        <body>
            ...
        </body>
    </html>