SoFunction
Updated on 2025-04-11

Basic method of vue access ts

The following will be completed in the form of project construction:

The project infrastructure is built through CLI, mainly vue (2.5.16) + webpack (3.6.0) + element-ui (2.8.2). The overall project also uses vuex, eslint, etc.

1. Dependence record

The project has been changed from basic js to ts. Because it was the first attempt, based on the principle of minimum dependency and minimum change, only some basic dependencies were introduced:

  • typescript: #3.1.6 -- The basic dependency of access to ts, the version needs to be modified according to the relevant version of the project
  • ts-loader: #3.5.0 -- Also basic dependency
  • ts-lint tslint-config-standard tslint-loader -- These three are replaced by the original eslint verification. I have not studied it carefully. It should be possible to deal with some inexplicable verification problems caused by eslint after the introduction of ts.

2. Configuration Note

Revise:

Change the original .js to .ts

entry: {
    app: ['babel-polyfill', './src/']
 },

Add ts:

extensions: ['.tsx', '.ts', '.js', '.vue', '.json'],

Rules adds the parsing to ts:

{
    test: /\.(ts|tsx)?$/,
    loader: 'ts-loader',
    exclude: /node_modules/,
    options: {
      appendTsxSuffixTo: [/\.vue$/],  // ts does not know how to handle .vue ending files, this configuration is required      happyPackMode: true  // Turn on multithreading to speed up compilation    }
 }

Replace eslint with tslint:

{
    test: /\.ts$/,
    loader: 'tslint-loader',
    exclude: /node_modules/,
    enforce: 'pre'
}

At the same timeAdd configuration in the root directoryConfiguration file:

// 
const mergeVue = require('webpack-merge')

loaders: mergeVue(({
    sourceMap: sourceMapEnabled,
    extract: isProduction
}), {
    ts: ['ts-loader', 'tslint-loader']   // Added}),

// 
{
    "extends": "tslint-config-standard",
    "globals": {
      "require": true
    },
    "rules": {
      "no-consecutive-blank-lines": false
    }
}

There are also some other basic modifications, such as ts will verify the duplicate names between different files and give error prompts. Of course, this can be handled through configuration, but I personally think that this prompt can be retained, and you only need to modify the corresponding variable name.
Added configuration file(Individual configuration fields will be filled in the following instructions)

{
  "compilerOptions": {
    "target": "es5",
    "strict": true,
    "module": "es2015",
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "types": [
      "node"
    ],
    "noImplicitAny": false,
    "allowSyntheticDefaultImports": true
  }
}

Add files to the src directory:

This file mainly tells ts, and files ending with .vue are handed over to vue for processing. However, this will cause a parent-child component reference problem, and the same is done later.

declare module '*.vue' {
    import Vue from 'vue'
    export default Vue
}

3. Modification Note

1. Replace the necessary .js with .ts

Here I talk about the necessary js-end files. What I process mainly logic-related files. Some config-type files have not been modified, and the js-end is still retained. The purpose is to minimize the change principle and avoid some difficult problems.

File modification

For vue files:

  • Need to add lang='ts' to the script tag
  • Definition components are also required
  • If other components are referenced, the .vue suffix can be omitted when ts is not introduced. However, after ts is introduced, the .vue suffix must be added when introducing the components.
<script lang="ts">
import Vue from 'vue'
import Table from '@/components/table/'

export default ({
    data(){
        return {
            name: ''
        }
    }
})

After the above three basic modifications, if your project is very simple, so simple that it is a test shelf, you can happily start npm without much problem. However, if it is an original project, many warning problems will be revealed when you start. Of course, if it is a basic TS verification problem, we can directly modify the file or configuration.

Ignoring the verification of ts format, we can see that after adding ts syntax to the original project (or not adding ts syntax), there will be other problems. The problems may not affect the compilation and operation of the program, but they will be red in the editor~ Next, let’s briefly talk about the pitfalls filled in.

4. Fill in the pit

Cannot find name ‘require‘. Do you need to install type definitions for node? When we use require to introduce certain files, this error message may appear. This problem is basically that we need to install the corresponding @type dependency. For this problem:

Install:npm i --save-dev @types/node,existAdd "types": ["node"] to it. If there is still an error message, you can add declare var require: any.

Similar issues include the introduction of lodash, qs, etc., and the corresponding @type/xx is required to be installed. If you use vue-cookie, you need to install the corresponding ts version vue-cookies-ts and the corresponding methods need to be modified. See the document vue-cookies-ts for details.

Cannot find module ‘XXX‘ or its corresponding type This error occurs when we configure it according to the basic content and import a certain ts file. This problem is actually quite strange. If you add the .ts suffix, it will prompt that there is no need to add it. After removing the suffix, the module cannot be found.

One solution to this problem is to see if there is alias configured, and at the same time, "paths": {"@/*": ["src/*"]} needs to be added. If the configuration does not take effect, the basic method two can solve it. The second method two is to put the project first, which is to use vscode to open a project directly, rather than opening a folder where there are many projects. This problem should be caused by the vetur plugin. Of course, there is a third method to add a separate vetur configuration. This has not been studied. Friends who have time can consider it.

Property ‘$http‘ does not exist on type ‘xxx‘ Usually, when vue develops, we use axios to encapsulate a unified method and introduce bindings:

import httpRequest from '@/utils/httpRequest'
.$http = httpRequest

// Use of methodsthis.$http()

In usethis(Vue)An error message will appear when using it. Consider the reason because we have configured it above. Files ending at .vue are treated as vue, and vue does not have the $http method. The easiest way is to directly apply any (this as any).$http , but for molding projects, there are too many changes to write this. The following method can be used (the problem of using $store is also handled):

Create a new one under srcAdd the following configuration:

import { Store } from 'vuex';
declare module 'vue/types/vue' {
    interface Vue {
        '$stroe': Store,
        '$http': any
    }
}

Property 'resetFields' does not exist on type 'Vue'

If element form-related methods are used, method calls such as form clearing and resetting may be involved. Usually, you can give form a ref and then call it through this.$refs['xxx'].resetFields(). However, after joining ts, an error will be prompted. The reason is that this here is pointed to vue and there is no relevant method.

The workaround uses type assertions to assert ref as element-related content:

import { Form as EleForm } from 'element-ui'
// Inside the methodconst ref = this.$refs['searchForm'] as EleForm
()

There is another situation, that is, the method of using child components between parent and child components inside the parent component, and using ref to call, the above error message will also appear. This problem was first considered to use similar assertions to assert ref as a child component, but the method was not working, and no suitable method was found through online searches. Most methods were directly asserted as any, that is (this.$refs['xxx'] as any).clearList() . Assertions like this, the problem can be solved, but I hope to find a more suitable method.

This is the end of this article about the basic method of vue access ts. For more related vue access ts content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!