jscodeshift/recast:objectExpression 总是打印得很好。我怎样才能防止这种情况发生?
jscodeshift/recast: objectExpression is always pretty-printed. How can I prevent that?
我正在使用 jscodeshift 转换函数调用:
foo() --> foo({uid: ... label: ...})
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'});
问题是 objectExpression 总是打印得很漂亮:
foo({
uid: 'LBL_btBeZETZ',
label: 'bar'
})
如何防止这种情况并得到类似的东西:
foo({uid: 'LBL_btBeZETZ', label: 'bar'})
ok,不可能,看看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" })
我正在使用 jscodeshift 转换函数调用:
foo() --> foo({uid: ... label: ...})
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'});
问题是 objectExpression 总是打印得很漂亮:
foo({
uid: 'LBL_btBeZETZ',
label: 'bar'
})
如何防止这种情况并得到类似的东西:
foo({uid: 'LBL_btBeZETZ', label: 'bar'})
ok,不可能,看看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" })