资讯专栏INFORMATION COLUMN

重构smart-import

Pocher / 3233人阅读

摘要:前情提要自动工具,前端打字员的自我救赎记第一次发布包经历,是重构中的代码是版本可以工作的代码配置文件待导入的模块引用模块的文件引用模块的方式忽略的模块实现监听文件的删除和添加以上代码主要使用了来监听文件的变化。

前情提要

自动 Import 工具,前端打字员的自我救赎

记第一次发布npm包经历,smart-import

GitHub:smart-import

develop是重构中的代码

master是1.0版本可以工作的代码

配置文件

from:待导入的模块

to:引用模块的文件

template:引用模块的方式

ignored:忽略的模块

</>复制代码

  1. {
  2. "from": "demo/pages/**/*.vue",
  3. "to": "demo/router/index.js",
  4. "template": "const moduleName = () => import(modulePath)",
  5. "ignored": [
  6. "demo/pages/pageA.vue"
  7. ]
  8. }
实现监听文件的删除和添加

</>复制代码

  1. #!/usr/bin/env node
  2. const path = require("path")
  3. const chokidar = require("chokidar")
  4. const config = JSON.parse(fs.readFileSync("smart-import.json"))
  5. class SmartImport {
  6. constructor({ from }) {
  7. this.from = from
  8. this.extname = path.extname(from)
  9. }
  10. watch() {
  11. chokidar
  12. .watch(this.from, {
  13. ignoreInitial: true
  14. })
  15. .on("add", file => {
  16. console.log("add", file)
  17. })
  18. .on("unlink", file => {
  19. console.log("unlink", file)
  20. })
  21. }
  22. }
  23. let smartImport = new SmartImport(config)
  24. smartImport.watch()

以上代码主要使用了chokidar来监听文件的变化。但存在一个问题,如果删除文件夹,而文件夹中包含匹配的模块,不会触发unlink事件。所以改成watch整个目录,然后在addunlink的回调中添加判断文件后缀的代码,因为我们可能只在意.vue,而不在意.js

</>复制代码

  1. ...
  2. watch() {
  3. chokidar
  4. .watch(path.dirname(this.from), {
  5. ignoreInitial: true
  6. })
  7. .on("add", file => {
  8. if (path.extname(file) === this.extname) {
  9. console.log("add", file)
  10. }
  11. })
  12. .on("unlink", file => {
  13. if (path.extname(file) === this.extname) {
  14. console.log("unlink", file)
  15. }
  16. })
  17. }
  18. ...

现在符合from的文件的变动(添加和删除)都被监视了,但是总觉得

</>复制代码

  1. if (path.extname(file) === this.extname) {
  2. }

写了两遍,不开心

</>复制代码

  1. class SmartImport {
  2. constructor({ from }) {
  3. this.from = from
  4. this.extname = path.extname(from)
  5. this.checkExt = this.checkExt.bind(this)
  6. }
  7. watch() {
  8. const { from, checkExt } = this
  9. chokidar
  10. .watch(path.dirname(from), {
  11. ignoreInitial: true
  12. })
  13. .on(
  14. "add",
  15. checkExt(file => {
  16. console.log("add", file)
  17. })
  18. )
  19. .on(
  20. "unlink",
  21. checkExt(file => {
  22. console.log("unlink", file)
  23. })
  24. )
  25. }
  26. checkExt(cb) {
  27. return file => {
  28. if (path.extname(file) === this.extname) {
  29. cb(file)
  30. }
  31. }
  32. }
  33. }

新添加了函数checkExt(),它的参数和返回值都是函数,只是添加了判断文件后缀名的逻辑。

高阶函数有木有!

函数式编程有木有!

另外就是注意通过this.checkExt = this.checkExt.bind(this),绑定this的指向。

文件的变动映射到数组中

定义一个数组保存匹配的文件,另外匹配文件的变动会触发doImport()事件

代码就变成了这样

</>复制代码

  1. class SmartImport {
  2. constructor({ from, ignored }) {
  3. this.from = from
  4. this.ignored = ignored
  5. this.extname = path.extname(from)
  6. this.modules = []
  7. }
  8. watch() {
  9. const { from, ignored, extname, modules } = this
  10. chokidar
  11. .watch(path.dirname(from), {
  12. ignoreInitial: true,
  13. ignored
  14. })
  15. .on(
  16. "add",
  17. this.checkExt(file => {
  18. console.log("add", file)
  19. modules.push(file)
  20. this.doImport()
  21. })
  22. )
  23. .on(
  24. "unlink",
  25. this.checkExt(file => {
  26. console.log("unlink", file)
  27. _.remove(modules, p => p === file)
  28. this.doImport()
  29. })
  30. )
  31. }
  32. checkExt(cb) {
  33. const { extname } = this
  34. return file => {
  35. if (path.extname(file) === extname) {
  36. cb(file)
  37. }
  38. }
  39. }
  40. doImport() {
  41. console.log("doImport...")
  42. console.log(this.modules)
  43. }
  44. }

