1.babel/core
const babel = require('@babel/core');
const code = "class glass {get name() { return '水杯' }}";
const options = {
presets: ['@babel/preset-env'],
}
// const result1 = babel.transform(code, options);
// babel.transformAsync(code, options).then(res => console.log(res));
// console.log(result);
// const content = babel.transformFileSync('./babel-file.js');
// console.log(content);
// const parsedAst = babel.parse(code, { parserOpts: { allowReturnOutsideFunction: true } });
// console.log(parsedAst);
// const result3 = babel.transformFromAst(parsedAst, code, options);
// console.log(result3);
const config = babel.loadPartialConfig(options); // 提前生成config
const result = babel.transform(code, config.options);
console.log(result);
babel/core的作用 = babel/parser(词法分析+语法分析 = AST) + babel/traverse (AST 经过plugin转化) + babel/generator (AST 生成code字符串)
2.babel/parser 实际就是babel内置的parser
babelParser.parse(code, options) 等价于babel.parse(code, options); 会return一个AST树
const babel = require('@babel/core');
const code = "class glass {get name() { return '水杯' }}";
const options = {
presets: ['@babel/preset-env'],
}
const parsedAst = babel.parse(code);
console.log(parsedAst);
import { parse } from '@babel/parser';
const ast = parse(code);
console.log(ast);
可以看到两个的输出ast是一样的值
3.babel/generator是读取ast,并将它转化成代码以及source map.
import { parse } from '@babel/parser';
import generate from '@babel/generator';
const ast = parse(code);
const output = generate(ast, {minified: true}, code);
console.log(output);
注意generater的作用仅仅是进行转化成代码,不会进行处理,与babel/core一节的transformFromAst不同,transformFromAst是会经过plugin的处理的,实质上是babel/traverse + generater的结合.
总结,实际上,通过babel/core的实现也可以看到,babel/core的依赖就是babel/parser + babel/traverse + babel/generator。当然,还有接下来要介绍的一些工具包
// babel/core的依赖
"@babel/code-frame": "^7.8.3",
"@babel/generator": "^7.9.0",
"@babel/helper-module-transforms": "^7.9.0",
"@babel/helpers": "^7.9.0",
"@babel/parser": "^7.9.0",
"@babel/template": "^7.8.6",
"@babel/traverse": "^7.9.0",
"@babel/types": "^7.9.0",
"convert-source-map": "^1.7.0",
"debug": "^4.1.0",
"gensync": "^1.0.0-beta.1",
"json5": "^2.1.2",
"lodash": "^4.17.13",
4.babel/code-frame生成错误源码以及错误的位置信息
可以看到babel/core babel/parser babel/traverse babel/generater等包都使用了这个包,console出错误信息,提示用户
例如:
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);