Skip to content

Commit

Permalink
fix: comment might be undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Jun 21, 2023
1 parent 7ad4259 commit e4c046f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface ConvertUnit {
}

export type PxtoremOptions = Partial<{
rootValue: number | ((input: Input) => number)
rootValue: number | ((input: Input | undefined) => number)
unitToConvert: string
unitPrecision: number
selectorBlackList: (string | RegExp)[]
Expand Down Expand Up @@ -71,10 +71,10 @@ function pxtorem(options?: PxtoremOptions) {
originOpts: ORIGINAL_OPTIONS,
}

setupCurrentOptions(h as any, firstNode)
setupCurrentOptions(h as any, { node, comment: firstNode })
},
Comment(node, h) {
setupCurrentOptions(h as any, node)
setupCurrentOptions(h as any, { node, comment: node })
},
CommentExit(comment) {
if (comment.text.match(isPxtoremReg)?.length) {
Expand Down
19 changes: 14 additions & 5 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AtRule, ChildNode, Comment, Container, Declaration, Rule } from 'postcss'
import type { AtRule, ChildNode, Comment, Container, Declaration, Root, Rule } from 'postcss'
import type { ConvertUnit, PxtoremOptions } from '..'
import { defaultOptions } from '..'
import { MAYBE_REGEXP } from './constant'
Expand Down Expand Up @@ -202,15 +202,24 @@ export type H = {
}
}

export function setupCurrentOptions(h: H, node: Comment | ChildNode) {
export function setupCurrentOptions(
h: H,
{
node,
comment,
}: {
node?: ChildNode | Root
comment?: ChildNode | Comment
},
) {
const opts = h[currentOptions].originOpts

const filePath = node?.source?.input.file

if ((node as Comment)?.text) {
if (isOptionComment(comment)) {
h[currentOptions].originOpts = {
...opts,
...getOptionsFromComment(node as Comment, opts.parseOptions),
...getOptionsFromComment(comment, opts.parseOptions),
}
}

Expand All @@ -223,7 +232,7 @@ export function setupCurrentOptions(h: H, node: Comment | ChildNode) {
return
}

h[currentOptions].rootValue = isFunction(opts.rootValue) ? opts.rootValue(node.source!.input) : opts.rootValue
h[currentOptions].rootValue = isFunction(opts.rootValue) ? opts.rootValue(node?.source!.input) : opts.rootValue

h[currentOptions].pxReplace = createPxReplace(h[currentOptions].rootValue, opts.unitPrecision, opts.minPixelValue)
}
Expand Down

0 comments on commit e4c046f

Please sign in to comment.