Convert SWC
JavaScript AST
to Babel AST
.
To use SWC
parser with babel
tools like:
@babel/traverse
@babel/types
- etc...
The thing is @babel/parser
has a a little differences with swc
standard:
File
node exists;Program
instead ofModule
;loc
withline
andcolumn
instead ofspan
;StringLiteral
has nokind
anhasEscape
;Identifier
has nooptional
and usesname
instead ofvalue
;BlockStatement
hasbody
instead ofstmts
;VariableDeclarator
has nooptional
anddefinite
;CallExpression
has notypeArguments
,spread
andexpression
properties inarguments
;TemplateElement
hasvalue
field withraw
andcooked
;- TypeScript ast nodes has prefix
TS
instead ofTs
; ExportNamedDeclaration
instead ofExportDeclaration
;ExportDefaultDeclaration
instead ofExportDefaultExpression
;VariableDeclaration
has nodeclare
field;- Has no
ParenthesisExpression
; ClassDeclaration
andClassExpression
usesid
instead ofidentifier
, hasClassBody
;ClassMethod
usesstatic
instead ofisStatic
;MemberExpression
hascomputed
property instead ofComputed
node inproperty
field;NewExpression
has no untyped node with aspread
property inarguments
, always hasarguments
field, instead ofnull
when absent;ArrayExpression
has no untyped node with aspread
property inelements
;Function
has notypeParameters
;TSTypeReference
has notypeParams
field;TSTypeOperator
hasoperator
instead ofop
;TSTypeParameter
has a fieldname
which isstring
instead ofIdentifier
;FunctionDeclaration
instead ofFunctionExpression
withidentifier
field;ImportDeclaration
hasimportKind
instead oftypeOnly
andattributes
fields;ObjectProperty
instead ofKeyValueProperty
,KeyValuePatternProperty
andAssignmentPatternProperty
;ExportNamedDeclaration
hasexportKind
,specifiers
fields;ExportSpecifier
haslocal
which is nevernull
instead oforig
;ExportDefaultDeclaration
hasdeclaration
instead ofdecl
;TSAnyKeyword
instead ofTSKeywordType
;TSAsExpression
instead ofTsConstAssertion
;ObjectMethod
withkind: get
instead ofGetterProperty
ObjectMethod
withkind: set
instead ofSetterProperty
- etc...
swc-to-babel
aims to smooth this differences.
npm i swc-to-babel
const swc = require('@swc/core');
const toBabel = require('swc-to-babel');
const traverse = require('@babel/traverse').default;
const ast = toBabel(swc.parseSync(`
const f = ({a}) => a;
`));
traverse({
ObjectProperty(path) {
console.log(path.value.name);
// output
'a';
},
});
/**
* Convert an SWC ast to a babel ast
* @param ast {Module} SWC ast
* @param {string} [src=""] Source code
* @returns {ParseResult<File>} Babel ast
*/
export default function toBabel(ast: Module, src?: string): ParseResult<File>;
MIT