0.前言

本快速入门指南将会教你如何在Vue项目中使用TypeScript进行开发。本指南非常灵活,它可以将TypeScript集成到现有的Vue项目中任何一个阶段。

1.初始化项目

首先,创建一个新的项目目录。

mkdir typescript-vue-tutorial
cd typescript-vue-tutorial

接着,在目录中创建如下目录结构。

typescript-vue-tutorial/
├─ dist/
└─ src/
└─ components/

TypeScript文件将位于src目录下,经过TypeScript编译器进行编译,然后通过webpack进行打包,最终在dist目录下生成编译打包好的bundle.js。我们编写的任何组件都将放在src / components文件夹中。

mkdir src
cd src
mkdir components
cd ..

Webpack最终会为我们生成dist目录。

现在我们将把这个文件夹变成一个npm包。

npm init

执行上述命令,您将获得一系列提示。除程序入口点外,您可以使用默认值。您可以随时在为您生成的package.json文件中更改它们。

2.安装依赖

安装TypeScript,Webpack,Vue和必要的加载器。

npm install --save-dev typescript webpack ts-loader css-loader vue vue-loader vue-template-compiler

Webpack是一个工具,它将您的代码和可选的所有依赖项打包到一个.js文件中。虽然您不需要使用像Webpack或Browserify这样的打包工具,但这些工具将允许我们使用我们稍后会介绍的.vue文件。

我们不需要添加.d.ts文件,但是,如果我们使用的是一个没有声明文件的软件包,那么我们就需要安装相应的@types / package。

3.添加TypeScript配置文件

您也许想将所有的TypeScript文件放在一起——包括编写的代码以及必要的声明文件。

为此,您需要创建一个tsconfig.json,其中包含输入文件列表以及所有的编译设置。您只需在项目根目录下创建一个名为tsconfig.json的新文件,并填写以下内容:

{
"compilerOptions": {
"outDir": "./built/",
"sourceMap": true,
"strict": true,
"noImplicitReturns": true,
"module": "es2015",
"moduleResolution": "node",
"target": "es5"
},
"include": [
"./src/**/*"
]
}

4.添加Webpack配置文件

我们需要添加一个名为webpack.config.js的Webpack配置文件,来帮助我们打包项目。

新建webpack.config.js文件,并将以下内容写入该文件中:

var path = require('path')
var webpack = require('webpack') module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
}
// other vue-loader options go here
}
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
} if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}

5.添加构建脚本

package.json文件中的script选项中,添加一个名为build的选项来运行Webpack.

"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
}

6.创建一个基础项目

配置好以上环境后,我们就可以创建一个Vue & TypeScript项目。

首先,新建./src/index.ts文件并写入以下内容。

// src/index.ts

import Vue from "vue";

let v = new Vue({
el: "#app",
template: `
<div>
<div>Hello {{name}}!</div>
Name: <input v-model="name" type="text">
</div>`,
data: {
name: "World"
}
});

接着,新建index.html 文件并写入以下内容。

<!doctype html>
<html>
<head></head> <body>
<div id="app"></div>
</body>
<script src="./dist/build.js"></script> </html>

最后,执行命令npm run build,并且在浏览器中打开 index.html

此刻,你将看到页面上显示的Hello World

在这下面,还有一个输入框,通过改变输入框的内容,页面上的内容也会随之改变。

恭喜!

现在你已经完全搞定了TypeScript和Vue!

7.添加一个组件

可以通过以下方式声明Vue组件:

// src/components/Hello.ts

import Vue from "vue";

export default Vue.extend({
template: `
<div>
<div>Hello {{name}}{{exclamationMarks}}</div>
<button @click="decrement">-</button>
<button @click="increment">+</button>
</div>
`,
props: ['name', 'initialEnthusiasm'],
data() {
return {
enthusiasm: this.initialEnthusiasm,
}
},
methods: {
increment() { this.enthusiasm++; },
decrement() {
if (this.enthusiasm > 1) {
this.enthusiasm--;
}
},
},
computed: {
exclamationMarks(): string {
return Array(this.enthusiasm + 1).join('!');
}
}
});

该组件有两个按钮和一些文本。

