Skip to content

Commit

Permalink
feat: ignore className and other attrs in JSX extraction
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 10, 2021
1 parent f1bfb58 commit 2e0d277
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const world = 'World'
const a = `Hello ${world}`

const foo = <div className="h1 mt-4"/>
21 changes: 19 additions & 2 deletions src/extraction/parsers/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@ import { parse } from '@babel/parser'
import traverse from '@babel/traverse'
import { DefaultDynamicExtractionsRules, DefaultExtractionRules, ExtractionRule } from '../rules'
import { shouldExtract } from '../shouldExtract'
import { ExtractionBabelOptions } from './options'
import { DetectionResult } from '~/core/types'

const defaultOptions: Required<ExtractionBabelOptions> = {
ignoredJSXAttributes: ['class', 'className', 'key', 'style', 'ref', 'onClick'],
}

export function detect(
input: string,
rules: ExtractionRule[] = DefaultExtractionRules,
dynamicRules: ExtractionRule[] = DefaultDynamicExtractionsRules,
userOptions: ExtractionBabelOptions = {},
) {
const {
ignoredJSXAttributes,
} = Object.assign({}, defaultOptions, userOptions)

const detections: DetectionResult[] = []

const ast = parse(input, {
Expand Down Expand Up @@ -57,8 +67,8 @@ export function detect(
}

function recordIgnore(path: any) {
const fullStart = path?.node?.start
const fullEnd = path?.node?.end
const fullStart = path?.node?.start ?? path?.start
const fullEnd = path?.node?.end ?? path?.end

if (!fullStart || !fullEnd)
return
Expand All @@ -80,6 +90,13 @@ export function detect(
JSXText(path: any) {
handlePath(path, 'jsx-text')
},
// scan for jsx attributes
JSXElement(path: any) {
path?.node?.openingElement?.attributes?.forEach((i: any) => {
if (ignoredJSXAttributes.includes(i?.name?.name))
recordIgnore(i)
})
},
// ignore `console.xxx`
CallExpression(path: any) {
const callee = path.get('callee')
Expand Down
9 changes: 9 additions & 0 deletions src/extraction/parsers/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,12 @@ export interface ExtractionHTMLOptions {
*/
inlineText?: boolean
}

export interface ExtractionBabelOptions {
/**
* HTML tags to be ignored
*
* @default ['class', 'className', 'key', 'style', 'ref', 'onClick']
*/
ignoredJSXAttributes?: string[]
}

0 comments on commit 2e0d277

Please sign in to comment.