Preface:

Record your emotional moments playing TS. Vue-cli does not support vue-config.ts, see this issue for details. As a TS freak, how could I throw in the towel? After half an afternoon, I did.

PS: The YiJie under issue is me.

First, explain the solution to the problem

Open the fridge, put the elephant in, and close the fridge. (bushi)

  1. First install two dependenciescross-env ts-node
  2. Modify yourpackage.jsonBecause IyarnWe use it a lot. So this isyarnOther package managers can do the same.
{
  "scripts": {
    "service": "cross-env VUE_CLI_SERVICE_CONFIG_PATH=./vue.config.ts ts-node ./node_modules/@vue/cli-service/bin/vue-cli-service.js"."serve": "yarn service serve"}},Copy the code
  1. Modify yourtsconfig.json
{
  "ts-node": {
    "transpileOnly": true."compilerOptions": {
      "module": "commonjs"}}}Copy the code
  1. Rename yoursvue.config.jsvue.config.tsAnd then fill in the type
import type { ProjectOptions } from '@vue/cli-service'

module.exports = {
  // ...
} as ProjectOptions
Copy the code

How was the problem solved

  • After looking through vue-CLI issue for a long time, I found that there is no best solution, all of them use JSdoc, and it has been delayed from 18 years to 21 years. I can’t bear it.

  • Check the vue-cli source code to find the package corresponding to vue-cli-service command. Since vue-CLI uses Monorepo, a little knowledge of Monorepo is required.

  • Find the corresponding bin directory and script file and start analyzing where the code loaded the file. The fastest way is to search globally for vue.config.js.

  • VUE_CLI_SERVICE_CONFIG_PATH, vue.config.js and vue.config. CJS will be loaded. Next we just need to inject the VUE_CLI_SERVICE_CONFIG_PATH environment variable as vue.config.ts we want.

  • Cross-env can be used here to set environment variables

  • Then we need our runtime environment to support TS. Here we use TS-Node to run our code.

    Is that why we need these bags

  • We then use these two packages for our purposes to combine the above service directive

  • Then we need to configure ts-Node, so modify tsconfig.json to make it commonjs.

  • This is where our problem is solved

conclusion

Ts ran away