March 2nd, 2019
11:22 pm
Compiling a custom PrimeNG theme deployed as a static asset

Posted under Angular & PrimeNG
Tags ,

I am  using multiple themes and theme selection, using custom themes

For interest I am loading the theme css as a static asset, in index.html:-

<head>
<meta charset=”utf-8″>
<title>Microapp Fabric Prototype</title>
<base href=”/”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link id=”theme-css” rel=”stylesheet” type=”text/css” href=”assets/resources/themes/salient/theme.css”>
</head>

Then I am dynamically changing the href to switch themes:-

export class ThemeSwitcher {
/*
* Select the target theme
* this may be an external theme or an internal packaged one
* If the path contains a ‘/’ the theme is assumed to be an external theme source
*/
changeTheme(theme: string) {
const themeLink: HTMLLinkElement = <HTMLLinkElement>document.getElementById(‘theme-css’);
themeLink.href = theme.indexOf(‘/’) >= 0 ? theme : ‘assets/resources/themes/’ + theme + ‘/theme.css’;
}
}

A theme SCSS under the assets folder will be automatically compiled and included inline in the package only when a specific theme is referred to in the “style” section of angular.json. When dynamically switching multiple themes as above, the themes are kept as static assets and are not inlined in the package and so are removed from the “style” section. When this is done, the theme scss files for all the themes are not compiled to css automatically when an ng build or ng serve is done. This post here details how to manually install and build the scss using node-sass. It goes into other details which I haven’t needed as I am using static assets, so only node-sass is needed. If in the actual theme directory, the following commands will install  node-sass and compile the scss for the theme and also create the source map:-

npm install node-sass

node-sass theme.scss theme.css ––source-map .

This can also be added to the scripts section of package.json to make an npm command:

“scripts”: {
“ng”: “ng”,
“start”: “ng serve”,
“build”: “ng build”,
“test”: “ng test”,
“lint”: “ng lint”,
“e2e”: “ng e2e”,
“scss”: “cd src/assets/resources/themes/legacy-blue && node-sass theme.scss theme.css ––source-map .”
},

This can be run by simply using npm run scss

Note as above that npm supports the cd command in the scripts section, both for linux and windows (as detailed here). The default directory is the root of the project, and this is consistent even if you run the npm command e.g. from a subdirectory. I did not manage to find a way to automate this via an ng build or ng serve command, so these would have to be run in conjunction with npm run scss (with the latter running first).

No Comments »

Comments RSS

Leave a Reply

You must be logged in to post a comment.