import * as fs from 'node:fs'; import { buildTheme } from '../../src/theme/theme'; export default function buildThemeConfig() { const fileName = './unocss.config.ts'; const _data = buildTheme(); // 写入时会先清空文件 fs.writeFile(fileName, `${createFileByTemplate(_data)}`, (err: any) => { if (err) { console.error(err); } else { // console.log('构建 css 提示文件完成'); console.table(flatten(_data)); } }); // 写完文件后使用编辑器格式化一下 } function flatten(obj: any, parentKey = ''): any { let result: any = {}; for (const [key, value] of Object.entries(obj)) { const newKey = parentKey ? `${parentKey}.${key}` : key; if (typeof value === 'object' && value !== null) { const flattened = flatten(value, newKey); result = { ...result, ...flattened }; } else { result[newKey] = value; } } return result; } // 通过模版生成文件 function createFileByTemplate(theme: any) { const file_string = ` /** * unocss defineConfig * @link unocss: https://github.com/unocss/unocss * @link unocss-preset-weapp: https://github.com/MellowCo/unocss-preset-weapp * */ import { defineConfig, presetIcons } from 'unocss'; import presetWeapp from 'unocss-preset-weapp'; import { transformerAttributify, transformerClass } from 'unocss-preset-weapp/transformer'; import transformerDirectives from '@unocss/transformer-directives'; const transformRules = { '.': '-d111-', '/': '-s111-', ':': '-c111-', '%': '-p111-', '!': '-e111-', '#': '-w111-', '(': '-b111l-', ')': '-b111r-', '[': '-f111l-', ']': '-f111r-', $: '-r111-', ',': '-r222-', }; const prefix = ''; export default defineConfig({ presets: [ // https://github.com/MellowCo/unocss-preset-weapp presetWeapp({ nonValuedAttribute: true, prefix: prefix, whRpx: true, transform: true, platform: 'uniapp', transformRules, }), // 由 Iconify 提供支持的纯 CSS 图标解决方案 presetIcons({ scale: 1, warn: true, extraProperties: { 'display': 'inline-block', 'vertical-align': 'middle', }, }), ], // transformers: [transformerDirectives()], // attributify: false, shortcuts: [ { 'border-base': 'border border-gray-500_10', 'z-tar-both': 'z-988', 'head-fixed': 'fixed top-0 left-0 w-full z-tar-both', center: 'flex justify-center items-center', }, ], theme: ${JSON.stringify(theme)}, transformers: [ transformerDirectives({ applyVariable: ['--at-apply', '--uno-apply', '--uno'], enforce: 'pre' }), transformerAttributify({ classPrefix: prefix, transformRules, nonValuedAttribute: true, }), transformerClass({ transformRules, }), ], }); `; return file_string; }