简体   繁体   中英

Babel plugins - Member access with index

I am writing a babel plugin. I came across a place where I need to use index operator. This is code I want to get a[Symbol.something](b) , however, I can't seem to find a way to do it. I have tried doing something like this:

types.callExpression(
    types.memberExpression(types.Identifier('a'), 
        types.memberExpression(types.Identifier('Symbol'), types.Identifier('something'))
    ),
    [types.Identifier('b')]
)

However, it throws error TypeError: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead g ot "MemberExpression" . I googled my problem, but I can't seem to find a way to do it.

You should use computed parameter of MemberExpression .

For example,

types.MemberExpression( types.Identifier('foo'), types.Identifier('bar') );

will generate foo.bar , whereas

types.MemberExpression( types.Identifier('foo'), types.Identifier('bar'), true );

will generate foo[bar] .

Thus, your code should be:

types.CallExpression(
  types.MemberExpression(
    types.Identifier('a'),
    types.MemberExpression(types.Identifier('Symbol'), types.Identifier('something')),
    true
  ),
  [types.Identifier('b')]
);

This will generate a[Symbol.something](b) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM