admin管理员组

文章数量:1336181

I'm using AST/ts-morph to manipulate a React component

const App = () => {
    return (
        <Router>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                <Route path="/contact" element={<Contact />}>
                    <Route path="/foo" element={<Foo />} />
                    <Route path="/bar" element={<Bar />} />
                </Route>
           </Routes>
        </Router >
    )
}

Its React, but it actually doesn't matter here. What I want to do now is insert some code into the /contact route at the end

At the end I will list my whole program, but here I will focus only on the part that fails. So, I managed to find the contact route. But the part where I insert some code into that route has so far failed. Here is what I have

const contactRouteElement = findContactRoute(); // -> JsxElement 
const expression = project.createExpression("isFoo && <Foo />");

const jsxExpression = JsxExpression.create(expression);

contactRouteElement.addJsxChild(jsxExpression);

const newSourceFile = project.createSourceFile("NewApp.tsx", sourceFile.getFullText(), { overwrite: true });


newSourceFile.saveSync();

It fails on this line

project.createExpression("isFoo && <Foo />");

with the error

project.createExpression is not a function

So the question is, how do you create an expression in ts-morph? BTW, is there an easier way to do this? I find ts-morph very hard to use!

本文标签: abstract syntax treeCreate an expression with tsmorph failsStack Overflow