jscodeshift / recast:objectExpression总是很漂亮。我怎么能防止这种情况?

时间:2017-03-12 21:19:29

标签: jscodeshift

我正在使用jscodeshift转换函数调用:

foo() - > foo({uid:... label:...})

(1)

问题是objectExpression总是很漂亮:

const newArgObj = j.objectExpression([
    j.property(
        'init',
        j.identifier('uid'),
        j.literal(getUID()),
    ),
    j.property(
        'init',
        j.identifier('label'),
        j.literal('bar'),
    )
]);
node.arguments = [newArgObj];

...

return callExpressions.toSource({quote: 'single'});

如何防止这种情况并获得如下内容:

foo({
    uid: 'LBL_btBeZETZ',
    label: 'bar'
})

1 个答案:

答案 0 :(得分:0)

好吧,这是不可能的,请看一下recast's printer.js source

case "ObjectExpression":
case "ObjectPattern":
case "ObjectTypeAnnotation":
    ...
    var len = 0;
    fields.forEach(function(field) {
        len += n[field].length;
    });

    var oneLine = (isTypeAnnotation && len === 1) || len === 0;
    var parts = [oneLine ? "{" : "{\n"];
    ...
            if (!oneLine) {
                lines = lines.indent(options.tabWidth);
            }
    ...
    parts.push(oneLine ? "}" : "\n}");

替代方法(至少在我的简单案例中) - 您可以使用原始字符串:

const rawCode = `{uid: '${getUID()}', label: 'bar' }`;
node.arguments = [rawCode];

node.arguments = [j.jsxText(rawCode)];

两者都会给你:

foo({uid: 'LBL_btBeZETZ', label: "bar" })