Matt
Matt

Reputation: 1609

How to add react-router to preact app from preact-cli

I created a Preact app using the preact-cli, and need to add react-router-dom to my project for routing. How can I add react-router to the project without ejecting the app, in order to install the router library?

I've seen options for adding webpack, but that' requires ejecting the app.

I added "preact-compat": "^3.19.0", to my package.json in the project, but not sure how to either add webpack or import the necessary react-router imports:

import {BrowserRouter as Router, Route, Switch, NavLink} from 'react-router-dom';

Upvotes: 0

Views: 524

Answers (2)

Matt
Matt

Reputation: 1609

Was able to get this working with import of import {BrowserRouter as Router, Route, Switch, NavLink} from 'react-router-dom'; and yarn build then yarn-serve

Upvotes: 0

rschristian
rschristian

Reputation: 2966

but that' requires ejecting the app

There is no way to "eject" from preact-cli. That isn't functionality that exists, so I'm a bit confused on what it is that you're referring to.

We make the entire config available to you through your preact.config.js. With this, you can configure absolutely any part of the Webpack config that you'd like, and only those bits. You don't need to do anything like CRA's eject, where you have to now own the entire config yourself. You can edit the pieces you want, and leave everything else out of site & out of mind.

I've seen options for adding webpack

preact-cli uses Webpack for bundling, it's the fundamental underlying tool. There's no way to use it without Webpack, so this doesn't make much sense.

I added "preact-compat": "^3.19.0"

Remove this. preact-cli already adds compat, and does it from the correct source.

If you read the docs for preact-compat, you'll see it's only for Preact 8.x and prior, which is a few years out-of-date at this point. The correct compat package for v10+ is preact/compat. We set this up for you already in preact-cli though, so nothing you need to do yourself.


Why do you think you need to do any configuration just to import the library? Did you run into any errors, or maybe docs that are confusing/misworded? Just ran a test with v6, should work out-of-the-box after you swap it in for preact-router (assuming you've set up a preact-cli project using one of our templates)

Upvotes: 0

Related Questions