0

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!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.