vue-next先行版+typescript尝试

获取项目

  • git clone [email protected]:vuejs/vue-next-webpack-preview.git
  • cd vue-next-webpack-preview
  • npm install

添加typescript依赖

  • npm install typescript ts-loader --save-dev

修改项目

1. 创建tsconfig.json文件

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
{
"compilerOptions": {
"target": "ES5",
"module": "CommonJS",
"strict": true,
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.vue"
],
"exclude": [
"node_modules"
]
}

2. 修改webpack.config.js文件

  • entry项把path.resolve(__dirname, './src/main.js')改为path.resolve(__dirname, './src/main.ts')
  • resolve项添加extensions: [".ts", ".js", ".json"]
  • rules添加
1
2
3
4
5
6
7
8
{
test: /\.ts$/,
exclude: /node_modules/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
}
}

3. src文件夹下修改

  • main.js改为main.ts
  • 新建文件shims-vue.d.ts
1
2
3
4
5
declare module '*.vue' {
import { ComponentOptions } from 'vue'
const component: ComponentOptions
export default component
}
  • App.vue文件修改
    1. script添加lang="ts"
    2. 引入模块defineComponent,即import { defineComponent } from 'vue'
    3. js代码放到export default defineComponent ({})

测试项目

  • 新建test.ts的测试文件
1
2
3
4
5
6
7
8
9
10
11
import { ref } from 'vue'
interface param {
count: number;
}
export const test = (param: param) => {
const count = ref(param.count)
const inc = () => {
count.value++
}
return { count, inc }
}
  • App.vue中引入
1
2
3
4
5
6
7
8
import { defineComponent } from 'vue'
import { test } from './test'
export default defineComponent ({
setup() {
const { count, inc } = test({count: 3})
return { count, inc }
}
})
  • 当把test({count: 3})修改为test({count: ""})时,可以看到vscode已经提示报错