UNPKG

@bixi/theme

Version:
106 lines (83 loc) 2.68 kB
--- type: Basic title: 定制主题 order: 5 --- `Bixi` 内置两种主题模式 `浅色模式` 和 `暗黑模式`。 ### 如何使用 在样式文件中引入 ```less @import '@bixi/theme/index.less'; // 浅色主题 @import '@bixi/theme/dark.less'; // 暗黑主题 ``` ### 主题切换 #### 安装依赖 ``` npm i less -D less-plugin-clean-css -D less-vars-to-js -D ``` #### 打包主题样式文件 因为 `Bixi` 是基于 `zorro` 所以在生成暗黑主题时,需要将 zorro 的主题打包进来。 ```ts const less = require('less'); const LessPluginCleanCSS = require('less-plugin-clean-css'); const LessPluginNpmImport = require('less-plugin-npm-import'); const fs = require('fs-extra'); const path = require('path'); const root = path.join(__dirname, '../../..'); const themePath = path.join(root, './src/styles.less'); // 项目样式文件入口 const themeContent = ` @import '~ng-zorro-antd/style/color/colorPalette.less'; // 加载 zorro @import '${themePath}'; `; function generateTheme(vars, fileName) { return less .render(themeContent, { javascriptEnabled: true, plugins: [new LessPluginNpmImport({ prefix: '~' }), new LessPluginCleanCSS({ advanced: true })], modifyVars: { // 通过 modifyVars 修改默认主题中 less 变量值,达到主题颜色的变更。 ...darkVars, // 可以通过 less-vars-to-js 收集暗黑模式下 less 变量。 }, }) .then(data => { fs.writeFileSync(path.join(root, `./src/assets/${fileName}`), data.css); // 输出静态 css 文件, 可用于主题切换。 }) .catch(e => { console.log(e); }); } ``` 通过 `less-vars-to-js` 收集 less 变量 ```ts const fs = require('fs'); const path = require('path'); const lessToJs = require('less-vars-to-js'); function gen(type) { const lessVars1 = fs.readFileSync('some less path', 'utf8'); const lessVars2 = fs.readFileSync('some less path', 'utf8'); return lessToJs(`${lessVars1}${lessVars2}`, { stripPrefix: true, resolveVariables: false, }); } gen('type'); ``` 以上,生成了一份暗黑模式的 css 文件,接下来使用 css 文件做主题切换 #### 运行时切换主题 通过 js 动态改变 `link` 标签内部 css 资源路径。 ```ts changeTheme(theme: 'default' | 'dark'): void { if (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'; } else { const dom = document.getElementById('dark-theme'); if (dom) { dom.remove(); } } } ```