去年咱们将基于 vue-cli2 构建的项目中的 webpack3 升级到 webpack4。今年咱们继续升(zhe
)级(teng
),添加 typescript
。html
目前市场上大部分脚手架在生成项目时都会提示是否要安装 typescript. 好比 vue-cli3+。但仍是有不少老项目或者是经过 vue-cli2 构建的项目一直在被维护中。若是你想对这些老项目从新改造、以旧换新,为其添加 typescript
支持的话,Give me five minutes Plz。vue
只须要如下 6 小步。node
$ npm install typescript ts-loader vue-property-decorator -D
复制代码
typescript
必须安装,你要问能不能不安装它,哼哼~你究竟干啥来的!webpack
ts-loader
告诉 webpack 我是 ts.git
vue-property-decorator
让 vue 支持修饰器,这里也可使用 vue-class-component
. 至于用法这里不讲,想了解能够点击开发教程进行阅读.github
在 build
目录下找到 webpack.base.config.js
文件. 新增一个 rule
配置.web
module: {
rules: [
...
{
test: /\.tsx?$/i,
use: [{
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/]
}
}],
exclude: /node_modules/
},
...
复制代码
在 src
目录下建立一个 shims-vue.d.ts
文件,这里叫啥无所谓,可是必需要以 .d.ts
为后缀.vue-router
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
复制代码
其做用是让TS编译器识别 vue 文件.vue-cli
在项目根目录下建立 tsconfig.json
文件. 这个文件可使用 tsc
命令建立.typescript
$ tsc --init
复制代码
若是提示没有 tsc
,你须要在全局安装 typescript
$ npm install typescript -g
复制代码
文件配置以下:
{
"compilerOptions": {
"strict": true,
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"allowSyntheticDefaultImports": true,
"declaration": false,
"noImplicitAny": true,
"strictNullChecks": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowJs": true,
"lib": [
"es2017",
"es2016",
"dom"
]
},
"include": ["src/**/*.*"],
"exclude": ["node_modules", "build", "dist"]
}
复制代码
这里不对配置一一进行介绍,想要了解能够点击编译选项进行阅读.
有 4 处文件须要修改
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
@Component
export default class App extends Vue {
}
</script>
复制代码
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
@Component
export default class HelloWorld extends Vue {
msg: string = 'Welcome to Your Vue.js App'
}
</script>
复制代码
import Vue from 'vue'
import Router, { RouteConfig } from 'vue-router'
import HelloWorld from '@/components/HelloWorld.vue'
Vue.use(Router)
const routes: RouteConfig[] = [
{
path: '/',
component:HelloWorld
}
]
export default new Router({
routes
})
复制代码
import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
复制代码
回到 webpack.base.config.js
配置文件,讲入口的 main.js
修改成 main.ts
便可.
module.exports = {
entry: {
app: './src/main.ts'
}
...
}
复制代码
到这里对 vue-cli2 添加 typescript 升级改造大(qing
)功(er
)告(yi
)成(ju
).
最后相关示例和总结双手奉上.