Adding TypeScript to your Svelte components in Rails 6
By Martijn Storck
Webpacker, TypeScript and Svelte are all easily added to your Ruby on Rails 6 application. But getting everything working together can be a bit tricky. This post shows how to add TypeScript to an existing Ruby on Rails application that uses Svelte.
Step 1: Install TypeScript
TypeScript can be installed using a webpacker task as follows:
rails webpacker:install:typescript
Step 2: Install svelte-check and svelte-preprocess
yarn add @tsconfig/svelte svelte-preprocess svelte-check
Adjust for npm if necessary
Step 3: Configure svelte preprocessor
In config/webpack/loaders/svelte.js
, add the preprocessor directive to your options as follows:
module.exports = {
test: /\.svelte$/,
use: [{
loader: 'svelte-loader',
options: {
hotReload: true,
preprocess: require('svelte-preprocess')({})
}
}],
}
Step 4: Convert your Svelte components to typescript
Since all valid JavaScript is valid TypeScript this step is surprisingly easy. In your .svelte
files, sSimply replace your
<script>
tags with
<script lang="ts">
You can now gradually add type definitions to your components as necessary.
Step 5: Check for warnings
To validate the TypeScript code, svelte provides us a handy command. Execute
npx svelte-check
This will not only show errors and warnings but also useful hints:
Loading svelte-check in workspace: /workspace
Getting Svelte diagnostics...
====================================
/workspace/app/javascript/components/Modal.svelte:7:7
Hint: Variable 'modal' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
let modal;
/workspace/app/javascript/components/Modal.svelte:14:11
Hint: 'keyCode' is deprecated (ts)
const handle_keydown = (e : KeyboardEvent) => {
if (e.keyCode === 13) {
dispatch("enter")
====================================
svelte-check found no errors and no warnings
Using the excellent Svelte language server gives you these warning right in your editor, for example using the official Svelte extension for Visual Studio Code:
While you’re at it, don’t forget to enable Format on Save to prevent yourself from ending up with blatant style violations as the one in this example. Can you spot it?
Conclusion
The tooling TypeScript provides for your editor is worth it alone. Once you get it set up it speeds up your development and helps you discover issues quickly. I recommend everyone to give TypeScript a shot, whether you’re doing vanilla JavaScript, Svelte or React.