注意,我又把this.checkExt = this.checkExt.bind(this)给删了,还是直接通过this.checkExt()调用方便,虽然代码看起来凌乱了。

另外就是把this.doImport()又写了两遍。嗯,思考一下。其实modules变化,就应该触发doImport()

发布-订阅模式有木有

所以添加了个类ModuleEvent

</>复制代码

  1. class ModuleEvent {
  2. constructor() {
  3. this.modules = []
  4. this.events = []
  5. }
  6. on(event) {
  7. this.events.push(event)
  8. }
  9. emit(type, val) {
  10. if (type === "push") {
  11. this.modules[type](val)
  12. } else {
  13. _.remove(this.modules, p => p === val)
  14. }
  15. for (let i = 0; i < this.events.length; i++) {
  16. this.events[i].apply(this, [type, this.modules])
  17. }
  18. }
  19. }

同时修改类SmartImport

</>复制代码

  1. class SmartImport {
  2. constructor({ from, ignored }) {
  3. this.from = from
  4. this.ignored = ignored
  5. this.extname = path.extname(from)
  6. this.moduleEvent = new ModuleEvent()
  7. }
  8. init() {
  9. this.moduleEvent.on((type, modules) => {
  10. this.doImport(type, modules)
  11. })
  12. this.watch()
  13. }
  14. watch() {
  15. const { from, ignored, extname, modules } = this
  16. chokidar
  17. .watch(path.dirname(from), {
  18. ignoreInitial: true,
  19. ignored
  20. })
  21. .on(
  22. "add",
  23. this.checkExt(file => {
  24. console.log("add", file)
  25. this.moduleEvent.emit("push", file)
  26. })
  27. )
  28. .on(
  29. "unlink",
  30. this.checkExt(file => {
  31. console.log("unlink", file)
  32. this.moduleEvent.emit("remove", file)
  33. })
  34. )
  35. }
  36. checkExt(cb) {
  37. const { extname } = this
  38. return file => {
  39. if (path.extname(file) === extname) {
  40. cb(file)
  41. }
  42. }
  43. }
  44. doImport(type, modules) {
  45. console.log(`type: ${type}`)
  46. console.log(modules)
  47. }
  48. }
  49. let smartImport = new SmartImport(config)
  50. smartImport.init()

终于理解了很多库中on方法的原理有木有!对象中有个events,专门存这些回调函数有木有

另外我们观察chokidar.on(eventType, cb),对比自己的moduleEvent.on(cb)。想想也是,也许我只想监听特定的事件呢

修改ModuleEvent

</>复制代码

  1. class ModuleEvent {
  2. constructor({ from, ignored }) {
  3. this.modules = glob.sync(from, {
  4. ignore: ignored
  5. })
  6. this.events = {}
  7. }
  8. on(type, cb) {
  9. if (!this.events[type]) {
  10. this.events[type] = []
  11. }
  12. this.events[type].push(cb)
  13. }
  14. emit(type, val) {
  15. if (type === "push") {
  16. this.modules[type](val)
  17. } else {
  18. _.remove(this.modules, p => p === val)
  19. }
  20. for (let i = 0; i < this.events[type].length; i++) {
  21. this.events[type][i].apply(this, [this.modules])
  22. }
  23. }
  24. }

后来觉得这个套路挺常见,将其抽象出来,最后形成代码如下

