如何在Vue项目中使用Typescript

时间:2023-03-09 06:41:12
如何在Vue项目中使用Typescript

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

(完)