本文整理汇总了TypeScript中babel-types.blockStatement函数的典型用法代码示例。如果您正苦于以下问题:TypeScript blockStatement函数的具体用法?TypeScript blockStatement怎么用?TypeScript blockStatement使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了blockStatement函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: generateAnonymousState
export function generateAnonymousState (
scope: Scope,
expression: NodePath<t.Expression>,
refIds: Set<t.Identifier>,
isLogical?: boolean
) {
let variableName = `anonymousState_${scope.generateUid()}`
let statementParent = expression.getStatementParent()
if (!statementParent) {
throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
}
const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
const ifExpr = jsx.findParent(p => p.isIfStatement())
const blockStatement = jsx.findParent(p => p.isBlockStatement() && p.parentPath === ifExpr) as NodePath<t.BlockStatement>
const expr = setParentCondition(jsx, cloneDeep(expression.node))
if (!callExpr) {
refIds.add(t.identifier(variableName))
statementParent.insertBefore(
buildConstVariableDeclaration(variableName, expr)
)
if (blockStatement && blockStatement.isBlockStatement()) {
blockStatement.traverse({
VariableDeclarator: (p) => {
const { id, init } = p.node
if (t.isIdentifier(id)) {
const newId = scope.generateDeclaredUidIdentifier('$' + id.name)
refIds.forEach((refId) => {
if (refId.name === variableName && !variableName.startsWith('_$')) {
refIds.delete(refId)
}
})
variableName = newId.name
refIds.add(t.identifier(variableName))
blockStatement.scope.rename(id.name, newId.name)
p.parentPath.replaceWith(
template('ID = INIT;')({ ID: newId, INIT: init })
)
}
}
})
}
} else {
variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
const func = callExpr.node.arguments[0]
if (t.isArrowFunctionExpression(func)) {
if (!t.isBlockStatement(func.body)) {
func.body = t.blockStatement([
buildConstVariableDeclaration(variableName, expr),
t.returnStatement(func.body)
])
} else {
func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr))
}
}
}
const id = t.identifier(variableName)
expression.replaceWith(id)
return id
}
示例2: transformLoop
function transformLoop (
name: string,
attr: NodePath<t.JSXAttribute>,
jsx: NodePath<t.JSXElement>,
value: AttrValue
) {
if (name !== WX_FOR) {
return
}
if (!value || !t.isJSXExpressionContainer(value)) {
throw new Error('wx:for 的值必须使用 "{{}}" 包裹')
}
attr.remove()
let item = t.stringLiteral('item')
let index = t.stringLiteral('index')
jsx
.get('openingElement')
.get('attributes')
.forEach(p => {
const node = p.node
if (node.name.name === WX_FOR_ITEM) {
if (!node.value || !t.isStringLiteral(node.value)) {
throw new Error(WX_FOR_ITEM + ' 的值必须是一个字符串')
}
item = node.value
p.remove()
}
if (node.name.name === WX_FOR_INDEX) {
if (!node.value || !t.isStringLiteral(node.value)) {
throw new Error(WX_FOR_INDEX + ' 的值必须是一个字符串')
}
index = node.value
p.remove()
}
if (node.name.name === WX_KEY) {
p.get('name').replaceWith(t.jSXIdentifier('key'))
}
})
const replacement = t.jSXExpressionContainer(
t.callExpression(
t.memberExpression(value.expression, t.identifier('map')),
[
t.arrowFunctionExpression(
[t.identifier(item.value), t.identifier(index.value)],
t.blockStatement([t.returnStatement(jsx.node)])
)
]
)
)
const block = buildBlockElement()
block.children = [replacement]
jsx.replaceWith(block)
}
示例3: generateAnonymousState
export function generateAnonymousState (
scope: Scope,
expression: NodePath<t.Expression>,
refIds: Set<t.Identifier>,
isLogical?: boolean
) {
let variableName = `anonymousState_${scope.generateUid()}`
let statementParent = expression.getStatementParent()
if (!statementParent) {
throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
}
const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
const conditionExpr = jsx.findParent(p => p.isConditionalExpression())
const logicExpr = jsx.findParent(p => p.isLogicalExpression({ operator: '&&' }))
let expr = cloneDeep(expression.node)
if (conditionExpr && conditionExpr.isConditionalExpression()) {
const consequent = conditionExpr.get('consequent')
if (consequent === jsx || jsx.findParent(p => p === consequent)) {
expr = t.conditionalExpression(conditionExpr.get('test').node as any, expr, t.nullLiteral())
}
}
if (logicExpr && logicExpr.isLogicalExpression({ operator: '&&' })) {
const consequent = logicExpr.get('right')
if (consequent === jsx || jsx.findParent(p => p === consequent)) {
expr = t.conditionalExpression(logicExpr.get('left').node as any, expr, t.nullLiteral())
}
}
if (!callExpr) {
refIds.add(t.identifier(variableName))
statementParent.insertBefore(
buildConstVariableDeclaration(variableName, expr)
)
} else {
variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
const func = callExpr.node.arguments[0]
if (t.isArrowFunctionExpression(func)) {
if (!t.isBlockStatement(func.body)) {
func.body = t.blockStatement([
buildConstVariableDeclaration(variableName, expr),
t.returnStatement(func.body)
])
} else {
statementParent.insertBefore(
buildConstVariableDeclaration(variableName, expr)
)
}
}
}
expression.replaceWith(
t.identifier(variableName)
)
}
示例4: buildRender
export function buildRender (
returned: t.Expression,
stateKeys: string[],
propsKeys: string[],
templateType?: string | never[]
) {
const returnStatement: t.Statement[] = [t.returnStatement(returned)]
if (stateKeys.length) {
const stateDecl = t.variableDeclaration('const', [
t.variableDeclarator(
t.objectPattern(Array.from(new Set(stateKeys)).filter(s => !propsKeys.includes(s)).map(s =>
t.objectProperty(t.identifier(s), t.identifier(s))
) as any),
t.memberExpression(t.thisExpression(), t.identifier('state'))
)
])
returnStatement.unshift(stateDecl)
}
if (propsKeys.length) {
let patterns = t.objectPattern(Array.from(new Set(propsKeys)).map(s =>
t.objectProperty(t.identifier(s), t.identifier(s))
) as any)
if (typeof templateType === 'string') {
patterns = t.objectPattern([
t.objectProperty(
t.identifier('data'),
templateType === 'wxParseData'
? t.objectPattern([t.objectProperty(t.identifier('wxParseData'), t.identifier('wxParseData')) as any]) as any
: t.identifier(templateType)
) as any
])
} else if (Array.isArray(templateType)) {
patterns = t.objectPattern([
t.objectProperty(t.identifier('data'), patterns as any) as any
])
}
const stateDecl = t.variableDeclaration('const', [
t.variableDeclarator(
patterns,
t.memberExpression(t.thisExpression(), t.identifier('props'))
)
])
returnStatement.unshift(stateDecl)
}
return t.classMethod(
'method',
t.identifier('render'),
[],
t.blockStatement(returnStatement)
)
}
示例5: transform
//.........这里部分代码省略.........
const bindingPath = binding.path.parentPath
if (bindingPath.isImportDeclaration()) {
const source = bindingPath.node.source
try {
const p = fs.existsSync(source.value + '.js') ? source.value + '.js' : source.value + '.tsx'
const code = fs.readFileSync(p, 'utf8')
componentProperies = transform({
isRoot: false,
isApp: false,
code,
isTyped: true,
sourcePath: source.value,
outputPath: source.value
}).componentProperies
} catch (error) {
//
}
}
}
}
},
ClassExpression (path) {
mainClass = path as any
},
ClassMethod (path) {
if (t.isIdentifier(path.node.key) && path.node.key.name === 'render') {
renderMethod = path
}
},
IfStatement (path) {
const consequent = path.get('consequent')
if (!consequent.isBlockStatement()) {
consequent.replaceWith(
t.blockStatement([
consequent.node as any
])
)
}
},
CallExpression (path) {
const callee = path.get('callee')
if (isContainJSXElement(path)) {
return
}
if (callee.isReferencedMemberExpression()) {
const id = findFirstIdentifierFromMemberExpression(callee.node)
const calleeIds = getIdsFromMemberProps(callee.node)
if (t.isIdentifier(id) && id.name.startsWith('on') && Adapters.alipay !== Adapter.type) {
const fullPath = buildFullPathThisPropsRef(id, calleeIds, path)
if (fullPath) {
path.replaceWith(
t.callExpression(
fullPath,
path.node.arguments
)
)
}
}
}
if (callee.isReferencedIdentifier()) {
const id = callee.node
const ids = [id.name]
if (t.isIdentifier(id) && id.name.startsWith('on')) {
const fullPath = buildFullPathThisPropsRef(id, ids, path)
if (fullPath) {
示例6: parseAst
//.........这里部分代码省略.........
needExportDefault = true
astPath.remove()
}
}
},
ExportNamedDeclaration (astPath) {
const node = astPath.node
const source = node.source
if (source && source.type === 'StringLiteral') {
const value = source.value
analyzeImportUrl({ astPath, value, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
}
},
ExportAllDeclaration (astPath) {
const node = astPath.node
const source = node.source
if (source && source.type === 'StringLiteral') {
const value = source.value
analyzeImportUrl({ astPath, value, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
}
},
Program: {
exit (astPath) {
astPath.traverse({
ClassBody (astPath) {
if (isQuickApp) {
const node = astPath.node
if (!hasComponentWillMount) {
node.body.push(t.classMethod(
'method', t.identifier('hasComponentWillMount'), [],
t.blockStatement([]), false, false))
}
if (!hasComponentDidShow) {
node.body.push(t.classMethod(
'method', t.identifier('componentDidShow'), [],
t.blockStatement([]), false, false))
}
if (!hasComponentDidHide) {
node.body.push(t.classMethod(
'method', t.identifier('componentDidHide'), [],
t.blockStatement([]), false, false))
}
node.body.push(t.classMethod(
'method', t.identifier('__listenToSetNavigationBarEvent'), [],
t.blockStatement([convertSourceStringToAstExpression(
`if (!Taro.eventCenter.callbacks['TaroEvent:setNavigationBar']) {
Taro.eventCenter.on('TaroEvent:setNavigationBar', params => {
if (params.title) {
this.$scope.$page.setTitleBar({ text: params.title })
}
if (params.frontColor) {
this.$scope.$page.setTitleBar({ textColor: params.frontColor })
}
if (params.backgroundColor) {
this.$scope.$page.setTitleBar({ backgroundColor: params.backgroundColor })
}
})
}`
)]), false, false))
node.body.push(t.classMethod(
'method', t.identifier('__offListenToSetNavigationBarEvent'), [],
t.blockStatement([convertSourceStringToAstExpression(
`Taro.eventCenter.off('TaroEvent:setNavigationBar')`
示例7: transformLoop
function transformLoop (
name: string,
attr: NodePath<t.JSXAttribute>,
jsx: NodePath<t.JSXElement>,
value: AttrValue
) {
const jsxElement = jsx.get('openingElement')
if (!jsxElement.node) {
return
}
const attrs = jsxElement.get('attributes').map(a => a.node)
const wxForItem = attrs.find(a => a.name.name === WX_FOR_ITEM)
const hasSinglewxForItem = wxForItem && wxForItem.value && t.isJSXExpressionContainer(wxForItem.value)
if (hasSinglewxForItem || name === WX_FOR || name === 'wx:for-items') {
if (!value || !t.isJSXExpressionContainer(value)) {
throw new Error('wx:for 的值必须使用 "{{}}" 包裹')
}
attr.remove()
let item = t.stringLiteral('item')
let index = t.stringLiteral('index')
jsx
.get('openingElement')
.get('attributes')
.forEach(p => {
const node = p.node
if (node.name.name === WX_FOR_ITEM) {
if (!node.value || !t.isStringLiteral(node.value)) {
throw new Error(WX_FOR_ITEM + ' 的值必须是一个字符串')
}
item = node.value
p.remove()
}
if (node.name.name === WX_FOR_INDEX) {
if (!node.value || !t.isStringLiteral(node.value)) {
throw new Error(WX_FOR_INDEX + ' 的值必须是一个字符串')
}
index = node.value
p.remove()
}
})
const replacement = t.jSXExpressionContainer(
t.callExpression(
t.memberExpression(value.expression, t.identifier('map')),
[
t.arrowFunctionExpression(
[t.identifier(item.value), t.identifier(index.value)],
t.blockStatement([t.returnStatement(jsx.node)])
)
]
)
)
const block = buildBlockElement()
block.children = [replacement]
try {
jsx.replaceWith(block)
} catch (error) {
//
}
return {
item: item.value,
index: index.value
}
}
}
示例8: parsePage
//.........这里部分代码省略.........
if (prop.isObjectMethod()) {
const body = prop.get('body')
if (hasArguments) {
return t.classMethod('method', t.identifier(name), params, body.node)
}
return t.classProperty(
t.identifier(name),
t.arrowFunctionExpression(params, body.node, isAsync)
)
}
if (hasArguments && (value.isFunctionExpression() || value.isArrowFunctionExpression())) {
const method = t.classMethod('method', t.identifier(name), params, value.node.body as any)
method.async = isAsync
return method
}
const classProp = t.classProperty(
t.identifier(name),
value.isFunctionExpression() || value.isArrowFunctionExpression()
? t.arrowFunctionExpression(value.node.params, value.node.body, isAsync)
: value.node
) as any
if (staticProps.includes(name)) {
classProp.static = true
}
return classProp
})
if (globals.hasCatchTrue) {
classBody.push(t.classMethod('method', t.identifier('privateStopNoop'), [t.identifier('e')], t.blockStatement([
t.expressionStatement(
t.callExpression(
t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')),
[]
)
)
])))
}
if (defaultProps.length) {
let classProp = t.classProperty(t.identifier('defaultProps'), t.objectExpression(
defaultProps.map(p => t.objectProperty(t.identifier(p.name), p.value))
)) as any
classProp.static = true
classBody.unshift(classProp)
}
} else if (arg.isIdentifier()) {
weappConf = arg.node.name
} else {
throw codeFrameError(arg.node, `${componentType || '组件'} 的第一个参数必须是一个对象或变量才能转换。`)
}
if (json && t.isObjectExpression(json)) {
classBody.push(t.classProperty(t.identifier('config'), json))
}
if (componentType === 'App') {
let hasWillMount = false
const globalData = template(`this.$app.globalData = this.globalData`)()
for (const method of classBody) {
if (!method) {
continue
示例9: parsePage
//.........这里部分代码省略.........
}
}
if (propKey) {
propsKeys.push(propKey)
}
}
})
}
return t.classProperty(t.identifier('_observeProps'), t.arrayExpression(
observeProps.map(p => t.objectExpression([
t.objectProperty(
t.identifier('name'),
t.stringLiteral(p.name)
),
t.objectProperty(
t.identifier('observer'),
p.observer
)
]))
))
}
if (PageLifecycle.has(name)) {
const lifecycle = PageLifecycle.get(name)!
const node = value.node as
| t.FunctionExpression
| t.ArrowFunctionExpression
const method = t.classMethod(
'method',
t.identifier(lifecycle),
params,
node ? node.body as t.BlockStatement : (prop.get('body') as any).node
)
method.async = isAsync
return method
}
if (prop.isObjectMethod()) {
const body = prop.get('body')
return t.classProperty(
t.identifier(name),
t.arrowFunctionExpression(params, body.node, isAsync)
)
}
return t.classProperty(
t.identifier(name),
value.isFunctionExpression() || value.isArrowFunctionExpression()
? t.arrowFunctionExpression(value.node.params, value.node.body, isAsync)
: value.node
)
})
if (defaultProps.length) {
let classProp = t.classProperty(t.identifier('defaultProps'), t.objectExpression(
defaultProps.map(p => t.objectProperty(t.identifier(p.name), p.value))
)) as any
classProp.static = true
classBody.unshift(classProp)
}
if (json && t.isObjectExpression(json)) {
classBody.push(t.classProperty(t.identifier('config'), json))
}
if (componentType === 'App') {
let hasWillMount = false
const globalData = template(`this.$app.globalData = this.globalData`)()
for (const method of classBody) {
if (!method) {
continue
}
if (!t.isClassMethod(method)) {
continue
}
if (t.isIdentifier(method.key, { name: Lifecycle.componentWillMount })) {
hasWillMount = true
method.body.body.unshift(globalData)
}
}
if (!hasWillMount) {
classBody.push(
t.classMethod(
'method',
t.identifier(Lifecycle.componentWillMount),
[],
t.blockStatement([globalData])
)
)
}
}
const renderFunc = buildRender(returned, stateKeys, propsKeys)
return t.classDeclaration(
t.identifier(componentType === 'App' ? 'App' : defaultClassName),
t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
t.classBody(
classBody.concat(renderFunc)
),
[]
)
}
示例10: generateAnonymousState
export function generateAnonymousState (
scope: Scope,
expression: NodePath<t.Expression>,
refIds: Set<t.Identifier>,
isLogical?: boolean
) {
let variableName = `anonymousState_${scope.generateUid()}`
let statementParent = expression.getStatementParent()
if (!statementParent) {
throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
}
const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
const ifExpr = jsx.findParent(p => p.isIfStatement())
const blockStatement = jsx.findParent(p => p.isBlockStatement() && p.parentPath === ifExpr) as NodePath<t.BlockStatement>
const expr = setParentCondition(jsx, cloneDeep(expression.node))
if (!callExpr) {
refIds.add(t.identifier(variableName))
statementParent.insertBefore(
buildConstVariableDeclaration(variableName, expr)
)
if (blockStatement && blockStatement.isBlockStatement()) {
blockStatement.traverse({
VariableDeclarator: (path) => {
const { id, init } = path.node
const isArrowFunctionInJSX = path.findParent(p => p.isJSXAttribute() ||
(
p.isAssignmentExpression() && t.isMemberExpression(p.node.left) && t.isThisExpression(p.node.left.object)
&& t.isIdentifier(p.node.left.property) && p.node.left.property.name.startsWith('')
)
)
if (isArrowFunctionInJSX) {
return
}
if (t.isIdentifier(id) && !id.name.startsWith(LOOP_STATE)) {
const newId = scope.generateDeclaredUidIdentifier('$' + id.name)
refIds.forEach((refId) => {
if (refId.name === variableName && !variableName.startsWith('_$')) {
refIds.delete(refId)
}
})
variableName = newId.name
if (Adapter.type === Adapters.quickapp && variableName.startsWith('_$')) {
const newVarName = variableName.slice(2)
scope.rename(variableName, newVarName)
variableName = newVarName
}
refIds.add(t.identifier(variableName))
blockStatement.scope.rename(id.name, newId.name)
path.parentPath.replaceWith(
template('ID = INIT;')({ ID: newId, INIT: init })
)
}
}
})
}
} else {
variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
const func = callExpr.node.arguments[0]
if (t.isArrowFunctionExpression(func)) {
if (!t.isBlockStatement(func.body)) {
func.body = t.blockStatement([
buildConstVariableDeclaration(variableName, expr),
t.returnStatement(func.body)
])
} else {
if (ifExpr && ifExpr.isIfStatement() && ifExpr.findParent(p => p === callExpr)) {
const consequent = ifExpr.get('consequent')
const test = ifExpr.get('test')
if (consequent.isBlockStatement()) {
if (jsx === test || jsx.findParent(p => p === test)) {
func.body.body.unshift(buildConstVariableDeclaration(variableName, expr))
} else {
func.body.body.unshift(t.variableDeclaration('let', [t.variableDeclarator(t.identifier(variableName), t.nullLiteral())]))
consequent.node.body.push(t.expressionStatement(t.assignmentExpression(
'=',
t.identifier(variableName),
expr
)))
}
} else {
throw codeFrameError(consequent.node, 'if 表达式的结果必须由一个花括号包裹')
}
} else {
func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr))
}
}
}
}
const id = t.identifier(variableName)
expression.replaceWith(id)
return id
}