在Vue项目中使用Typescript的实现

2020-06-16 06:09:35易采站长站整理

3.0迟迟没有发布release版本,现阶段在Vue项目中使用Typescript需要花不小的精力在工程的配置上面。主要的工作是webpack对TS,TSX的处理,以及2.x版本下面使用class的形式书写Vue 组件的一些限制和注意事项。

Webpack 配置

配置webpack对TS,TSX的支持,以便于我们在Vue项目中使用Typescript和tsx。


module.exports = {
entry: './index.vue',
output: { filename: 'bundle.js' },
resolve: {
extensions: ['.ts', '.tsx', '.vue', '.vuex'] },
module: {
rules: [
{ test: /.vue$/, loader: 'vue-loader',
options: {
loaders: {
ts: 'ts-loader',
tsx: 'babel-loader!ts-loader',
}
}
},
{
test: /.ts$/,
loader: 'ts-loader',
options: { appendTsSuffixTo: [/TS.vue$/] } },
{
test: /.tsx$/,
loader: 'babel-loader!ts-loader',
options: {
appendTsxSuffixTo: [/TSX.vue$/] }
}
] }
}

在上面的配置中,vue文件中的TS内容将会使用ts-loader处理,而TSX内容将会按照ts-loader–>babel-loader的顺序处理。

appendTsSuffixTo/appendTsxSuffixTo 配置项的意思是说,从vue文件里面分离的script的ts,tsx(取决于<script lang=”xxx”></script>)内容将会被加上ts或者tsx的后缀,然后交由ts-loader解析。

我在翻看了ts-loader上关于appendTsxSuffixTo的讨论发现,ts-loader貌似对文件后缀名称有很严格的限定,必须得是ts/tsx后缀,所以得在vue-loader extract <script>中内容后,给其加上ts/tsx的后缀名,这样ts-loader才会去处理这部分的内容。

ts-loader只对tsx做语法类型检查,真正的jsx–>render函数应该交由babel处理。

所以我们还需要使用plugin-transform-vue-jsx来将vue jsx转换为真正的render函数。


// babel.config.json
{
"presets": ["env"],
"plugins": ["transform-vue-jsx"]}

同时,配置TS对tsx的处理为preserve,让其只对tsx做type类型检查。


// tsconfig.json
{
"compilerOptions": {
"jsx": "preserve",
}

使用vue cli 4.x

高版本的vue cli如4.x已经集成了vue + typescript的配置。选择use Typescript + Use class-style component syntax选项创建工程。

创建后的工程目录如下:

在src根目录下,有两个shims.xx.d.ts的类型声明文件。


// shims.vue.d.ts
declare module "*.vue" {
import Vue from "vue";
export default Vue;