learn-nuxt-ts

Switch to TypeScript

[13-Apr-2020] Please use the official Nuxt TypeScript package: https://typescript.nuxtjs.org/guide/setup.html

Before adding anything, let switch to TypeScript first. I was guided by the two following links:

Adding Nuxt-ts

yarn add nuxt-ts
yarn add --dev nuxt-property-decorator
yarn remove nuxt

Optionally, you can add TypeScript as a development dependency:

yarn add --dev typescript

For VS Code users, you can force the usage of TypeScript from node_modules/ instead of using default VS Code TypeScript thanks to .vscode/settings.json:

{
  // Windows version
  "typescript.tsdk": "node_modules\\typescript\\lib",
  // Linux
  "typescript.tsdk": "node_modules/typescript/lib"
}

Update configuration

Few configurations have to be added or changed:

Update package.json by using nuxt-ts instead of nuxt:

{
  "scripts": {
    "dev": "nuxt-ts",
    "build": "nuxt-ts build",
    "start": "nuxt-ts start",
    "generate": "nuxt-ts generate"
  }
}

Add a tsconfig.json:

{
  "extends": "@nuxt/typescript",
  "compilerOptions": {
    "baseUrl": ".",
    "types": ["@types/node", "@nuxt/vue-app"],
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "paths": {
      "@/*": ["*"],
      "~/*": ["*"]
    }
  }
}

Renaming nuxt.config.js into nuxt.config.ts. I simply change the first line:

- var pkg = require('./package')
+ import pkg from "./package.json";

and commented out the build: { ... } content to avoid having a “declared but never used” and “implicitly has an ‘any’ type” error

Update existing code

The application scaffold is not much, only pages/index.vue has to be updated:

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator';

import Logo from '@/components/Logo.vue';

@Component({
  components: {
    Logo
  }
})
export default class Index extends Vue {}
</script>

Don’t forget lang="ts"!