TypeScript 快速上手学习系列- 结合Vue使用

本文介绍了如何快速上手TypeScript并将其与Vue结合使用。首先,创建项目目录和结构,接着初始化项目并安装相关依赖,如Vue和TypeScript。然后,添加配置文件和必要的脚本,确保Webpack能正确处理TypeScript。最后,展示如何编写Vue组件并使用TypeScript进行定义。
摘要由CSDN通过智能技术生成

TypeScript-Vue

创建目录

创建项目文件夹:

mkdir ts-demo

创建 src 文件夹:

mkdir src

当前 demo 结构:

ts-demo/
└─ src/

进入 src 目录新建 components 文件夹:

cd src
mkdir components

在根目录创建 dist 文件夹:

mkdir dist

现在,项目结构如下:

ts-demo/
├─ dist/
└─ src/
   └─ components/

初始化项目

在根目录初始化项目:

npm init

安装完成:

D:\demo\ts-demo\src>cd ..

D:\demo\ts-demo>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ts-demo)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\demo\ts-demo\package.json:

{
  "name": "ts-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

安装依赖

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

安装完成:

D:\demo\ts-demo>npm install --save-dev typescript webpack webpack-cli ts-loader css-loader vue vue-loader vue-template-compiler
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts-demo@1.0.0 No description
npm WARN ts-demo@1.0.0 No repository field.

+ webpack-cli@4.9.2
+ vue-template-compiler@2.6.14
+ css-loader@6.7.0
+ ts-loader@9.2.7
+ vue-loader@17.0.0
+ webpack@5.70.0
+ typescript@4.6.2
+ vue@3.2.31
added 175 packages from 193 contributors in 7.748s

添加TypeScript配置文件

tsc --init

安装完成:

D:\demo\ts-demo>tsc --init

Created a new tsconfig.json with:
                                                                                                                     TS
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true


You can learn more at https://aka.ms/tsconfig.json

添加webpack

向项目添加一份 webpack.config.js 文件:
webpack.config.js:

var path = require('path')
var webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

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]'
        }
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ]
      }
    ]
  },
  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',
  plugins: [
    // make sure to include the plugin for the magic
    new VueLoaderPlugin()
  ]
}

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
    })
  ])
}

package.json 中添加一行脚本:

"build": "webpack",

package.json

{
  "name": "ts-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^6.7.0",
    "ts-loader": "^9.2.7",
    "typescript": "^4.6.2",
    "vue": "^3.2.31",
    "vue-loader": "^17.0.0",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2"
  }
}

这样,就可以通过npm run build构建项目。

index.html:

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>typescript demo</title>
</head>

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

./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
    }
});

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('!');
        }
    }
});

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/vue-shims.d.ts:

declare module "*.vue" {
    import Vue from "vue";
    export default Vue;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值