Skip to content

Commit

Permalink
fix pug support in esm (#319)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
tjk and antfu committed May 9, 2023
1 parent 3f1e0da commit 4c535c9
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
6 changes: 6 additions & 0 deletions packages/plugin-utils/src/createUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { exclude, include, kebabCase, partition, slash } from './utils'
import { buildAliasTransformer, transformGroups } from './transforms'
import { applyExtractors as _applyExtractors } from './extractors/helper'
import { regexClassSplitter } from './regexes'
import { setPug } from './extractors'

export type CompletionsResult = ReturnType<typeof generateCompletions>
export type LayerName = 'base' | 'utilities' | 'components'
Expand Down Expand Up @@ -549,6 +550,11 @@ export function createUtils(
}

async function _init() {
try {
setPug((await import('pug')).default)
}
catch (e) {}

options = await resolveOptions(userOptions, utilsOptions, true)
files = []

Expand Down
7 changes: 2 additions & 5 deletions packages/plugin-utils/src/extractors/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { extname } from 'path'
import { uniq } from '@antfu/utils'
import type { Extractor, ExtractorResultDetailed } from 'windicss/types/interfaces'
import { DefaultExtractor } from './default'
import { PugExtractor } from './pug'
import { PugExtractor, getPug } from './pug'
import { SvelteExtractor } from './svelte'

export function getDefaultExtractors() {
Expand All @@ -13,15 +13,12 @@ export function getDefaultExtractors() {
},
]

// auto detect pug
try {
require.resolve('pug')
if (getPug()) {
extractors.push({
extractor: PugExtractor,
extensions: ['vue', 'pug'],
})
}
catch (e) {}

return extractors
}
Expand Down
16 changes: 13 additions & 3 deletions packages/plugin-utils/src/extractors/pug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@ import { DefaultExtractor } from '../extractors/default'

const regexTemplate = /<template.*?lang=['"]pug['"][^>]*?>\n([\s\S]*?\n)<\/template>/gm

let pug: typeof import('pug') | undefined

export function getPug() {
return pug
}

export function setPug(_pug: typeof import('pug')) {
pug = _pug
}

export function PugExtractor(code: string, id?: string): ExtractorResultDetailed {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Pug = require('pug') as typeof import('pug')
if (!pug)
return DefaultExtractor(code)

const compile = (code: string) => {
try {
return Pug.compile(code, { filename: id })()
return pug!.compile(code, { filename: id })()
// other build processes will catch pug errors
}
catch {}
Expand Down

0 comments on commit 4c535c9

Please sign in to comment.