Skip to content

Commit

Permalink
Merge branch 'main' into issue-3807
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jun 11, 2024
2 parents e9389ff + c7f6311 commit 9c5976f
Show file tree
Hide file tree
Showing 19 changed files with 11,140 additions and 12,247 deletions.
22 changes: 12 additions & 10 deletions docs/config/layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,17 @@ outputToCssLayers: true
You can change the CSS Layer names with:

```ts
outputToCssLayers: (layer) => {
// The default layer will be output to the "utilities" CSS layer.
if (layer === 'default')
return 'utilities'

// The shortcuts layer will be output to the "shortcuts" sublayer the of "utilities" CSS layer.
if (layer === 'shortcuts')
return 'utilities.shortcuts'

// All other layers will just use their name as the CSS layer name.
outputToCssLayers: {
cssLayerName: (layer) => {
// The default layer will be output to the "utilities" CSS layer.
if (layer === 'default')
return 'utilities'

// The shortcuts layer will be output to the "shortcuts" sublayer the of "utilities" CSS layer.
if (layer === 'shortcuts')
return 'utilities.shortcuts'

// All other layers will just use their name as the CSS layer name.
}
}
```
28 changes: 28 additions & 0 deletions docs/integrations/vite.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,34 @@ export default defineConfig({

<ContentExample :item="playgrounds['vite-elm']" class="Link" integrations />

## Legacy

If `@vitejs/plugin-legacy` with `renderModernChunks: false`, your need add it to `unocss` option

```ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Unocss from 'unocss/vite'
import { presetUno } from 'unocss'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
plugins: [
vue(),
Unocss({
presets: [presetUno()],
legacy: {
renderModernChunks: false,
},
}),
legacy({
targets: ['defaults', 'not IE 11'],
renderModernChunks: false,
}),
],
})
```

## License

- MIT License &copy; 2021-PRESENT [Anthony Fu](https://github.com/antfu)
6 changes: 6 additions & 0 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,12 @@ export interface UserOnlyOptions<Theme extends object = object> {
* @default 'build'
*/
envMode?: 'dev' | 'build'
/**
* legacy.renderModernChunks need to be consistent with @vitejs/plugin-legacy
*/
legacy?: {
renderModernChunks: boolean
}
}

/**
Expand Down
9 changes: 7 additions & 2 deletions packages/preset-mini/src/_utils/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { toArray } from '@unocss/core'
import { colorOpacityToString, colorToString, getStringComponent, getStringComponents, parseCssColor } from '@unocss/rule-utils'
import type { Theme } from '../theme'
import { h } from './handlers'
import { cssMathFnRE, directionMap, globalKeywords, xyzArray, xyzMap } from './mappings'
import { cssMathFnRE, cssVarFnRE, directionMap, globalKeywords, xyzArray, xyzMap } from './mappings'
import { bracketTypeRe, numberWithUnitRE, splitComma } from './handlers/regex'

export const CONTROL_MINI_NO_NEGATIVE = '$$mini-no-negative'
Expand Down Expand Up @@ -244,16 +244,21 @@ export function colorableShadows(shadows: string | string[], colorVar: string) {
}

let colorVarValue = ''
const lastComp = components.at(-1)
if (parseCssColor(components.at(0))) {
const color = parseCssColor(components.shift())
if (color)
colorVarValue = `, ${colorToString(color)}`
}
else if (parseCssColor(components.at(-1))) {
else if (parseCssColor(lastComp)) {
const color = parseCssColor(components.pop())
if (color)
colorVarValue = `, ${colorToString(color)}`
}
else if (lastComp && cssVarFnRE.test(lastComp)) {
const color = components.pop()!
colorVarValue = `, ${color}`
}

colored.push(`${isInset ? 'inset ' : ''}${components.join(' ')} var(${colorVar}${colorVarValue})`)
}
Expand Down
7 changes: 4 additions & 3 deletions packages/transformer-attributify-jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ export default function transformerAttributifyJsx(options: TransformerAttributif
idFilter,
async transform(code, _, { uno }) {
const tasks: Promise<void>[] = []

const attributify = uno.config.presets.find(i => i.name === '@unocss/preset-attributify')
const attributifyPrefix = attributify?.options?.prefix ?? 'un-'
for (const item of Array.from(code.original.matchAll(elementRE))) {
// Get the length of the className part, and replace it with the equal length of empty string
let attributifyPart = item[2]
Expand Down Expand Up @@ -103,8 +104,8 @@ export default function transformerAttributifyJsx(options: TransformerAttributif
const matchedRule = attr[0].replace(/:/, '-')
if (matchedRule.includes('=') || isBlocked(matchedRule))
continue

tasks.push(uno.parseToken(matchedRule).then((matched) => {
const updatedMatchedRule = matchedRule.startsWith(attributifyPrefix) ? matchedRule.slice(attributifyPrefix.length) : matchedRule
tasks.push(uno.parseToken(updatedMatchedRule).then((matched) => {
if (matched) {
const startIdx = (item.index || 0) + (attr.index || 0) + item[0].indexOf(item[2])
const endIdx = startIdx + matchedRule.length
Expand Down
7 changes: 6 additions & 1 deletion packages/vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@ export default function UnocssPlugin<Theme extends object>(
defaults: UserConfigDefaults = {},
): Plugin[] {
const ctx = createContext<VitePluginConfig>(configOrPath as any, {
envMode: process.env.NODE_ENV === 'development' ? 'dev' : 'build',
envMode: process.env.NODE_ENV === 'development'
? 'dev'
: 'build',
...defaults,
legacy: typeof configOrPath !== 'string'
? (configOrPath?.legacy || { renderModernChunks: true })
: { renderModernChunks: true },
})
const inlineConfig = (configOrPath && typeof configOrPath !== 'string') ? configOrPath : {}
const mode = inlineConfig.mode ?? 'global'
Expand Down
17 changes: 11 additions & 6 deletions packages/vite/src/modes/global/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,10 @@ export function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>
// we inject a hash to chunk before the dist hash calculation to make sure
// the hash is different when unocss changes
async renderChunk(_, chunk, options) {
if (isLegacyChunk(chunk, options))
return null
const isLegacy = isLegacyChunk(chunk, options)

if (isLegacy && (!ctx.uno.config.legacy || ctx.uno.config.legacy.renderModernChunks))
return null
// skip hash generation on non-entry chunk
if (!Object.keys(chunk.modules).some(i => RESOLVED_ID_RE.test(i)))
return null
Expand All @@ -174,11 +175,16 @@ export function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>
const fakeCssId = `${viteConfig.root}/${chunk.fileName}-unocss-hash.css`
css = await applyCssTransform(css, fakeCssId, options.dir, this)

const hash = getHash(css)
const transformHandler = 'handler' in cssPost.transform!
? cssPost.transform.handler
: cssPost.transform!
await transformHandler.call({} as any, getHashPlaceholder(hash), fakeCssId)
if (isLegacy) {
await transformHandler.call({} as any, css, '/__uno.css')
}
else {
const hash = getHash(css)
await transformHandler.call({} as any, getHashPlaceholder(hash), fakeCssId)
}

// fool the css plugin to generate the css in corresponding chunk
chunk.modules[fakeCssId] = {
Expand Down Expand Up @@ -220,8 +226,7 @@ export function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>
const result = await generateAll()
const mappedVfsLayer = Array.from(vfsLayers).map(layer => layer === LAYER_MARK_ALL ? layer : layer.replace(/^_/, ''))
const importStatements = result.getLayer(LAYER_IMPORTS)
const cssWithLayers = Array.from(vfsLayers).map(layer => `${importStatements ?? ''}#--unocss-layer-start--${layer}--{start:${layer}} ${
layer === LAYER_MARK_ALL
const cssWithLayers = Array.from(vfsLayers).map(layer => `${importStatements ?? ''}#--unocss-layer-start--${layer}--{start:${layer}} ${layer === LAYER_MARK_ALL
? result.getLayers(undefined, [...mappedVfsLayer, LAYER_IMPORTS])
: (result.getLayer(layer.replace(/^_/, '')) || '')
} #--unocss-layer-end--${layer}--{end:${layer}}`).join('')
Expand Down
Loading

0 comments on commit 9c5976f

Please sign in to comment.