Using Typescript with Vue.JS Single File Components

Update from the future: Typescript + Vue is changing. Check out the official Vue guide, it has everything you need know, the article below is out of date.

Typescript is officially supported, but you need to add a few things to your webpack config. To use single.vue file components, you need to do a bit more. This took me forever to figure out for some reason. When I was looking around for instructions, I found a few outdated blog posts full of code that didn’t work, a bunch of vue-cli templates that didn’t work with single file components, and an official Github repo and companion library that contained all the code I needed but I had to wade through the issues to figure it out. So here it is, how to use webpack, typescript, and vue single file components together in harmony.

  1. I started with the webpack-simple template from vue-cli. Check the template repo for installation instructions.
  2. Install ts-loader for typescript support and link typescript if you have it installed globally. Instructions are also on the repo. Don’t forget to npm link typescript!
  3. Modify your webpack.config.js. I’ve marked the necessary changes with a capital TK. Note that I chose to use SCSS, so vue-cli inserted the scss rules you see on lines 33 through 39:

4. This is the key. The secret sauce to making it all work. Add a small file to src/ so that typescript knows your .vue files are modules and allows you to import them.

5. tsconfig.json. I know for a fact that it has to exist for this to work, but I don’t entirely know what parts of it are necessary. I know that this one works and I didn’t take the time to figure out why.

6. Any script tag you want to be interpreted as typescript needs to be <script lang="ts">.

In the end, all the code I needed was within the depths of The vue class component decorator library, but the official typescript support page doesn’t mention usage of single file components and I couldn’t find an up to date write up on the internet, so here we go.


Show your support

Clapping shows how much you appreciated Chuck Dries’s story.