渲染时,它需要一个初始的name和一个我们想要显示的感叹号的数量initialEnthusiasm

当我们点击“+”按钮时,它会在文本末尾添加一个感叹号。

同样,当我们点击-按钮时,它会删除感叹号,直到只剩下一个感叹号。

声明好组件后,在根Vue实例中可以按照如下方式引用:

// src/index.ts

import Vue from "vue";
import HelloComponent from "./components/Hello"; let v = new Vue({
el: "#app",
template: `
<div>
Name: <input v-model="name" type="text">
<hello-component :name="name" :initialEnthusiasm="5" />
</div>
`,
data: { name: "World" },
components: {
HelloComponent
}
});

8.单文件组件

目前,定义组件较为常用的方式是使用.vue单文件方式定义,我们可以试着将上述定义的组件改写成单文件组件(SFC)。

当使用Webpack或Browserify构建项目时,Vue提供了像 vue-loader and vueify 这样的插件,这些插件允许您以类似HTML的文件定义组件。这些以.vue扩展名结尾的文件是单文件组件。

我们已经在安装依赖项时已经安装了vue-loader。并且,在webpack.config.js文件中指定了ts-loader的appendTsSuffixTo:[/ \ .vue $ /]选项,它允许TypeScript处理从单文件组件中提取的代码。

另外,我们还必须告诉TypeScript 当.vue文件被导入时它是什么样子的。

所以,我们需要添加vue-shims.d.ts文件:

// src/vue-shims.d.ts

declare module "*.vue" {
import Vue from "vue";
export default Vue;
}

我们不需要在任何地方导入此文件。它将由TypeScript自动包含,

现在,我们就可以编写一个单文件组件!

<!-- src/components/Hello.vue -->

<template>
<div>
<div class="greeting">Hello {{name}}{{exclamationMarks}}</div>
<button @click="decrement">-</button>
<button @click="increment">+</button>
</div>
</template> <script lang="ts">
import Vue from "vue"; export default Vue.extend({
props: ['name', 'initialEnthusiasm'],
data() {
return {
enthusiasm: this.initialEnthusiasm,
}
},
methods: {
increment() { this.enthusiasm++; },
decrement() {
if (this.enthusiasm > 1) {
this.enthusiasm--;
}
},
},
computed: {
exclamationMarks(): string {
return Array(this.enthusiasm + 1).join('!');
}
}
});
</script> <style>
.greeting {
font-size: 20px;
}
</style>

在根组件中导入:

// src/index.ts

import Vue from "vue";
import HelloComponent from "./components/Hello.vue"; let v = new Vue({
el: "#app",
template: `
<div>
Name: <input v-model="name" type="text">
<hello-component :name="name" :initialEnthusiasm="5" />
</div>
`,
data: { name: "World" },
components: {
HelloComponent
}
});

在编写单文件组件时,我们需要注意以下几点:

  • 我们必须在script标签上声明 <script lang="ts">
  • 我们必须在index.ts中导入带有.vue扩展名的组件。
  • 我们默认导出一个对Vue.extend的调用(而不是选项包本身),如果你不写Vue.extend,在构建项目时会遇到错误。

现在,您可以尝试运行npm run build并打开index.html来查看结果!

完整代码请戳TypeScript Vue Starter

(完)

