Follow the below steps to use a TypeScript with Vue.
Step 1: Install Vue.js.
Type the following.
vue init webpack vue-typescript-template
After installing, go into that folder. Next, we need to create the tsconfig.json file.
Step 2: Create the tsconfig.json file.
{
"compilerOptions": {
"lib": ["dom", "es5", "es2015"],
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"allowSyntheticDefaultImports": true
}
}
To run typescript in our file, we must create a tsconfig.json file. It will set up the configurations for us. If you have worked on Angular before, you are familiar with that file.
Step 3: Install the TypeScript dependencies.
Go to your root and hit the following command.
npm install typescript ts-loader --save-dev
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules|vue\/src/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
...
In there, rename the entry to .ts and add it to the extensions.
...
entry: {
app: './src/main.ts'
},
...
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
...
Now, Add es-module: true
to build/vue-loader.conf.js
.
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
esModule: true,
...
Step 4: Start the server.
Type the command to start the server.
npm run dev
If you have done all the configurations correctly, you can run the project.
Step 5: Write class-based components.
First, we need to install the following packages to declare class-based components.
npm install vue-class-component vue-property-decorator --save-dev
We need to add two properties inside the tsconfig.json file.
"experimentalDecorators": true,
"allowJs": true,
It will help us to remove the errors.
Our project already has one component called HelloWorld.vue component. I am now writing this whole component in class-based syntax.
<template>
<div>
<p>Class based component</p>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
@Component({
components: { HelloWorld }
})
export default class HelloWorld extends Vue {
}
</script>
You can see here I have used a Component decorator inside the vue component. Also, this syntax is almost familiar with Angular Component.
So now go to http://localhost:8080. You can see that it is working precisely fine.
So you can use TypeScript decorator and class in the Vue.js application. So this is how you can integrate TypeScript with Vue js.
That’s it.
You should mention the first step to install vue-cli. There are some users who are starting new.