benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.99k stars 349 forks source link

recast parse typescript Error #1258

Open yumo-mt opened 1 year ago

yumo-mt commented 1 year ago
//  code.tsx
import React, { useState, useEffect } from 'react'

const Home = () => {
  const [modal2Value, setModal2Value] = useState('abc')
  const selectedData: [
    { label: string; value: string | number },
    { label: string; value: string | number },
  ] = [
    { label: 'xx', value: 123 },
    { label: 'zz', value: '234' },
  ]
  useEffect(() => {
    setModal2Value(selectedData[0].value as string) // this code throw error
  }, [])
  return <h1>{modal2Value}</h1>
}

export default Home
// index.ts
const recast = require('recast');
const fs = require('fs');
const mCode = fs.readFileSync('./code.tsx',{encoding:'utf-8'});

const tsAst = recast.parse(mCode, {
  parser: require("recast/parsers/typescript")
});
console.log(tsAst)

which should i use parse ? thanks

phitattoo commented 1 year ago
```tsx
//  code.tsx
import React, { useState, useEffect } from 'react'

const Home = () => {
  const [modal2Value, setModal2Value] = useState('abc')
  const selectedData: [
    { label: string; value: string | number },
    { label: string; value: string | number },
  ] = [
    { label: 'xx', value: 123 },
    { label: 'zz', value: '234' },
  ]
  useEffect(() => {
    setModal2Value(selectedData[0].value as string) // this code throw error
  }, [])
  return <h1>{modal2Value}</h1>
}

export default Home
// index.ts
const recast = require('recast');
const fs = require('fs');
const mCode = fs.readFileSync('./code.tsx',{encoding:'utf-8'});

const tsAst = recast.parse(mCode, {
  parser: require("recast/parsers/typescript")
});
console.log(tsAst)

ฉันควรใช้การแยกวิเคราะห์แบบใด ? ขอบคุณ

jonz94 commented 1 year ago

Hi, you can try the babel-ts parser.

Example:

const recast = require('recast');
const fs = require('fs');
const mCode = fs.readFileSync('./code.tsx', { encoding: 'utf-8' });

const tsAst = recast.parse(mCode, {
  parser: require('recast/parsers/babel-ts'),
});

console.log(tsAst);

PS. you will also need to install @babel/parser package first.