How VUE integrates TypeScript

Vue – pain points of the router

As we successfully integrated TypeScript into the VUE project in our last post, we’ll focus on vue-Router as our first point of transformation in the project.

The vue-Router configuration currently has thousands of lines of code.

As you can see from the figure, there are 1200 lines of code for the router alone. However, the router code is basically the same, with a lot of copy code, so the disadvantages are obvious

  • New rules a page, it is difficult to find the insertion of the target anchor point, more trouble
  • A lot of configuration code is mixed with logical code, which is risky to modify
  • A router typically has a vue component, and each new rule requires a bunch of repetitive code
  • It’s hard to understand without visual routing

Refactoring began

1. The first step is to separate configuration from logic

Separate the configuration files into a single config.tsx file

TSX is used because some routers need to return a keep-alive component, and ts is unrecognizable because typescript considers it a JSX

Import the config. TSX file separately into router.ts

Then run server, this is the console error

For error handling, see the previous article

Although the console reported an error, the page still runs smoothly and is not affected.

In this way, the entire routing file, logic and configuration are basically separated, for the people who modify the route behind, it is very convenient, basically solve the first two pain points.

2. Config. TSX is generated using a configuration file

Although configuration and routing are separated, there are still some pain points in the configuration file. Look at the code

** ‘, {},[],keep-alive,import**

If it is a TSX file, it also needs to write // @ts-ignore, which is cumbersome and not intuitive, and there is the possibility of writing mistakes. In order to avoid this situation, it is better to use tools to generate, so we spent time developing vue-gen-router.

So let’s go straight to the code

// Add dependency yarn add --dev vue-gen-router node_modules/. Bin /vue-gen-router -I example/router.yamlCopy the code

TSX typescript file is generated in the SRC/Routers directory by default

Yaml /router.yaml /router.yaml /router.yaml /router.yaml

Enter on the command line

node_modules/.bin/vue-gen-router -i router.yaml -o src/routers -f config.tsx
Copy the code

View the generated code

This saves a lot of code, because it is generated by a template, so there is no problem. The key is that the router configuration file is changed to YAML data, paving the way for the next step of visual editing the route.

Vue-gen-router GitHub link if you like to give a star ah

That’s the end of the second post, and I’ll write the visual editing route later when I have time.