本文整理汇总了TypeScript中babel-traverse.NodePath.replaceWith方法的典型用法代码示例。如果您正苦于以下问题:TypeScript NodePath.replaceWith方法的具体用法?TypeScript NodePath.replaceWith怎么用?TypeScript NodePath.replaceWith使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babel-traverse.NodePath
的用法示例。
在下文中一共展示了NodePath.replaceWith方法的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: replaceJSXTextWithTextComponent
export function replaceJSXTextWithTextComponent (path: NodePath<t.JSXText | t.JSXExpressionContainer>) {
const parent = path.findParent(p => p.isJSXElement())
if (parent && parent.isJSXElement() && t.isJSXIdentifier(parent.node.openingElement.name) && parent.node.openingElement.name.name !== 'Text') {
path.replaceWith(t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier('Text'), []),
t.jSXClosingElement(t.jSXIdentifier('Text')),
[path.isJSXText() ? t.jSXText(path.node.value) : path.node]
))
}
}
示例3: 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)
}
示例4: 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)
)
}
示例5: parseModule
export function parseModule (jsx: NodePath<t.JSXElement>, dirPath: string, type: 'include' | 'import') {
const openingElement = jsx.get('openingElement')
const attrs = openingElement.get('attributes')
const src = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'src' }))
if (!src) {
throw new Error(`${type} 标签必须包含 \`src\` 属性`)
}
const value = src.get('value')
if (!value.isStringLiteral()) {
throw new Error(`${type} 标签的 src 属性值必须是一个字符串`)
}
const srcValue = value.node.value
if (type === 'import') {
const wxml = getWXMLsource(dirPath, srcValue, type)
const { imports } = parseWXML(resolve(dirPath, srcValue), wxml, true)
try {
jsx.remove()
} catch (error) {
//
}
return imports
} else {
const { wxml } = parseWXML(dirPath, getWXMLsource(dirPath, srcValue, type), true)
const block = buildBlockElement()
try {
if (wxml) {
block.children = [wxml as any]
jsx.replaceWith(wxml)
} else {
block.children = [t.jSXExpressionContainer(t.jSXEmptyExpression())]
jsx.replaceWith(block)
}
} catch (error) {
//
}
}
}
示例6: parseTemplate
export function parseTemplate (path: NodePath<t.JSXElement>, dirPath: string) {
const openingElement = path.get('openingElement')
const attrs = openingElement.get('attributes')
const is = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'is' }))
const data = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'data' }))
// const spread = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'spread' }))
const name = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'name' }))
const refIds = new Set<string>()
if (name) {
const value = name.node.value
if (value === null || !t.isStringLiteral(value)) {
throw new Error('template 的 `name` 属性只能是字符串')
}
const className = pascalName(value.value) + pascalName(basename(dirPath))
path.traverse({
Identifier (p) {
if (!p.isReferencedIdentifier()) {
return
}
const jsxExprContainer = p.findParent(p => p.isJSXExpressionContainer())
if (!jsxExprContainer || !jsxExprContainer.isJSXExpressionContainer()) {
return
}
refIds.add(p.node.name)
}
})
const block = buildBlockElement()
block.children = path.node.children
let render: t.ClassMethod
if (refIds.size === 0) {
// 无状态组件
render = buildRender(block, [], [])
} else if (refIds.size === 1) {
// 只有一个数据源
render = buildRender(block, [], Array.from(refIds), Array.from(refIds)[0])
} else {
// 使用 ...spread
render = buildRender(block, [], Array.from(refIds), [])
}
const classDecl = t.classDeclaration(
t.identifier(className),
t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
t.classBody([render!]),
[]
)
path.remove()
return {
name: className,
ast: classDecl
}
} else if (is) {
const value = is.node.value
if (!value) {
throw new Error('template 的 `is` 属性不能为空')
}
if (t.isStringLiteral(value)) {
const className = pascalName(value.value)
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
path.replaceWith(t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
t.jSXClosingElement(t.jSXIdentifier(className)),
[],
true
))
} else if (t.isJSXExpressionContainer(value)) {
if (t.isStringLiteral(value.expression)) {
const className = pascalName(value.expression.value)
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
path.replaceWith(t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
t.jSXClosingElement(t.jSXIdentifier(className)),
[],
true
))
} else if (t.isConditional(value.expression)) {
const { test, consequent, alternate } = value.expression
if (!t.isStringLiteral(consequent) || !t.isStringLiteral(alternate)) {
throw new Error('当 template is 标签是三元表达式时,他的两个值都必须为字符串')
}
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
const block = buildBlockElement()
block.children = [t.jSXExpressionContainer(t.conditionalExpression(
test,
t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier('Template'), attributes.concat(
[t.jSXAttribute(t.jSXIdentifier('is'), consequent)]
)),
t.jSXClosingElement(t.jSXIdentifier('Template')),
[],
//.........这里部分代码省略.........
示例7: transform
export default function transform (options: Options): TransformResult {
if (options.adapter) {
setAdapter(options.adapter)
}
if (Adapter.type === Adapters.swan) {
setLoopOriginal('privateOriginal')
}
setTransformOptions(options)
const code = options.isTyped
? ts.transpile(options.code, {
jsx: ts.JsxEmit.Preserve,
target: ts.ScriptTarget.ESNext,
importHelpers: true,
noEmitHelpers: true
})
: options.code
options.env = Object.assign({ 'process.env.TARO_ENV': options.adapter || 'weapp' }, options.env || {})
setting.sourceCode = code
// babel-traverse 无法生成 Hub
// 导致 Path#getSource|buildCodeFrameError 都无法直接使用
// 原因大概是 babylon.parse 没有生成 File 实例导致 scope 和 path 原型上都没有 `file`
// 将来升级到 babel@7 可以直接用 parse 而不是 transform
const ast = parse(code, {
parserOpts: {
sourceType: 'module',
plugins: [
'classProperties',
'jsx',
'flow',
'flowComment',
'trailingFunctionCommas',
'asyncFunctions',
'exponentiationOperator',
'asyncGenerators',
'objectRestSpread',
'decorators',
'dynamicImport'
] as any[]
},
plugins: [
require('babel-plugin-transform-flow-strip-types'),
[require('babel-plugin-transform-define').default, options.env]
].concat((process.env.NODE_ENV === 'test') ? [] : require('babel-plugin-remove-dead-code').default)
}).ast as t.File
if (options.isNormal) {
return { ast } as any
}
// transformFromAst(ast, code)
let result
const componentSourceMap = new Map<string, string[]>()
const imageSource = new Set<string>()
const importSources = new Set<string>()
let componentProperies: string[] = []
let mainClass!: NodePath<t.ClassDeclaration>
let storeName!: string
let renderMethod!: NodePath<t.ClassMethod>
let isImportTaro = false
traverse(ast, {
TemplateLiteral (path) {
const nodes: t.Expression[] = []
const { quasis, expressions } = path.node
let index = 0
if (path.parentPath.isTaggedTemplateExpression()) {
return
}
for (const elem of quasis) {
if (elem.value.cooked) {
nodes.push(t.stringLiteral(elem.value.cooked))
}
if (index < expressions.length) {
const expr = expressions[index++]
if (!t.isStringLiteral(expr, { value: '' })) {
nodes.push(expr)
}
}
}
// + 号连接符必须保证第一和第二个 node 都是字符串
if (!t.isStringLiteral(nodes[0]) && !t.isStringLiteral(nodes[1])) {
nodes.unshift(t.stringLiteral(''))
}
let root = nodes[0]
for (let i = 1; i < nodes.length; i++) {
root = t.binaryExpression('+', root, nodes[i])
}
path.replaceWith(root)
},
ClassDeclaration (path) {
mainClass = path
const superClass = path.node.superClass
if (t.isIdentifier(superClass)) {
const binding = path.scope.getBinding(superClass.name)
if (binding && binding.kind === 'module') {
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'
//.........这里部分代码省略.........
示例8: 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
}
}
}
示例9: 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
}
示例10: parseTemplate
export function parseTemplate (path: NodePath<t.JSXElement>, dirPath: string) {
if (!path.container) {
return
}
const openingElement = path.get('openingElement')
const attrs = openingElement.get('attributes')
const is = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'is' }))
const data = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'data' }))
// const spread = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'spread' }))
const name = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'name' }))
const refIds = new Set<string>()
const loopIds = new Set<string>()
let imports: any[] = []
if (name) {
const value = name.node.value
if (value === null || !t.isStringLiteral(value)) {
throw new Error('template 的 `name` 属性只能是字符串')
}
const className = buildTemplateName(value.value)
path.traverse(createWxmlVistor(loopIds, refIds, dirPath, [], imports))
const firstId = Array.from(refIds)[0]
refIds.forEach(id => {
if (loopIds.has(id) && id !== firstId) {
refIds.delete(id)
}
})
const block = buildBlockElement()
block.children = path.node.children
let render: t.ClassMethod
if (refIds.size === 0) {
// 无状态组件
render = buildRender(block, [], [])
} else if (refIds.size === 1) {
// 只有一个数据源
render = buildRender(block, [], Array.from(refIds), firstId)
} else {
// 使用 ...spread
render = buildRender(block, [], Array.from(refIds), [])
}
const classProp = t.classProperty(t.identifier('options'), t.objectExpression([
t.objectProperty(
t.identifier('addGlobalClass'),
t.booleanLiteral(true)
)
])) as any
classProp.static = true
const classDecl = t.classDeclaration(
t.identifier(className),
t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
t.classBody([render, classProp]),
[]
)
path.remove()
return {
name: className,
ast: classDecl
}
} else if (is) {
const value = is.node.value
if (!value) {
throw new Error('template 的 `is` 属性不能为空')
}
if (t.isStringLiteral(value)) {
const className = buildTemplateName(value.value)
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
path.replaceWith(t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
t.jSXClosingElement(t.jSXIdentifier(className)),
[],
true
))
} else if (t.isJSXExpressionContainer(value)) {
if (t.isStringLiteral(value.expression)) {
const className = buildTemplateName(value.expression.value)
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
path.replaceWith(t.jSXElement(
t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
t.jSXClosingElement(t.jSXIdentifier(className)),
[],
true
))
} else if (t.isConditional(value.expression)) {
const { test, consequent, alternate } = value.expression
if (!t.isStringLiteral(consequent) || !t.isStringLiteral(alternate)) {
throw new Error('当 template is 标签是三元表达式时,他的两个值都必须为字符串')
}
let attributes: t.JSXAttribute[] = []
if (data) {
attributes.push(data.node)
}
const block = buildBlockElement()
block.children = [t.jSXExpressionContainer(t.conditionalExpression(
//.........这里部分代码省略.........