The way to upgrade js to ts (including vue upgrade strategy)

Author : xuzhiping   2022-11-16 15:40:00 Browse: 1377
Category : JavaScript

Abstract: Basic grammar For the basic grammar of TS, there is no more introduction here, just look at the official website, after all, a ...

Basic grammar

For the basic grammar of TS, there is no more introduction here, just look at the official website, after all, a very hard document can kill a series of books:

links:

Write the ts file

TypeScript file with At the end of ts, the content is basically written in JavaScript format. It should be noted that some areas require explicit type declarations, such as:

Function (id: number) {
  // do something...
}

In addition, ts also extends many functions of js, for example, you can customize a type:

Type T = "a" | "b"

Let a: t = "a"; // a can only be equal to "a" or "b"

This allows you to control the input of specified characters. You don't have to worry about the bug caused by incorrect input, which are equal to a string in js. For more details, please refer to the document.

Transfer js file to ts file

1. Modify the file directly

This method is suitable for small files. It can be done in a short time, such as a small tool function. Just add some type declarations, return value declarations, or namespaces.

This is the simplest and hard core method, but it has a disadvantage. For large files that have been written, such as modifying the jquery source code, it is very difficult, so the following methods are available.

2. Declare the js file

This method does not require modification of the js source code, just create a .d.ts file with the same name in the same level folder or under the type folder path configured in your tsconfig.json.

The .d.ts file is TypeScript's declaration file for JavaScript, which is used to declare js files. You can manually write a corresponding declaration file.

Use tools to generate declaration files

First, you need to configure tsconfig.json. In the root directory of your project, locate the file and fill in the following information:

{
  // change this option to match your project
  "include": ["src/**/*"]

  "compilerOptions": {
    // tell TypeScript to read JS files because they are usually ignored as source files
    "allowJs": true
    // generate .d.ts file
    "declaration": true
    // this compiler should only output d.ts files at runtime
    "emitDeclarationOnly": true
    // Type declarations should be placed in this directory. Remove this option, and the .d.ts file will be placed at the same level as the js file
    "outDir": "dist"
  }
}

Then execute:

Npx typescript your/js/file/path.js-declaration-allowJs-emitDeclarationOnly-outDir types

Please replace the path information on the command line. For example, I need to create a declaration file for the src/utils/colors.js file in the project Enter the file path, then execute it, and after a while, you can see that it has been compiled successfully!

The way for js to upgrade ts 2

Then you can see the newly created declaration file in the project.

Source file for js:

Road 3 for js to upgrade ts

Newly created declaration file:

Road 4 for js to upgrade ts

No other operation is required, so it can be directly introduced into the project. Of course, you can also modify the declaration file on a small scale. For example, if you only want a string, you can change any to string.

Using ts in vue files

With the above conversion method, you can use js to ts flexibly. What about the operation in the vue file?

There are two ways, but they both need a pre-operation:

Modify the lang attribute in the <script> tag of the vue file to ts, that is:

<script lang="ts">
// vue
</script>

Use class mode

Go directly to the code, because it is basically different from the usual vue file.

Import {Vue, Component} from "vue-property-decorator"

@ Component ({SomeOtherComponent})
Export default class VueClassComponent extends Vue {
    // equivalent to a data attribute
    Private dataA: number = 1


Get computedA: string {
Return this.dataA = = 1? "a": "b"
}

// equivalent to a method method
Private onClick (e: MouseEvent): void {
Return true
}

/ / declare periodic functions
Private created () {
// do something
}

Private beforeDestroy () {
// do something
}

It's basically like this, and the official vue also uses this as the main description. But in this way, visual inspection is not more compatible with vue3. After all, the biggest change in the writing of vue3 is not in this way. Instead, a highly mobile setup () method is added to the original foundation, so I ruled out this way of use when I modified it.

Use the original way that is more like vue

The flexibility of vue may be here, the flexibility of writing is very suitable for quickly upgrading js to ts. You just need to make some changes in the original vue file:

Import Vue, {PropType} from "vue"

Export default Vue.extend ({
Name: "VueComponent"

Props: {
SomeProps: {
Type: String
Default: ""
}

// because passing values can only use the basic type of js, but vue provides a conversion method.
// in ts, the type should be interface
SomeComplexProps: {
Type: Object as PropType < MyComplexObject >
}
}

Data () {
Return {
DataA: 1, // No type is required. The default is number.
DataB: void 0 as undefined | number // can be either a single type or a compound type
}
}

Computed: {
// it should be noted here that the calculated properties should explicitly give the return type. This is also stated in the vue documentation, because dynamic cannot map the corresponding type and needs to be explicitly declared.
ComputedA (): number {
Return 1
}
}

Methods: {
OnClick (e: MouseEvent) {
// do something
}
}

// everything else is the same
});

In this way, the general logic and code modification are basically consistent.

Inject custom attributes to the vue prototype

Sometimes you need to use some user-defined methods and attributes globally. In the js era, you can directly add them in the main file and in the prototype chain of vue. To use ts, you need to not only add it to the prototype chain, but also declare it in the declaration file. For example, if you want to add a tool method named $u to vue, you need to do three steps:

1. Export the tool method and declare:

Tool functions in the src/utils folder, create an index.ts and organize all the tool functions as follows:

// whether or not a function
Const isFunction = (o: any) = > {
  Return Object.prototype.toString.call (o) .slice (8,-1) = = "Function"
}

// whether Boolean or not
Const isBoolean = (o: any) = > {
  Return Object.prototype.toString.call (o) .slice (8,-1) = = "Boolean"
}

// Export function entity
Export const utils = {
IsFunction
IsBoolean
}

// Export function declaration
Export interface Utils {
IsFunction: (o: any) = > boolean
IsBoolean: (o: any) = > boolean
}

2. Add prototype chain

Add a prototype chain to main.ts:

Import {utils} from "@ / utils"
Vue.prototype.$u = utils

3. Add a declaration

Finally, find the vue-prototype.d.ts file in the /src directory, import the Utils interface declaration just now, and add:

Import {Utils} from "@ / utils"

Declare module "vue/types/vue" {
  Interface Vue {
    $u: Utils
  }
}

In this way, you can use the $u method in any vue file in the project, and you can point out the prompt ~

The way for js to upgrade ts 5

Conclusion

The conversion is almost complete at this point. The main reason for my upgrade project is that it can provide type support, so that we no longer worry about the type in the project, it is much easier to use.

Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).