简体   繁体   English

Babel 如何在代码中添加新行或换行符?

[英]Babel how to add new line or line break to code?

I haven't found a way to add an empty line to my code with Babel.我还没有找到用 Babel 在我的代码中添加空行的方法。 I have javascript code that is parsed with the Babel library.我有用 Babel 库解析的 javascript 代码。 I have for example the following code:例如,我有以下代码:

var e = t && t.__esModule ? function () {
  return t.default;
} : function () {
  return t;
};

and I need to convert this into:我需要将其转换为:

var e = t && t.__esModule ? function () {
  return t.default;
} : 
function () {
  return t;
};

I have tried to insert code before the function with我试图在函数之前插入代码

path.insertAfter(t.expressionStatement(t.stringLiteral('\n')))

but the Babel generator turns the code into:但是 Babel 生成器将代码变成:

var e = t && t.__esModule ? function () {
  return t.default;
} : ("\n", function () {
  return t;
});

I need to add line breaks at multiple places in the code for example also after a function opens with '{' or after '},'.我需要在代码中的多个位置添加换行符,例如在函数以“{”或“},”打开之后。 How can I do this with Babel?我怎样才能用 Babel 做到这一点? Is there a different approach possible?有没有可能的不同方法? Is there a Babel alternative?有没有 Babel 替代品?

I wanted to do something which is impossible with an AST as @loganfsmyth pointed out.正如@loganfsmyth 指出的那样,我想做一些 AST 不可能的事情。 An AST removes intentionally information such as line breaks and whitespaces. AST 有意删除了换行符和空格等信息。 What I was looking for was a Concrete Syntax Tree (CST) or a Linter.我正在寻找的是具体语法树(CST)或 Linter。 ESLint allowed me to add line breaks where required. ESLint 允许我在需要的地方添加换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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