Using Typescript with Vue.JS Single File Components

Chuck Dries
2 min readMay 16, 2017

Update from the future: Vue 2.5 introduced large changes to Typescript support. There’s some really great stuff, but this article is no longer correct.

For now, three tips:

  1. There’s a recommended configuration on the typescript support article in the vue documentation. Use it, but I had to add noImplicitThis: false . I’ll get into why in the article.
  2. The doc mentions using Vue.extend on component objects. Since single file components export component objects, do what it says.
...
<script>
import Vue from 'vue';
export default Vue.extend({
...your component object
});
</script>
...

3. You still need sfc.d.ts which is still not mentioned anywhere in the Vue documentation.

Below is the unedited original article.

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.

Huzzah!

--

--

Chuck Dries

Decent programmer, mediocre poet. Currently at Adobe