志不强者智不达。——《墨子·修身》

在一个 JavaScript + Vue 项目中引入 TypeScript 编写的代码组件

1. 保证依赖支持 TypeScript

  • 安装 TypeScript 相关依赖(如果还没有):

    1
    2
    npm install --save-dev typescript
    npm install --save-dev @types/node
  • 如果你的 Vue 版本是 Vue 2,建议也装上 vue-property-decoratorvue-class-component(class 风格):

    1
    npm install --save vue-class-component vue-property-decorator

2. 配置 tsconfig.json

  • 在项目根目录新建或完善 tsconfig.json,确保包括你的 TypeScript 组件目录。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    {
    "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "allowJs": true,
    "checkJs": false,
    "jsx": "preserve",
    "sourceMap": true,
    "strict": false,
    "baseUrl": ".",
    "paths": {},
    "types": [
    "webpack-env"
    ],
    "lib": [
    "esnext",
    "dom",
    "dom.iterable",
    "scripthost"
    ]
    },
    "include": [
    "src/**/*",
    "typings/**/*.d.ts"
    ]
    }

3. 直接在 Vue 单文件组件中引入 ts 组件

场景A:你写的 ts 组件也是 vue 单文件组件(.vue)

  1. 直接用 <script lang="ts"> 即可(Vue CLI、Vite 都支持):

    1
    2
    3
    4
    5
    6
    7
    <!-- MyComponent.vue -->
    <script lang="ts">
    import { defineComponent } from 'vue'
    export default defineComponent({
    // 你的TS代码
    })
    </script>
  2. 你的 js 组件可以直接 import 这个 ts 组件使用:

    1
    import MyComponent from './MyComponent.vue'

场景B:ts 组件是纯 .ts 文件(比如工具函数或类)

  • 直接 import 即可,Vite 或 Vue CLI 都会识别:

    1
    import { myUtil } from './utils/myUtil.ts'

4. 如果是外部 TypeScript 库

  • 直接 npm 安装,然后 import 使用即可。
  • 如果没有类型声明,可以自己写一个 .d.ts 文件简单声明。

5. 常见问题

  • 没有类型提示/报错?
    请检查 tsconfig.json 是否包含了 TypeScript 文件目录。
  • JS 文件中 import TS 文件出错?
    allowJs: true 可以支持 js/ts 混用。
  • Vetur/Volar 报错?
    可以考虑升级相关插件或者切换到 Volar(推荐新项目用 Volar)。

6. 典型用法示例

ts 组件:

1
2
3
4
5
6
7
8
9
10
11
import { defineComponent } from 'vue'

export default defineComponent({
name: 'MyTsComponent',
props: {
msg: String
},
setup(props) {
return () => <div>{props.msg}</div>
}
})

js 组件中引用:

1
2
3
4
5
6
<script>
import MyTsComponent from '../components/MyTsComponent.ts'
export default {
components: { MyTsComponent }
}
</script>

7. 总结

  • 配置好 tsconfig.json
  • 直接 import TS 组件或者 <script lang="ts">
  • 使用 Vite/Vue CLI 这样的现代工具基本无缝