如何在Vue项目中使用Typescript的更多相关文章

  1. Vue项目中应用TypeScript

    一.前言 与如何在React项目中应用TypeScript类似 在VUE项目中应用typescript,我们需要引入一个库vue-property-decorator, 其是基于vue-class-c ...

  2. 如何在VUE项目中添加ESLint

    如何在VUE项目中添加ESLint 1. 首先在项目的根目录下 新建 .eslintrc.js文件,其配置规则可以如下:(自己小整理了一份),所有的代码如下: // https://eslint.or ...

  3. 如何在Vue项目中给路由跳转加上进度条

    1.前言 在平常浏览网页时,我们会注意到在有的网站中,当点击页面中的链接进行路由跳转时,页面顶部会有一个进度条,用来标示页面跳转的进度(如下图所示).虽然实际用处不大,但是对用户来说,有个进度条会大大 ...

  4. 转:如何在Vue项目中使用vw实现移动端适配

    https://www.w3cplus.com/mobile/vw-layout-in-vue.html 有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flex ...

  5. 如何在Vue项目中引入jQuery?

    假设你的项目由vue-cli初始化 (e.g. vue init webpack my-project). 在你的vue项目目录下执行: npm install jquery --save-dev 打 ...

  6. 如何在Vue项目中使用vw实现移动端适配(转)

    有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flexible实现手淘H5页面的终端适配>提出了Flexible的布局方案,随着viewport单位越来越 ...

  7. 如何在Vue项目中使用vw实现移动端适配

    有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在< 使用Flexible实现手淘H5页面的终端适配>提出了Flexible的布局方案,随着 viewport 单位 ...

  8. 如何在VUE项目中使用SCSS

    首先要了解什么是CSS 预处理器? SCSS是一种CSS预处理语言 定义了一种新的专门的编程语言,编译后形成正常的css文件,为css增加一些编程特性,无需考虑浏览器的兼容性(完全兼容css3),让c ...

  9. 如何在Vue项目中,通过点击DOM自动定位VScode中的代码行?

    作者:vivo 互联网大前端团队- Youchen 一.背景 现在大型的 Vue项目基本上都是多人协作开发,并且随着版本的迭代,Vue 项目中的组件数也会越来越多,如果此时让你负责不熟悉的页面功能开发 ...

随机推荐

  1. classpath:类路径

    classpath:可以用于web.xml中获取spring springmvc配置文件的位置 用于sprnig配置文件中获取mapper的位置 classpath:可以获取到java目录下的,res ...

  2. python基本数据类型及常用功能

    1.数字类型 int -int(将字符串转换为数字) a = " print(type(a),a) b = int(a) print(type(b),b) num = " v = ...

  3. 编译 lame for iOS

    网上找了许多编译lame的教程,结果都是编译失败,多次尝试后发现是编译脚本放错路径了,记录下编译的过程,把编译脚本放到源码文件夹中和修改编译脚本中的目录是关键: 一.首先去Lame官网 http:// ...

  4. .netCore+Vue 搭建的简捷开发框架--目录

    .netCore+Vue 搭建的简捷开发框架 .netCore+Vue 搭建的简捷开发框架 (2)--仓储层实现和EFCore 的使用 .netCore+Vue 搭建的简捷开发框架 (3)-- Ser ...

  5. Python flask构建微信小程序订餐系统☝☝☝

    Python flask构建微信小程序订餐系统☝☝☝ 一.Flask MVC框架结构 1.1实际项目结构 1.2application.py  项目配置文件 Flask之flask-script模块使 ...

  6. Java虚拟机重点知识归纳总结

    一.     JVM内存分区 分为程序计数器.虚拟机栈.本地方法栈.Java堆.方法区5个区域 其中Java堆和方法区是线程共享的,虚拟机栈.本地方法栈.程序计数器是线程隔离的. 程序计数器: 1.可 ...

  7. JavaScript回调函数和递归函数

    一.回调函数--通过函数的指针来调用函数 把一个函数的指针作为另一个函数的参数,当调用这个参数的时候,这个函数就叫做回调函数 在链式运动上会用到回调函数,之后运动会见到 A.通过指针来调用函数 B.通 ...

  8. Halcon一日一练:获取程序运行时间

    很多时候,我们需要知道每个函数的运算周期,以提高程序的运行效率.知道运行时间对于图像算法处理很重要 Halcon提供相关的算子,我们先来看代码: **获取图像处理时间 read_image(Image ...

  9. opencv::模板匹配(Template Match)

    模板匹配介绍 模板匹配就是在整个图像区域发现与给定子图像匹配的小块区域. 所以模板匹配首先需要一个模板图像T(给定的子图像) 另外需要一个待检测的图像-源图像S 工作方法,在带检测图像上,从左到右,从 ...

  10. 基于canvas实现钟表

    原理说明 1.通过arc方法实现钟表外环: 2.通过line实现钟表时针,分针,秒针和刻度标志的绘制,基于save和restore方法旋转画布绘制不同角度的指针: 3.通过font方法实现在画布上绘制 ...