框架
重点:
webpack的rule中添加ts-loader;
happyPackMode置为true;
appendTsxSuffixTo中添加vue;
注:
happyPack: 多进程模式构建,实现构建加速;
appendTsxSuffixTo:为表达式列表匹配到的文件添加.ts或.tsx后缀,让 tsc 对 vue 文件能够当成一个 module 进行处理,以解决 moudle not found 的问题(tsc 本身不认识 vue 结尾的文件)
代码
this.webpackUtils.addModuleRules([{
name: 'module-ts',
test: /\.ts$/,
include: [PATH.resolve(projectDir, 'src')],
use: [
{
name: 'ts-loader',
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
happyPackMode: true,
appendTsxSuffixTo: [/\.vue$/]
},
}
],
},
业务代码
index.ts(入口文件)
// import Vue from 'vue/dist/vue.esm.js'
import Vue from 'vue'
import Index from './index.vue';
var VM = new Vue({
el: '#root',
// template: '<div><Index /></div>',
// components:{Index}
render: h => h(Index)
});
index.vue
script标签中添加lang="ts",否则不能识别ts。
<template>
<div id="app">aaaa
{{message}}
</div>
</template>
<script lang="ts">
export default {
data() {
return {
message: 'Hello Vue!'
}
},
created() {
// `this` 指向 vm 实例
// let name = "vueeeeee";
let name: string = "tssssssss";
console.log('a is: ' + name)
}
};
</script>
参考
1、[在Vue中使用TypeScript]
(https://juejin.im/entry/5b19682be51d4506c1301e6f)
2、[webpack thread-loader with ts-loader]
(https://stackoverflow.com/questions/52570597/webpack-thread-loader-with-ts-loader)