尽管typescript 提供了直接引用外部定义文件的功能(@types),但是很多时候以前的模块以及公司内部的项目都不好方便的支持typescript 类型特性,以下是一个简单的集成说明
环境准备
-
- 项目结构
├── app-demo
├── app-demo-types
└── app-learning
-
- 说明
app-demo 一个简单的js 项目,这个npm 包是我们需要后期创建ts 定义的
app-demo-types 基于typescript 对于app-deme 项目创建ts 定义文件
app-learning 我们基于js 以及typescript 的模式使用开发的app-demo npm 包
集成使用说明
具体代码参考github
-
- app-demo 代码
Login.js
module.exports = class Login{
constructor(name,age){
=name;
this.age=age;
}
login(){
return `${}------${this.age}`
}
}
-
- app-demo-types
pacakge.json
{
"name": "@dalongrong/types-demo-types",
"version": "1.0.2",
"types": "index.d.ts",
"license": "MIT",
"scripts": {
"p": "yarn publish --access public"
},
"publishConfig": {
"registry": "https://"
}
}
index.d.ts
declare module "@dalongrong/types-demo" {
export class Login{
constructor(name:string,age:number)
login():string
}
}
declare module "@dalongrong/types-appdemo" {
export class Login{
constructor(name:string,age:number)
login():string
}
}
-
- app-learning 集成
package.json
{
"name": "app-learning",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@dalongrong/types-demo": "^1.0.0",
"@dalongrong/types-demo-types": "^1.0.2"
}
}
tsconfig.json
{
"include": [
"src/**/*"
],
"files": ["node_modules/@dalongrong/types-demo-types/index.d.ts"], // ts 定义文件引入
"compilerOptions": {
"declaration": true,
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"outDir": "dist",
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
src/app.ts
import {Login} from "@dalongrong/types-demo"
let login = new Login("dd",333)
let info = login.login()
console.log(info)
vs code 提示信息
app.js
// 基于reference 引用
/// <reference types="@dalongrong/types-demo-types" />
const {Login} = require("@dalongrong/types-demo")
console.log(Login)
var myuser = new Login("dalong",333)
console.log(myuser.login())
vs code 提示信息
说明
以上是基于typescript 自定义文件提升js 的类型能力的一个玩法,对于js 还是推荐直接基于typescript 开发(强大的生态),而且应该编写相关的类型定义文件
方便提升js 代码的类型处理能力