安装ts命令,全局安装typescript
npm i -g typescript
安装完成后,输入以下命令检查安装是否成功
npm i -g typescript
第一个ts程序
// index.ts (()=>{ function hello(str){ return 'hello' + str } console.log(hello('jack')) })()
打开命令行,执行以下命令
tsc index.ts
会自动生成index.js
node index.js // 打印结果为hellojack
类型注解
TypeScript 里的类型注解是一种轻量级的为函数或变量添加约束的方式。
//错误演示 (()=>{ function hello(str:string){ //(1)str变量已被约束为只能赋值string类型 return 'hello,'+str } console.log(hello(1)) //(2)此处会报错,因为str只能接收string类型 / 类型“number”的参数不能赋给类型“string”的参数。 })()
//正确演示 (()=>{ function hello(str:string){ //(1)str变量只能赋值string类型 return 'hello,'+str } console.log(hello('jack')) //(2)此处str变量为string类型,不会报错 })()
接口
在 TypeScript
里,只在两个类型内部的结构兼容,那么这两个类型就是兼容的。 这就允许我们在实现接口时候只要保证包含了接口要求的结构就可以,而不必明确地使用 implements
语句。
interface Person{ //使用接口描述了一个拥有firstname和lastname的字段对象 firstname:string, lastname:string } function greeter(person:Person){ //规定person只能接收和接口结构相同的对象 return person.firstname + person.lastname } let user = { firstname:'米', lastname:'耀华' } console.log(greeter(user)) //米耀华
使用webpack打包ts
下载依赖
yarn add -D typescript yarn add -D webpack@4.41.5 webpack-cli@3.3.10 yarn add -D webpack-dev-server@3.10.2 yarn add -D html-webpack-plugin@4.5.0 clean-webpack-plugin@3.0.0 yarn add -D ts-loader@8.0.11 yarn add -D cross-env@7.0.2
src/main 入口文件
document.write('Hello Webpack TS!')
index页面:public/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>webpack & TS</title> </head> <body> </body> </html>
build/webpack.config.js
const {CleanWebpackPlugin} = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const path = require('path') const isProd = process.env.NODE_ENV === 'production' // 是否生产环境 function resolve (dir) { return path.resolve(__dirname, '..', dir) } module.exports = { mode: isProd ? 'production' : 'development', entry: { app: './src/main.ts' }, output: { path: resolve('dist'), filename: '[name].[contenthash:8].js' }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', include: [resolve('src')] } ] }, plugins: [ new CleanWebpackPlugin({ }), new HtmlWebpackPlugin({ template: './public/index.html' }) ], resolve: { extensions: ['.ts', '.tsx', '.js'] }, devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map', devServer: { host: 'localhost', // 主机名 stats: 'errors-only', // 打包日志输出输出错误信息 port: 8081, open: true }, }
打包命令配置(package.json中scripts节点)
"dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js", "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
启动 / 打包文件
npm run dev npm run build
发表评论