A quick start guide to creating an app with Preact, TypeScript and Ruby on Rails
After following this guide, you will have created a “Hello world” application that uses Preact, TypeScript and Ruby on Rails. We’ll also be installing ESLint!
Installing prerequisites - ruby and sqlite3
Make sure you have installed rbenv and Ruby:
You’ll most likely have sqlite3
already installed (check using sqlite3 --version
) but if you don’t you can download it from the SQLite download page.
Installing Ruby on Rails
Then install Ruby on Rails:
Once installed, open a new terminal window and double-check that it was successfully installed:
Create your Ruby on Rails app with React
Since there isn’t Preact boilerplate code available, I found it much easier to get started with React and then switch it out for Preact afterwards.
Add TypeScript and ESLint
Make sure to update all of your JavaScript files to end with .ts
and .tsx
!
If your code is rendering a Preact component you’ll want it to end in
.tsx
. If it’s just a util file with some functions in it, then you only need.ts
(but you can still just use.tsx
and it will work fine).
Add the following line in tsconfig.json
:
Then add a lint script to your package.json
:
Also make sure to create a .eslintrc.js
file in your root folder and add the following:
Install Preact
And add the the following to the plugin section of your babel.config.js
file:
Now that you’ve got Preact, you can also delete react
and react-dom
from your dependencies in your package.json
file.
Create your first controller
Create your first controller. I’ve named mine hello
:
This will create a file for you called app/controllers/hello_controller.rb
. Add the following code to it:
Then add this new controller you’ve created to config/routes.rb
:
Switch out any React references for Preact
When we first created this app, a app/javascript/packs/hello_react.tsx
file will have been created for us. Rename this to hello_preact.tsx
, and switch out its contents for a Preact component:
And finally, we need to add our new Preact component to app/views/hello/home.html.erb
Starting things up
Finally, we can run these two commands to start up our Preact + Rails app:
And voila! 🎉 You should now have a “Hello world” app that uses Preact and Ruby on Rails.
I struggled to find good documentation online to help me get started with this stack, so I hope this guide has helped you if you were facing the same difficulties.
Happy coding!
References
Rails: Install Rails 5.2.3 with rbenv