swc-to-babel
v3.0.1
Published
convert swc ast to babel
Downloads
514
Maintainers
Readme
SWC-to-babel
Convert SWC
JavaScript AST
to Babel AST
.
To use SWC
parser with babel
tools like:
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.
Install
npm i swc-to-babel
Example
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';
},
});
API reference
/**
* 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>;
License
MIT