How to use babel-types

Comprehensive babel-types code examples:

How to use babel-types.isSpreadElement:

130
131
132
133
134
135
136
137
138
139
140
141


const CallExpression = (next, ast, opts) => {
  const { callee } = ast;


  const memberChain = utils.maybeThreadMemberSyntax(next, ast).reverse();
  const isSpreadCall = ast.arguments.some(arg => bt.isSpreadElement(arg));
  const spreadArgs = isSpreadCall
    ? ArrayExpression(next, { elements: ast.arguments }, opts)
    : undefined;

How to use babel-types.isAssignmentPattern:

225
226
227
228
229
230
231
232
233
234
let returns = false;
let variables = [];
let members = [];

const params = node.params.reduce((acc, value) => {
  const param = t.isAssignmentPattern(value) ? value.left.name : value.name;

  acc.push(param);

  return acc;

How to use babel-types.forStatement:

63
64
65
66
67
68
69
70
71
72
  t.variableDeclarator(c.LENGTH, t.memberExpression(arr, c.LENGTH)),
  t.variableDeclarator(c.INDEX, t.numericLiteral(0)),
  t.variableDeclarator(key),
  t.variableDeclarator(c.KEY),
]),
t.forStatement(
  null,
  t.binaryExpression('<', c.INDEX, c.LENGTH),
  t.updateExpression('++', c.INDEX),
  t.blockStatement([

How to use babel-types.isExportNamedDeclaration:

15
16
17
18
19
20
21
22
23
24
if (!path) {
  return path;
}

if (t.isExportDefaultDeclaration(path) ||
  t.isExportNamedDeclaration(path) && path.has('declaration')) {
  path = path.get('declaration');
}

// var x = init;

How to use babel-types.isUpdateExpression:

101
102
103
104
105
106
107
108
109
110
if (path.node.object.type === 'ThisExpression' && datas.includes(path.node.property.name)) {
  path.get('object').replaceWithSourceString('this.data')
  //一定要判断一下是不是赋值操作
  if(
    (t.isAssignmentExpression(path.parentPath) && path.parentPath.get('left') === path) ||
    t.isUpdateExpression(path.parentPath)
  ) {
      // findParent
      const expressionStatement = path.findParent((parent) =>   
        parent.isExpressionStatement()

How to use babel-types.VariableDeclarator:

202
203
204
205
206
207
208
209
210
211
ThisExpression(path){
    //构建var _this = this
    let node = t.VariableDeclaration(
        'var',
        [
            t.VariableDeclarator(
                t.Identifier('_this'),
                t.Identifier('this')
            )
        ]

How to use babel-types.VariableDeclaration:

199
200
201
202
203
204
205
206
207
208
```js  
const Visitor = {
    //this表达式
    ThisExpression(path){
        //构建var _this = this
        let node = t.VariableDeclaration(
            'var',
            [
                t.VariableDeclarator(
                    t.Identifier('_this'),

How to use babel-types.isConditionalExpression:

47
48
49
50
51
52
53
54
55
56
    return state.file.opts.anu;
},
isLoopMap(astPath) {
    if (
        t.isJSXExpressionContainer(astPath.parentPath) ||
        t.isConditionalExpression(astPath.parentPath)
    ) {
        var callee = astPath.node.callee;
        return (
            callee.type == 'MemberExpression' &&

How to use babel-types.assertArrayExpression:

85
86
87
88
89
90
91
92
93
94
const ast = buildLiteralAst({
    foo: [ 'bar', 1 ]
});

babelTypes.assertStringLiteral(ast.properties[0].key, { value: 'foo' });
babelTypes.assertArrayExpression(ast.properties[0].value);

t.is(ast.properties[0].value.elements.length, 2);
babelTypes.assertStringLiteral(ast.properties[0].value.elements[0], { value: 'bar' });
babelTypes.assertNumericLiteral(ast.properties[0].value.elements[1], { value: 1 });

How to use babel-types.AssignmentExpression:

40
41
42
43
44
45
46
47
48
49
function makeCondition(node, state, inside) {
  if (inside) {
    return t.ConditionalExpression(
      t.BinaryExpression(
        '!=',
        t.AssignmentExpression('=', state.temp, node),
        t.NullLiteral(),
      ),
      inside,
      state.temp,

How to use babel-types.parenthesizedExpression:

159
160
161
162
163
164
165
166
167
168
} else {
  funcLines = funcLines.concat(rulesRegistration);
  funcLines.push(t.returnStatement(t.identifier(stylesheetId)));
}

createSelfInvoke = function (expr) { return t.parenthesizedExpression(expr); };

// wrapping up the self-invoke function
funcExpr = t.functionExpression(null, [], t.blockStatement(funcLines));
funcCallExpr = t.callExpression(

How to use babel-types.cloneDeep:

39
40
41
42
43
44
45
46
47
48
// 1.0.3 20180806
//let exportDeclaration = types.exportDefaultDeclaration(
//  types.assignmentExpression(
//    '=',
//    buildMemberExprssion(moduleRefer),
//    types.cloneDeep(declaration)
//  )
//)
// ^1.1.0 20190123
let exportDeclaration = types.exportDefaultDeclaration(

How to use babel-types.isSuper:

33
34
35
36
37
38
39
40
41
42
traverse(p.node, {
    enter (p) {
        
        if (t.isExpressionStatement(p.node) && 
            t.isCallExpression(p.node.expression) &&
            t.isSuper(p.node.expression.callee)) {
            
                p.remove();
                
        }

How to use babel-types.isModuleDeclaration:

0
1
2
3
4
5
6
7
8
9
'use strict';

const types = require('babel-types');

function isModuleNode(node) {
  return types.isModuleDeclaration(node);
}

function isClassMethodBody(block) {
  return types.isClassMethod(block.container);

How to use babel-types.FunctionExpression:

83
84
85
86
87
88
89
90
91
92
  let s =  t.returnStatement(childNode.expression);
  childNode = t.blockStatement([s])
}

let arrow = t.ArrowFunctionExpression(loopArgs.map(item=>t.Identifier(item)),childNode);
// let arrow = t.FunctionExpression(null, loopArgs.map(item=>t.Identifier(item)),childNode);

loopNode = t.JSXExpressionContainer(t.CallExpression(mapExpression,[
  arrow
]))

How to use babel-types.assertNumericLiteral:

74
75
76
77
78
79
80
81
82

    t.is(ast.properties.length, 2);
    babelTypes.assertStringLiteral(ast.properties[0].key, { value: 'foo' });
    babelTypes.assertStringLiteral(ast.properties[0].value, { value: 'bar' });
    babelTypes.assertStringLiteral(ast.properties[1].key, { value: 'baz' });
    babelTypes.assertNumericLiteral(ast.properties[1].value, { value: 1 });

    t.pass();
});

How to use babel-types.throwStatement:

51
52
53
54
55
56
57
58
59
60
    '>',
    t.binaryExpression('-', dateNow(), loopStart),
    t.numericLiteral(maxLoopTimeMs),
  ),
),
t.throwStatement(
  t.newExpression(t.identifier('RangeError'), [
    t.stringLiteral(
      'Potential infinite loop. You can disable this from settings.',
    ),

How to use babel-types.updateExpression:

66
67
68
69
70
71
72
73
74
75
  t.variableDeclarator(c.KEY),
]),
t.forStatement(
  null,
  t.binaryExpression('<', c.INDEX, c.LENGTH),
  t.updateExpression('++', c.INDEX),
  t.blockStatement([
    t.expressionStatement(t.assignmentExpression('=', key, c.INDEX)),
    t.expressionStatement(t.assignmentExpression('=', c.KEY, c.INDEX)),
    t.expressionStatement(t.assignmentExpression('+=', output, ConcatStringList(compile(branch.body)))),

How to use babel-types.isJSXSpreadAttribute:

200
201
202
203
204
205
206
207
208
209
deps.push({
  name,
  selfClosing: path.node.openingElement.selfClosing,
  props: path.node.openingElement.attributes.map(
    attr =>
      T.isJSXSpreadAttribute(attr)
        ? {
            name: '__spread',
            type: resolveType(attr.argument),
          }

How to use babel-types.isBooleanLiteral:

39
40
41
42
43
44
45
46
47
48
const args = path.node.arguments
if (
  t.isMemberExpression(callee) &&
  t.isThisExpression(callee.object) &&
  (callee.property.name === '__travel' || callee.property.value === '__travel') &&
  t.isBooleanLiteral(args[2]) &&
  args[2].value === true
) {
  isProps = true
  path.isProps = true

How to use babel-types.JSXOpeningElement:

7
8
9
10
11
12
13
14
15
16
const useCnpm = require('../utils/index').useCnpm();

module.exports = {
    createElement(nodeName, attrs, children) {
        return t.JSXElement(
            t.JSXOpeningElement(t.JSXIdentifier(nodeName), attrs, false),
            t.jSXClosingElement(t.JSXIdentifier(nodeName)),
            children
        );
    },

How to use babel-types.ConditionalExpression:

37
38
39
40
41
42
43
44
45
46
  }
}

function makeCondition(node, state, inside) {
  if (inside) {
    return t.ConditionalExpression(
      t.BinaryExpression(
        '!=',
        t.AssignmentExpression('=', state.temp, node),
        t.NullLiteral(),

How to use babel-types.decorator:

135
136
137
138
139
140
141
142
143
144
      isDefault: true
    })
  );

  classDeclaration.decorators.push(
    types.decorator(types.callExpression(types.identifier('loading'), []))
  );
}
if (this.props.reactbootstraphocerror) {
  astUtils.newImport(

How to use babel-types.yieldExpression:

73
74
75
76
77
78
79
80
81
82




Compiler.prototype.wrapCallExpression = function(node) {
  return t.yieldExpression(node, true);
}

Compiler.prototype.ast_variableDeclaration = function() {
    return t.variableDeclaration('var', [

How to use babel-types.importNamespaceSpecifier:

41
42
43
44
45
46
47
48
49
50
let specifier;

if (isDefault) {
  specifier = types.importDefaultSpecifier(localIdentifier);
} else if (isNamespace) {
  specifier = types.importNamespaceSpecifier(localIdentifier);
} else {
  specifier = types.importSpecifier(
    localIdentifier,
    typeof identifier === 'string' ? localIdentifier : types.identifier(identifier[1])

How to use babel-types.isWhileStatement:

56
57
58
59
60
61
62
63
64
65
if (
  isTimePoint(block[i]) ||
  (t.isIfStatement(block[i]) && block[i].name == 'emptyContinuation') ||
  t.isDoWhileStatement(block[i]) ||
  t.isTryStatement(block[i]) ||
  t.isWhileStatement(block[i]) ||
  t.isForStatement(block[i])
) {
  splitPoints.push(i);
} else if (hasCallExpression(path.get('body')[i])) {

How to use babel-types.isForStatement:

57
58
59
60
61
62
63
64
65
66
  isTimePoint(block[i]) ||
  (t.isIfStatement(block[i]) && block[i].name == 'emptyContinuation') ||
  t.isDoWhileStatement(block[i]) ||
  t.isTryStatement(block[i]) ||
  t.isWhileStatement(block[i]) ||
  t.isForStatement(block[i])
) {
  splitPoints.push(i);
} else if (hasCallExpression(path.get('body')[i])) {
  splitPoints.push(i);

How to use babel-types.isDoWhileStatement:

54
55
56
57
58
59
60
61
62
63
let splitPoints = [];
for (let i = 0; i < block.length; ++i) {
  if (
    isTimePoint(block[i]) ||
    (t.isIfStatement(block[i]) && block[i].name == 'emptyContinuation') ||
    t.isDoWhileStatement(block[i]) ||
    t.isTryStatement(block[i]) ||
    t.isWhileStatement(block[i]) ||
    t.isForStatement(block[i])
  ) {

How to use babel-types.JSXElement:

6
7
8
9
10
11
12
13
14
15
const useYarn = require('../utils/index').useYarn();
const useCnpm = require('../utils/index').useCnpm();

module.exports = {
    createElement(nodeName, attrs, children) {
        return t.JSXElement(
            t.JSXOpeningElement(t.JSXIdentifier(nodeName), attrs, false),
            t.jSXClosingElement(t.JSXIdentifier(nodeName)),
            children
        );

How to use babel-types.isJSXOpeningElement:

123
124
125
126
127
128
129
130
131
132
babelTraverse(rast, {
    ClassMethod (path) {
        if (path.node.key.name === 'render') {
            path.traverse({
                JSXIdentifier (path) {
                    if (t.isJSXClosingElement(path.parent) || t.isJSXOpeningElement(path.parent)) {
                        const node = path.node;
                        const componentName = state.components[node.name] || state.components[parseComponentName(node.name)];
                        if (componentName) {
                            path.replaceWith(t.jSXIdentifier(componentName));

babel-types functions:

Sorted by popularity