</>复制代码

  1. #!/usr/bin/env node
  2. const fs = require("fs")
  3. const path = require("path")
  4. const glob = require("glob")
  5. const chokidar = require("chokidar")
  6. const _ = require("lodash")
  7. const config = JSON.parse(fs.readFileSync("smart-import.json"))
  8. const CustomEvent = (() => {
  9. let events = {}
  10. let on = (type, cb) => {
  11. if (!events[type]) {
  12. events[type] = []
  13. }
  14. events[type].push(cb)
  15. }
  16. let emit = (type, data) => {
  17. for (let i = 0; i < events[type].length; i++) {
  18. events[type][i].apply(this, [data])
  19. }
  20. }
  21. return {
  22. on,
  23. emit
  24. }
  25. })()
  26. class SmartImport {
  27. constructor({ from, ignored }) {
  28. this.from = from
  29. this.ignored = ignored
  30. this.extname = path.extname(from)
  31. this.modules = glob.sync(from, {
  32. ignore: ignored
  33. })
  34. }
  35. init() {
  36. CustomEvent.on("push", m => {
  37. console.log("Do pushing")
  38. this.modules.push(m)
  39. })
  40. CustomEvent.on("remove", m => {
  41. console.log("Do removing")
  42. _.remove(this.modules, p => p === m)
  43. })
  44. this.watch()
  45. }
  46. watch() {
  47. const { from, ignored, extname, modules } = this
  48. chokidar
  49. .watch(path.dirname(from), {
  50. ignoreInitial: true,
  51. ignored
  52. })
  53. .on(
  54. "add",
  55. this.checkExt(file => {
  56. CustomEvent.emit("push", file)
  57. })
  58. )
  59. .on(
  60. "unlink",
  61. this.checkExt(file => {
  62. CustomEvent.emit("remove", file)
  63. })
  64. )
  65. }
  66. checkExt(cb) {
  67. const { extname } = this
  68. return file => {
  69. if (path.extname(file) === extname) {
  70. cb(file)
  71. }
  72. }
  73. }
  74. }
  75. let smartImport = new SmartImport(config)
  76. smartImport.init()
未完待续

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/92502.html

相关文章

  • 记第一次发布npm包经历,smart-import

    摘要:故事背景前情提要自动工具,前端打字员的自我救赎的功能根据配置文件,在目标文件中自动导入规定目录下自定义模块,并监听规定目录下文件的变动,自动更新尚在测试中的使用安装工具编写配置文件需要自动导入的模块的后缀名自动导入的模块的来源目 故事背景 前情提要:自动 Import 工具,前端打字员的自我救赎 github: smart-import smart-import 的功能 根据配置文件...

    Raaabbit 评论0 收藏0
  • 重构:一项常常被忽略的基本功

    摘要:无论如何,单元测试一直是一中非常重要却常常被忽视的技能。在实践中,重构的要求是很高的它需要有足够详尽的单元测试,需要有持续集成的环境,需要随时随地在小步伐地永远让代码处于可工作状态下去进行改善。 showImg(https://segmentfault.com/img/bVbttWF?w=1000&h=528); 五月初的时候朋友和我说《重构》出第 2 版了,我才兴冲冲地下单,花了一个...

    idealcn 评论0 收藏0
  • 重构改善既有的代码设计(重构原则)

    摘要:难以通过重构手法完成设计的改动先想像重构的情况。何时不该重构现有代码根本不能正常运作。现在,我可以修改这个子类而不必承担午一中影响另一处的风险。 重构:对软件内部结构的一种调整,目的是再不改变软件的可观察行为的前提下,提高其可理解性,降低其修改成本。 两顶帽子 添加新功能 添加新功能时不应该修改既有代码,只管添加新功能,通过测试重构 重构时你就不能再添加功能,只管改进程序结构,此时...

    XUI 评论0 收藏0
  • 重构-改善既有代码的设计(二) --重构原则

    摘要:改进代码设计的一个重要原则就是消除重复代码使软件更容易被理解优秀的代码能够让接收你代码的付出更少的学习成本。重构更容易找到重构能加深对代码的理解。可以重构的情况添加功能时可以重构。说明你没有发现代码的错误。需要重构复审代码时可以重构。 为何重构 重构不是银弹,但是帮助你达到以下几个目的 改进软件设计 不良的程序需要更多的代码。而代码越多,正确的修改就越困难。改进代码设计的一个重要原则就...

    myshell 评论0 收藏0
  • 重构-改善既有代码设计》读书笔记-重构

    摘要:重构改善既有代码设计动词使用一系列重构手法,在不改变软件可观察行为的前提下,调整其结构。修补错误时重构代码时重构怎么重构关于代码的重构技巧参考重构改善既有代码设计读书笔记代码篇个人博客 重构定义 名词 对软件内部结构的一种调整,目的是在不改变软件可观察行为的前提下,提高其可理解性,降低其修改成本。——《重构-改善既有代码设计》 动词 使用一系列重构手法,在不改变软件可观察行为的前提下,...

    ermaoL 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<