FrankKai.github.io
FrankKai.github.io copied to clipboard
VSCode插件开发踩坑
- require类型问题
- 查看打包后的插件内容
- dependencies中的包未生效
- 使用esbuild压缩打包文件
- 发布插件 ERROR TF400898
require类型问题
require不生效
读取项目中文件(require("./foo.js"))的话,需要采用非webpack模式的打包,否则会引入失败
require.cache
需要手动delete require.cache["xxxx"],否则会导致引入文件为缓存文件,获取不到最新文件。 本质上是因为nodejs的require有缓存机制。
查看打包后的插件内容
vsix包中的打包文件,受到.vscodeignore的影响,有两种方式查看即将生成的vsix包中的文件:vsce ls 和 将vsix后缀改为zip,解压后查看
dependencies中的包未生效
如果在插件内部引入了npm包作为运行时依赖,也就是dependencies,需要将.vscodeignore中的node_modules/**移除。移除后,会将node_modules也打入到vsix包中
使用esbuild压缩打包文件
有很重要的一点,esbuild天然支持打包ts类型的文件。
Bundling can automatically strip TypeScript types, convert ECMAScript module syntax to CommonJS, and transform newer JavaScript syntax into older syntax for a specific version of node
原始的ts方式打包
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile",
"build": "yarn compile && vsce package --no-yarn"
},
=>
esbuild方式优化打包
"scripts": {
"vscode:prepublish": "yarn esbuild-base -- --minify",
"esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node",
"esbuild": "yarn esbuild-base -- --sourcemap",
"esbuild-watch": "yarn esbuild-base -- --sourcemap --watch",
"test-compile": "tsc -p ./",
"pretest": "yarn test-compile"
},
其中最重要的是这一行:
esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node
- outfile需要与package.json中的main对应上
- external:vscode。将代码中的vscode模块标记为external,这样在打包时,就不会报出错误
- format=cjs。将包打包为commonjs,因为vscode插件是运行在vocode中,而vscode又是一个天然在node环境下运行的electron应用
- platform设置为node。format会自动设置为cjs,es6的export会被转化为CommonJS的exports对象;node内部模块,例如fs,会被标记为external(由于vscode插件运行时拥有node环境,因此nodejs内部模块即使没打进包也没关系);关闭tree shaking,因为tree shaking作用于es module,而不能作用于cjs
我开发的一个插件,使用esbuild打包后,大小从2.23MB(把node_modules,未压缩js文件,图片等等都打了进去),变成了44KB(一个高度压缩的extension.js,图片等等)。
发布插件 ERROR TF400898
运行vsce publish,提示如下错误: ERROR TF400898: An Internal Error Occurred. Activity Id: 78f21af1-d92d-4984-afcd-b53942d97394.
是因为package.json里的displayName为空导致的。
{
"displayName": "",
}
为其指定值即可。
vscode插件本地开发过程中运行正常,但是打包后引入插件就无效。 从侧边栏自定义了一个右键菜单,点击菜单中的选项会打开一个webview。但是打包之后引入插件,右键菜单出来了,点击之后webview不会打开。尝试了一下,把webview换成vscode.window.showWarningMessage,也没有生效。