我正在使用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'
})
答案 0 :(得分:0)
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" })