Skip to content

Commit

Permalink
feat(core): expose mergeConfigs utility
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed May 26, 2023
1 parent 0c7a7f8 commit c53d291
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 2 deletions.
29 changes: 29 additions & 0 deletions packages/core/src/config.ts
Expand Up @@ -164,3 +164,32 @@ export function resolveConfig<Theme extends {} = {}>(

return resolved
}

/**
* Merge multiple configs into one, later ones have higher priority
*/
export function mergeConfigs<Theme extends {} = {}>(
configs: UserConfig<Theme>[],
): UserConfig<Theme> {
function getMerged<T extends 'rules' | 'variants' | 'extractors' | 'shortcuts' | 'preflights' | 'preprocess' | 'postprocess' | 'extendTheme' | 'safelist' | 'separators' | 'presets'>(key: T): ToArray<Required<UserConfig<Theme>>[T]> {
return uniq(configs.flatMap(p => toArray(p[key] || []) as any[])) as any
}

const merged = Object.assign(
{},
...configs,
{
presets: getMerged('presets'),
safelist: getMerged('safelist'),
preprocess: getMerged('preprocess'),
postprocess: getMerged('postprocess'),
preflights: getMerged('preflights'),
rules: getMerged('rules'),
variants: getMerged('variants'),
shortcuts: getMerged('shortcuts'),
extractors: getMerged('extractors'),
},
)

return merged
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Expand Up @@ -2,3 +2,4 @@ export * from './types'
export * from './utils'
export * from './extractors'
export * from './generator'
export * from './config'
48 changes: 46 additions & 2 deletions test/config.test.ts
@@ -1,8 +1,8 @@
import type { Preset, UserConfig } from '@unocss/core'
import { createGenerator } from '@unocss/core'
import { createGenerator, mergeConfigs } from '@unocss/core'
import type { Theme } from '@unocss/preset-mini'
import presetMini from '@unocss/preset-mini'
import { describe, expect, test } from 'vitest'
import { describe, expect, it, test } from 'vitest'

describe('config', () => {
const createUno = (userConfig: UserConfig) => {
Expand Down Expand Up @@ -133,3 +133,47 @@ describe('config', () => {
`)
})
})

describe('mergeConfigs', () => {
it('basic', () => {
expect(mergeConfigs([
{
shortcuts: {
foo: 'string',
},
},
{
shortcuts: [
{
bar: 'string',
},
[/a/i, () => 'a'],
],
},
]))
.toMatchInlineSnapshot(`
{
"extractors": [],
"postprocess": [],
"preflights": [],
"preprocess": [],
"presets": [],
"rules": [],
"safelist": [],
"shortcuts": [
{
"foo": "string",
},
{
"bar": "string",
},
[
/a/i,
[Function],
],
],
"variants": [],
}
`)
})
})

1 comment on commit c53d291

@jd-solanki
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks 😇

Please sign in to comment.