vscode 里js代码智能提示

在编写代码时能获得智能提示是一件极其舒适以及富有安全感的事情,javascript的代码,在很多情况下都不能获得很友好的提示,故有了typescript,但是从javascript迁移代码到typescript中的代价比较大,所以js项目的开发过程中,总结了几种在vscode中获得代码智能提示的方法,以供大家参考。

模块使用

使用npm模块时,一般的模块都会带有d.ts的类型文件描述,所以当模块引入进来以后,使用模块的时候都会带有相关接口或者属性的只能提示。
某些库如果没有d.ts文件的时候,可能需要安装类型文件 @types/some-module

类型注释

某些变量在开发过程中是可以确定变量类型的,所以可以在定义变量或者方法的时候添加js注释,以获得相关的代码提示,如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/** @type { HTMLCanvasElement } */
const canvas = document.getElementById('tutorial');

/** @type { import("vuex/types").Module } */
const mod = {
namespaced: true,
state: {}
}

/**
* @param {String} url
* @param {Object} data
* @returns {Promise<{ code: Number, message: String, data: Object }>}
*/
async function baseRequest(url, data) {
return axios({ method: 'post', url, data });
}

当然也可以提前定义类型:

1
2
3
4
5
6
7
8
9
10
11
/**
* @typedef { import("vuex/types").Module } Module
*/

// some code

/** @type { Module } */
const mod = {
namespaced: true,
state: {}
}

jsconfig的typeAcquisition

有些库可能是通过html的script标签直接引进进来的,然后会在代码里使用某个全局变量,这种情况下,想要或者这个全局变量的相关智能提示,可以使用jsconfig.jsontypeAcquisition提供的功能,简单用法如下:
createjs为例:
首先在html中引入了createjs的库

1
2
3
<!-- some code -->
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<!-- some code -->

然后安装createjs的类型

1
npm install -D @types/createjs

之后在项目的根目录下新建一个jsconfig.json文件,内容如下,当然还可以添加一下其他配置,这个配置文件很有用的

1
2
3
4
5
{
"typeAcquisition": {
"include": ["createjs"]
}
}

具体代码使用:

1
2
3
4
5
6
7
8
const stage = new createjs.Stage('tutorial')

const circle = new createjs.Graphics();
circle.beginFill('red');
circle.drawCircle(100, 100, 50);

const shape = new createjs.Shape(circle);
stage.update();

当然这种方法的前提是有对应的类型文件,并且你知道类型文件中声明的namespace叫什么。