How to use @babel/types

Comprehensive @babel/types code examples:

How to use @babel/types.inheritLeadingComments:

58
59
60
61
62
63
64
65
66
67
68
function replaceWithMultiple(nodes) {
  var _pathCache$get;


  this.resync();
  nodes = this._verifyNodeList(nodes);
  t.inheritLeadingComments(nodes[0], this.node);
  t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
  (_pathCache$get = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get.delete(this.node);
  this.node = this.container[this.key] = null;
  const paths = this.insertAfter(nodes);

How to use @babel/types.removeProperties:

83
84
85
86
87
88
89
90
91
92
93
94
    if (context.visit(node, key)) return;
  }
};


traverse.clearNode = function (node, opts) {
  t.removeProperties(node, opts);
  cache.path.delete(node);
};


traverse.removeProperties = function (tree, opts) {

How to use @babel/types.inheritTrailingComments:

59
60
61
62
63
64
65
66
67
var _pathCache$get;

this.resync();
nodes = this._verifyNodeList(nodes);
t.inheritLeadingComments(nodes[0], this.node);
t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
(_pathCache$get = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get.delete(this.node);
this.node = this.container[this.key] = null;
const paths = this.insertAfter(nodes);

How to use @babel/types.ImportDeclaration:

53
54
55
56
57
58
59
60
61
62
traverse(jsAst, {
  // 监听整个ast节点
  Program(path) {
    // 添加import导入
    const importDefaultSpecifier = [types.ImportDefaultSpecifier(types.Identifier('PageMixins'))];
    const importDeclaration = types.ImportDeclaration(importDefaultSpecifier, types.StringLiteral('@/mixins/PageMixins'));
    path.get('body')[0].insertBefore(importDeclaration);
  },
  // export的监听
  ExportDefaultDeclaration(path) {

How to use @babel/types.detail:

342
343
344
345
346
347
348
349
350
351
const parentPath = path.parentPath

if (declarations.length > 1) {
    //处理for里面的var
    //如:for (var e = t.data.result.list, a = 0; a < e.length; a++)
    // for (var that = this, n = t.detail.value, o = that.moenylist, a = 0; a < o.length; a++) {
    //     if (o[a] == n) {}
    // }
    if (t.isForStatement(parentPath)) {
        //TODO: ? var 就处理一下,其他不管了

How to use @babel/types.IfStatement:

425
426
427
428
429
430
431
432
433
434
ConditionalExpression: {
        exit (path) {
            let { test, consequent, alternate } = path.node
            let new_consequent = t.BlockStatement([t.ExpressionStatement(consequent)])
            let new_alternate = t.BlockStatement([t.ExpressionStatement(alternate)])
            let if_node = t.IfStatement(test, new_consequent, new_alternate)
            path.replaceWithMultiple(if_node)
            path.stop()
        }
    }

How to use @babel/types.toSequenceExpression:

183
184
185
186
187
188
189
190
191
192
193
194
  this.node = this.container[this.key] = node;
}


function replaceExpressionWithStatements(nodes) {
  this.resync();
  const toSequenceExpression = t.toSequenceExpression(nodes, this.scope);


  if (toSequenceExpression) {
    return this.replaceWith(toSequenceExpression)[0].get("expressions");
  }

How to use @babel/types.jSXFragment:

110
111
112
113
114
115
116
117
118
119
exArray.push(t.objectProperty(t.identifier('render'), t.arrowFunctionExpression([
  t.identifier('_'),
  t.identifier('record'),
], t.BlockStatement([
  t.returnStatement(
    t.jSXFragment(t.jsxOpeningFragment(), t.jsxClosingFragment(), [
      ...actionsExpressionArray,
      blankLine
    ])
  )

How to use @babel/types.objectTypeSpreadProperty:

576
577
578
579
580
581
582
583
584
585
  }: Selection,
  state: State,
  concreteType: ?string,
) {
  if (kind === 'ModuleImport') {
    return t.objectTypeSpreadProperty(
      t.genericTypeAnnotation(t.identifier(key)),
    );
  }
  if (schemaName === '__typename' && concreteType) {

How to use @babel/types.forInStatement:

366
367
368
369
370
371
372
373
374
375
  let body = [];
  contexts.forEach(child => {
    body.push(this.visitChildren(child));
  });

  return t.forInStatement(left, right, t.blockStatement(flatten(body)));
}

visitRaise_stmt(ctx) {
  return t.throwStatement(t.identifier(ctx.getText()));

How to use @babel/types.toKeyAlias:

29
30
31
32
33
34
35
36
37
38
39
40


  return "value";
}


function push(mutatorMap, node, kind, file, scope) {
  const alias = t.toKeyAlias(node);
  let map = {};
  if ((0, _has.default)(mutatorMap, alias)) map = mutatorMap[alias];
  mutatorMap[alias] = map;
  map._inherits = map._inherits || [];

How to use @babel/types.fun:

828
829
830
831
832
833
834
835
836
837
838


var useScopeList = {}
/**
 * var t = getApp() --> var app = getApp()
 * t.siteInfo ->> app.globalData.siteInfo
 * t.fun() --> app.globalData.fun()
 *
 * @param {*} ast
 */
function getAppHandleByAst (ast) {

How to use @babel/types.TemplateElement:

58
59
60
61
62
63
64
65
66
67

const newQuasis = prefix.concat(suffix).concat('').concat('').slice(0, 2)
active.push(
  t.TemplateLiteral(
    newQuasis.map((item, idx) => (
      t.TemplateElement(
        {
          raw: item,
          value: item,
        },

How to use @babel/types.replace:

360
361
362
363
364
365
366
367
368
369
function trimWhitespace(text) {
  text = text.replace(/\r/g, "");
  if (/\n/g.test(text)) {
    text = text
      .split("\n")
      .map((t, i) => (i ? t.replace(/^\s*/g, "") : t))
      .filter(s => !/^\s*$/.test(s))
      .join(" ");
  }
  return text.replace(/\s+/g, " ");

How to use @babel/types.importNamespaceSpecifier:

57
58
59
60
61
62
63
64
65
66
function createImportDefaultSpecifier(id) {
  return types.importDefaultSpecifier(types.identifier(id));
}

function createImportNamespaceSpecifier(id) {
  return types.importNamespaceSpecifier(types.identifier(id));
}

function createImportSpecifier(local, imported) {
  return types.importSpecifier(

How to use @babel/types.converter:

185
186
187
188
189
190
191
192
193
194
// 	var f = '<a href="' + (h = s.helper.escapeCharacters(h, "*_", !1)) + '"';
// 	return "" !== d && null !== d && (d = d.replace(/"/g, "&quot;"), f += ' title="' + (d = s.helper
// 			.escapeCharacters(d, "*_", !1)) + '"'),
// 		f += ">" + u + "</a>";
// };
// return e = (e = t.converter._dispatch("anchors.before", e, r, t)).replace(
// 		/(\[((?:\[[^\]]*]|[^\[\]])*)][ ]?(?:\n[ ]*)?\[(.*?)])()()()()/g, n),
// 	e = e.replace(
// 		/(\[((?:\[[^\]]*]|[^\[\]])*)]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
// 		n),

How to use @babel/types.ExportDefaultDeclaration:

50
51
52
53
54
55
56
57
58
59
// insert `export default ${identifier}(module)(xxx)`
if (t.isClassDeclaration(declaration) || t.isFunctionDeclaration(declaration)) {
  if (t.isIdentifier(declaration.id)) {
    path.replaceWith(declaration);
    insertNodes.push(
      t.ExportDefaultDeclaration(
        t.callExpression(
          t.identifier(identifier),
          [declaration.id]
        )

How to use @babel/types.toComputedKey:

55
56
57
58
59
60
61
62
63
64
}

let key, value;

if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) {
  key = t.toComputedKey(node, node.key);
}

if (t.isProperty(node)) {
  value = node.value;

How to use @babel/types.inheritsComments:

80
81
82
83
84
85
86
87
88
89
    scope
  });
}

if (value) {
  t.inheritsComments(value, node);
  map[kind] = value;
}

return map;

How to use @babel/types.isVar:

121
122
123
124
125
126
127
128
129
130
131
132
exports.BlockScoped = BlockScoped;
const Var = {
  types: ["VariableDeclaration"],


  checkPath(path) {
    return t.isVar(path.node);
  }


};
exports.Var = Var;

How to use @babel/types.isObjectPattern:

48
49
50
51
52
53
54
55
56
57
  parts.push(node.name);
} else if (t.isLiteral(node)) {
  parts.push(node.value);
} else if (t.isCallExpression(node)) {
  gatherNodeParts(node.callee, parts);
} else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
  for (const prop of node.properties) {
    gatherNodeParts(prop.key || prop.argument, parts);
  }
} else if (t.isPrivateName(node)) {

How to use @babel/types.isScope:

98
99
100
101
102
103
104
105
106
107
108
109
exports.Expression = Expression;
const Scope = {
  types: ["Scopable", "Pattern"],


  checkPath(path) {
    return t.isScope(path.node, path.parent);
  }


};
exports.Scope = Scope;

How to use @babel/types.isIndexedAccessType:

116
117
118
119
120
121
122
123
124
125
126
function UnionTypeAnnotation(node, parent) {
  return t.isArrayTypeAnnotation(parent) || t.isNullableTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isUnionTypeAnnotation(parent);
}


function OptionalIndexedAccessType(node, parent) {
  return t.isIndexedAccessType(parent, {
    objectType: node
  });
}

How to use @babel/types.m:

136
137
138
139
140
141
142
143
144
145
146
}


module.exports = {
  noScope: false,
  MemberExpression (path) {
    if ( // t.m(123)
      t.isIdentifier(path.node.object) &&
      this.options.filterModules.includes(path.node.object.name)
    ) {
      path.skip()

How to use @babel/types.isBlockScoped:

112
113
114
115
116
117
118
119
120
121
122
123


};
exports.Referenced = Referenced;
const BlockScoped = {
  checkPath(path) {
    return t.isBlockScoped(path.node);
  }


};
exports.BlockScoped = BlockScoped;

How to use @babel/types.call:

108
109
110
111
112
113
114
115
116
117
  y &&
    (t =
      op[0] & 2
        ? y['return']
        : op[0]
        ? y['throw'] || ((t = y['return']) && t.call(y), 0)
        : y.next) &&
    !(t = t.call(y, op[1])).done)
)
  return t

How to use @babel/types.TemplateLiteral:

56
57
58
59
60
61
62
63
64
65
const suffix = !isLast && !/^\s/.test(quasis[index + 1].node.value.raw) ?
  [quasis[index + 1].node.value.raw.split(' ').shift()] : []

const newQuasis = prefix.concat(suffix).concat('').concat('').slice(0, 2)
active.push(
  t.TemplateLiteral(
    newQuasis.map((item, idx) => (
      t.TemplateElement(
        {
          raw: item,

How to use @babel/types.yieldExpression:

27
28
29
30
31
32
33
34
35
36
t.blockStatement(
  [ // body
    t.variableDeclaration("const", [ // declaration
      t.variableDeclarator(
        t.identifier('response'),
        t.yieldExpression(
          t.callExpression(
            t.identifier('call'),
            [
              t.identifier(injectVariableKey),

How to use @babel/types.isUnaryLike:

95
96
97
98
99
100
101
102
103
104

if (isClassExtendsClause(node, parent)) {
  return true;
}

if (hasPostfixPart(node, parent) || t.isUnaryLike(parent) || t.isAwaitExpression(parent)) {
  return true;
}

if (t.isBinary(parent)) {

How to use @babel/types.isTSUnknownKeyword:

16
17
18
19
20
21
22
23
24
25
 * @returns {string}
 */
function typeToPartialGuard(type, tg) {
  if (t.isTSNeverKeyword(type)) {
    return "(() => false)";
  } else if (t.isTSAnyKeyword(type) || t.isTSUnknownKeyword(type)) {
    return "(() => true)";
  } else if (t.isTSUndefinedKeyword(type)) {
    return `${tg}.isUndefined`;
  } else if (t.isTSNullKeyword(type)) {

@babel/types functions:

Sorted by popularity