简体   繁体   English

如何从babel-core中取出转译的字符串?

[英]How do I get the transpiled string out of babel-core?

I'm trying to use babel with npm and I think the package I need is babel-core. 我正在尝试将babel与npm一起使用,我认为我需要的软件包是babel-core。 Specifically what I want to do is pass it a string of ES6 code and get it to hand me back a string of transpiled code. 具体来说,我想给它传递一串ES6代码,然后将其交给我一串已转译的代码。 That's it. 而已。 You'd think that would be simple but I can not figure this out with the documentation. 您可能认为这很简单,但是我无法通过文档来解决。 From what I've read, I should be able to do this: 从我的阅读中,我应该能够做到这一点:

var babel = require('babel-core');
var code = 'x => x + 1';
var result = babel.transform(code);

But the problem is, result is an object containing an AST, not a string. 但是问题是,结果是一个包含AST而不是字符串的对象。 I tried to run transformFromAst on that object but that doesn't work either. 我试图在该对象上运行transformFromAst,但这也不起作用。 Can anyone help me get the actual transpiled string? 谁能帮助我获得实际的转译字符串?

result.code will have the ES5 code in it. result.code中将包含ES5代码。 result.ast will have the ast. result.ast将具有ast。 It probably didn't look like it because you aren't passing any options to Babel, so it will just pass through the code unchanged, eg 它可能看起来不像是因为您没有将任何选项传递给Babel,所以它将只通过不变的代码传递,例如

npm install babel-preset-es2015

and

var result = babel.transform(code, {
    presets: ['es2015']
});

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

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