Vue.js 3 Cookbook
上QQ阅读APP看书,第一时间看更新

Adding TypeScript to a Vue CLI project

Using TypeScript in a JavaScript project, even for static type checking, is good practice. It helps minimize the chance of errors and Object problems inside your project.

Adding TypeScript to a Vue project with the help of the Vue UI is very simple, and you will be able to use JavaScript code with TypeScript.

Getting ready

The pre-requisite for this recipe is as follows:

  • Node.js 12+

The Node.js global objects that are required are as follows

  • @vue/cli
  • @vue/cli-service-global

How to do it...

First, we need to create our Vue CLI project. To find how to create a Vue CLI project, please check the 'Creating your first project with Vue CLI' recipe. We can use the one we created in the last recipe or start a new one.

To add TypeScript to a Vue CLI project, follow these steps:

  1. Open the Vue UI interface. Open the Terminal (macOS or Linux) or Command Prompt/PowerShell (Windows) and execute the following command:
> vue ui
  1. On your project, go to the Plugins manager, click on + Add plugin, and search for @vue/cli-plugin-typescript:

  1. Now, click on the Install @vue/cli-plugin-typescript button at the bottom of the page:

  1. You will be asked for some configuration settings after the plugin is downloaded, before the final installation:
    • Use class-style component syntax? Use the vue-class-component plugin with TypeScript.
    • Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Activate Babel to transpile TypeScript in addition to the TypeScript compiler.
    • Use ESLint? Use ESLint as a linter for the .ts and .tsx files.
    • Convert all .js files to .ts? Automatically convert all your .js files to .ts files in the installation process.
    • Allow .js files to be compiled? Activate the tsconfig.json flag to accept .js files in the compiler.
  2. After choosing your options, click on Finish the installation.
  3. Now, your project is a TypeScript Vue project, with all the files configured and ready to be coded:

How it works...

The Vue UI as a plugin manager will download the TypeScript package made for Vue, and install and configure it for you with the settings you choose.

Your project will be changed and modified according to your specifications, and will then be ready for development.

See also

Find more information about TypeScript ESLint at https://github.com/typescript-eslint/typescript-eslint

Find more information about vue-class-component at https://github.com/vuejs/vue-class-component.