feat(createFile): support async content #299
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
首先是关于effect机制。
在shuvi中,@vue/reactivity 无法追踪异步effect,或者说是nextTick里发生的effect。
一般来说,effect会首先被执行一次,并收集依赖。
我们发现,effectFunction在访问reactive的变量时,如果发生在nextTick中,那么该变量将无法被正常追踪。
这个问题会导致,如果content是异步函数,并且引用了context(projectManager/fileManager设置的context),当reactive context 变更时,
无法触发effect。
这个issue简要说明了这个问题
vuejs/core#2093
vue/core源码的测试用例也可以证实这个问题
需要注意的是,官方文档里watchEffect里异步函数的例子是给reactive变量赋值,而非访问(其实相当于react的useEffect)。
当前,createFile具有三种签名
1 参数是一个对象,其字段分别为name,content函数(没有参数),dependencies
2 参数是一个对象,其字段分别为name,content函数(参数为context),dependencies
3 参数是一个函数,这个函数接受一个context参数,并返回1中的对象
由于前面说的,如果createFile需要引用context,那么其content函数必须是同步函数才能工作。
因此,对于本次异步化改造,只改造了1的情况。
其中3的情况目前其实已经不存在了。最初,filePresets仅由service负责,于是有一个比较庞大的context来存放文件信息。
当时,对于custom app/runtime/server.js来说,dependencies是存放在context中的,而context只能从content函数中拿到,为此,只好设计了3这种签名以满足需求。