前言
之前记得写过一篇 《关于vConsole 源码的理解分享(vConsole一个移动端调试控制台工具)》的博文,最近在看这个项目的时候,发现作者又开始维护这个项目了,而且还发现微信开发者工具,手机模拟的时候用到这个工具,说明这个腾讯开源的项目被用在了内部,需要维护起来了。我记得之前的那个项目是18年之后好像就没怎么在github上更新过了, 但是刚看了提交记录发下其实一致在维护的。
重大改动
重新看了下源码和之前写的文章的时候相比较,有两个大的改动点
- 使用svelte来做 UI的事了,之前是用一个js方法来解析引入的html,现在使用更成熟的框架来做这件事了
- 使用typescript
其实最重要的变化是svelte的变化
使用svelte
vConsole中的dom 方案换成了svelte, 下面的代码主要看如何加载svelte 和 如何加载less
以core 源码分析
-
加载svelte 的核心方法
core.ts 文件
// 初始化svelte 组件, target 为挂载的dom, props为svelte的属性 this.compInstance = new CoreCompClass({ target, props: { switchButtonPosition: { x: switchX, y: switchY, }, }, });
-
加载外部less 加载
core.svelte 文件
onMount(() => { // modify font-size to prevent scaling // const dpr = window.devicePixelRatio || 1; const viewportEl = document.querySelectorAll('[name="viewport"]'); if (viewportEl && viewportEl[0]) { const viewportContent = viewportEl[viewportEl.length - 1].getAttribute('content') || ''; const initialScale = viewportContent.match(/initial\-scale\=\d+(\.\d+)?/); const scale = initialScale ? parseFloat(initialScale[0].split('=')[1]) : 1; if (scale !== 1) { fontSize = Math.floor(1 / scale * 13) + 'px'; } // console.log(scale, fontSize); } // style // 加载style Style.use && Style.use(); // console.log('core.svelte onMount', Style); unsubscribe = contentStore.subscribe((store) => { if (!show) { return; } if (preivousContentUpdateTime !== store.updateTime) { preivousContentUpdateTime = store.updateTime; autoScrollToBottom(); } }); });
-
改变svelte的属性
/**
* Update the position of Switch button.
*/
public setSwitchPosition(x: number, y: number) {
// 直接. 修改属性
this.compInstance.switchButtonPosition = { x, y };
}
export let theme = '';
svelte中暴露的prop.
-
事件的监听
svelte提供方法
// 新建一个事件分发对象 const dispatch = createEventDispatcher();
// svelte组件中使用,触发事件 const onTapEventShow = (e) => { dispatch('show', { show: true }); };
// ts 中绑定svelte实例的事件 this.compInstance.$on('show', (e) => { if (e.detail.show) { this.show(); } else { this.hide(); } });
总结
再次读vconsole的源码,大致结构以及对象的形式基本没变,就换了个svelte, 本质上还是一个操作dom和事件交互的库, 只不过svelte框架的优势就是很vue化,使得使用起来更便利。