我做了很多研究,找不到找到生成ng-zorro主题并在运行时对其进行更改的方法。
最后,我可以找到一种方法来做到这一点。
该示例适用于在项目中使用.less
样式的项目
[首先,您需要通过命令less-plugin-clean-css
]安装npm i less -D less-plugin-clean-css -D
dev依赖项>
在src
文件夹中创建theme.less
@import "../node_modules/ng-zorro-antd/ng-zorro-antd.less"; // this is important @primary-color : #f5222d; // and define the variables which are uses in the library
这里是完整变量enter link description here的链接
在themes
文件夹中创建assets
文件夹
定义less-compiler.js
其中包含:
const less = require('less'); const LessPluginCleanCSS = require('less-plugin-clean-css'); const fs = require('fs'); const darkThemeVars = require('ng-zorro-antd/dark-theme'); const appStyles = './src/theme.less'; // this path should be the path of the theme.less file const themeContent = `@import '${appStyles}';`; less.render(themeContent, { javascriptEnabled: true, plugins: [new LessPluginCleanCSS({ advanced: true })], modifyVars: { ...darkThemeVars } }).then(data => { fs.writeFileSync( // output path for the theme style './src/assets/themes/style.dark.css', data.css ) }).catch(e => { // log the render error console.error(e); });
在终端中运行
node ./less-compiler.js
(此命令应在style.dark.css
文件夹中生成src/assets/themes
文件)
((可选)
如果要在每次构建项目时都运行node ./less-compiler.js
,则可以在"build": "ng build",
中将"build": "ng build && node ./less-compiler.js",
替换为package.json
,然后可以通过npm run build
命令构建项目。定义一个可帮助您删除主题链接或将其添加到头部的功能。 (在我的情况下,app.component.ts
文件中定义的函数)
// ............. export class AppComponent { theme = ''; constructor() { setInterval(() => { this.changeTheme() }, 2000); } changeTheme() { if (this.theme === 'dark') { const style = document.createElement('link'); style.type = 'text/css'; style.rel = 'stylesheet'; style.id = 'dark-theme'; style.href = '/assets/themes/style.dark.css'; document.head.appendChild(style); } else { const dom = document.getElementById('dark-theme'); if (dom) { dom.remove(); } } this.theme = this.theme === 'dark' ? '' : 'dark'; } }
我希望这可以帮助您轻松组织运行时主题切换。