In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
本篇内容介绍了"Node.js + imgcook如何自动生成依赖"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
imgcook 在淘宝内部版本提供了类似依赖管理的功能,用于在 imgcook 编辑器编写函数时引入其他依赖包,比如 axios、underscore、@rax/video 等。
不过从使用体验上,还是较为繁琐,因为编辑器并没有让大家形成像在 package.json 声明依赖的习惯,而且因为编辑器是 GUI 界面,所以从每个函数打开代码,并查看依赖的操作是比较繁琐的,这就导致每次开发完一个 imgcook 模块后,如果依赖了其他包(大部分情况下都需要),就需要一个个打开函数并确认版本号,并在依赖管理中添加,这在我使用的过程中,往往是一次痛苦的过程。
如何解决
imgcook 提供了 Schema 源码开发模式,通过在编辑器中直接修改模块协议(Schema)就能替代 GUI 的操作步骤,然后通过搜索 dependencies,我发现依赖管理功能是通过协议中的 imgcook.dependencies 实现的:
{ "alias": "Axios", "packageRax1": "axios", "versionRax1": "^0.24.0", "packageRaxEagle": "axios", "versionRaxEagle": "^0.24.0", "checkDepence": true }
由于函数的代码也存在协议中,那么是不是只需通过处理原协议文档,扫描出对应的依赖并保存到节点中,再点击"保存"就可以看到依赖管理中的包列表被更新了。
实现功能
为此我在 @imgcook/cli 中实现了拉取模块协议内容的功能,具体 Pull Request 有:imgcook/imgcook-cli#12 和 imgcook/imgcook-cli#15,可以通过命令行工具拉取对应模块的协议(Schema)如下:
$ imgcook pull -o json
执行后会把模块协议内容输出到命令行中的 stdout。
有了这个功能后,就可以实现一些命令行工具,基于 Unix Pipeline 程序,与 imgcook-cli 的数据源形成协作,举个例子,通过 imgcook pull 输出的 JSON 并不易读,那么不妨写一个 imgcook-prettyprint 来美化输出结果,代码实现如下:
#!/usr/bin/env node let originJson = ''; process.stdin.on('data', (buf) => { originJson += buf.toString('utf8'); }); process.stdin.on('end', () => { const origin = JSON.parse(originJson); console.log(JSON.stringify(origin, null, 2)); });
上面的程序通过 process.stdin 接收管线(Pipeline)上游的数据,即 imgcook 模块协议内容,然后在 end 事件中解析并美化输出,运行如下命令:
$ imgcook pull -o json | imgcook-prettyprint
就能看到美化后的输出结果了,这就是一个 Unix Pipeline 程序的简单示例。
接下来就来看下如何通过这种方式,完成依赖的自动生成。与上面例子类似,我们再创建一个文件 ckdeps:
#!/usr/bin/env node let originJson = ''; process.stdin.on('data', (buf) => { originJson += buf.toString('utf8'); }); process.stdin.on('end', () => { transform(); }); async function transform() { const origin = JSON.parse(originJson); const funcs = origin.imgcook?.functions || []; if (funcs.length === 0) { process.stdout.write(originJson); return; } console.log(JSON.stringify(origin)); }
通过 origin.imgcook.functions,可以获取到函数的代码内容,比如:
{ "content": "export default function mounted() {\n\n}", "name": "mounted", "type": "lifeCycles" }
那么接下来就是通过解析 content,获取到代码中的 import 语句,再生成对应的依赖对象到 origin.imgcook.dependencies 中,那么我们需要引用 @swc/core 来解析 JavaScript 代码:
const swc = require('@swc/core'); await Promise.all(funcs.map(async ({ content }) => { const ast = await swc.parse(content); // the module AST(Abstract Syntax Tree) }));
获取到 ast 后,就能通过代码获取 import 语句的信息了,不过由于 ast 比较复杂,@swc/core 提供了专用的遍历机制如下:
const { Visitor } = require('@swc/core/visitor'); /** * 用于保存通过函数解析, 获得的依赖对象列表 */ const liveDependencies = []; /** * 定义访问器 */ class ImportsExtractor extends Visitor { visitImportDeclaration(node) { let alias = 'Default'; liveDependencies.push({ alias, packageRax1: node.source.value, versionRax1: '', packageRaxEagle: node.source.value, versionRaxEagle: '', checkDepence: true, }); return node; } } // 使用方式 const importsExtractor = new ImportsExtractor(); importsExtractor.visitModule(ast);
类 ImportsExtractor 继承自 @swc/core/visitor 的 Visitor,由于是要遍历 import 声明语句,它的语法类型名称是 ImportDeclaration,因此只需要实现 visitImportDeclaration(node) 方法,即可在方法内获得所有的 import 语句,再按照对应节点的结构转换成依赖对象并更新就好。定义好抽取器后,剩下的事情就是把 ast 喂给抽取器,这样就能把模块所有的依赖都收集起来,用于后面依赖的生成。
从上面的代码可以看到,版本号目前使用了空字符串,这会导致我们如果更新协议内容,依赖的版本信息会丢失,因此我们需要定义一种获取版本的方法。
由于前端的依赖都是存储在 NPM Registry 上的,因此我们可以通过 HTTP 接口来获取版本,比如:
const axios = require('axios'); async function fillVersions(dep) { const pkgJson = await axios.get(`https://registry.npmjs.org/${dep.packageRax1}`, { type: 'json' }); if (pkgJson.data['dist-tags']) { const latestVersion = pkgJson.data['dist-tags'].latest; dep.versionRax1 = `^${latestVersion}`; dep.versionRaxEagle = `^${latestVersion}`; } return dep; }
我们按照 https://registry.npmjs.org/${packageName} 的规则,就能拿到存储在 Registry 中的包信息,然后 data['dist-tags'].latest 代表的是 latest 标签对应的版本,简单来说就是当前包的最新版本,然后再基于这个版本号增加一个 ^ 版本前缀即可(你也可以按照自己的诉求修改最终的版本以及 NPM Registry)。
最后一步,就是把我们从函数代码中抓取的依赖信息更新,并输出出来:
async function transform() { // ... origin.imgcook.dependencies = newDeps; console.log(JSON.stringify(origin)); }
然后通过运行:
$ imgcook pull -o json | ckdeps > { ..., "dependencies": [{ ... }] }
然后,开发者只需要把输出的 JSON 拷贝到编辑器中保存。哦,等等,在编辑器中并不能直接使用 JSON 保存,而是需要使用 ECMAScript Module 的方式(export default { ... }),那这样是不是意味着每次都需要手动编辑一下呢,答案是否,Unix Pipeline 的思路非常利于解决这种流程问题,我们只需要再新建一个节点脚本 imgcook-save 即可:
#!/usr/bin/env node let originJson = ''; process.stdin.on('data', (buf) => { originJson += buf.toString('utf8'); }); process.stdin.on('end', () => { transform(); }); async function transform() { const origin = JSON.parse(originJson); console.log(`export default ${JSON.stringify(origin, null, 2)}`);}
最后完整的命令是:
$ imgcook pull -o json | ckdeps | imgcook-save > export default { ... }
这样,我们就可以直接拷贝内容到编辑器。
效果体验
比如,我在喔其中一个项目的 created 函数中增加了 axios 的依赖,关闭窗口后点击保存(确保 Schema 保存),然后通过命令:
$ imgcook pull -o json | ckdeps -f | imgcook-save
然后在编辑器中打开 Schema 编辑,复制生成的内容并保存,然后打开"依赖管理"可以看到:
通过解析生成的代码已经更新到依赖面板了,这下终于可以解放双手,去做其他的事情了。
One more thing?
是不是这样就结束了呢?在 macOS 中,提供了 pbcopy 命令,可以复制 stdin 到剪贴板,那么跟 imgcook 的例子结合一下:
$ imgcook pull -o json | ckdeps | imgcook-save | pbcopy
这样就省掉了自己拷贝的工作,命令执行完直接打开编辑器 ⌘V 即可。
最后的最后,我要升华一下主题,在 @imgcook/cli 支持了输出 JSON 文本的功能后,就意味着 imgcook 接入了 Unix Pipeline 的生态,通过这种方式,我们可以在这个过程中构建很多有趣实用的工具,并与很多 Unix 工具协作使用(比如 bpcopy、grep、cat、sort 等)。
本文只是通过依赖的自动生成为例,使用 Unix Pipeline 的方式,验证了其可行性以及和 imgcook 编辑器配合使用的体验,目前来说,我可以通过这种方式,弥补不少编辑器上的体验缺失,让我更方便地使用 imgcook 的核心功能。
"Node.js + imgcook如何自动生成依赖"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.