Table of Contents
背景
观察
源代码
示例代码
这种功能随手实现
问题
零碎代码管理成本
NPM 依赖变化的风险
思路
分析
场景
核心思路
效果
发散
零碎代码依赖
jdists 介绍
声明零碎代码
引入零碎代码
总结
收益
成本
结束语
参考资料
Home Web Front-end HTML Tutorial 用 jdists 处理零碎代码依赖_html/css_WEB-ITnose

用 jdists 处理零碎代码依赖_html/css_WEB-ITnose

Jun 24, 2016 am 11:22 AM

标签: jdists 零碎代码

作者:王集鹄 2016年3月23日

背景

这两天发生了一件在开源社区引起了不小的波澜的事:

一个开发者把自己的组件( left-pad )从 NPM 下架了,导致被依赖的其他组件(包括一些流行的工具,如: babel )无法安装。

看到这段 license 的日志,这事多半是早有预谋的。

当然我不是想要讨论这件事的是非,只是抛一个新的问题「如何管理零碎代码?」。

一些小小的代码片段:封装成组件有些浪费,配置文件都比代码多;不封装,到用的时候还得四处寻找复制粘贴。

比如这段格式化代码,功能非常简单,但也不想每次用都现敲代码。

function format(template, json) {  return template.replace(/#\{(.*?)\}/g, function(all, key) {    return json && (key in json) ? json[key] : "";  });}
Copy after login

所以有很多人造轮子的时候,也有很多人在造螺丝钉。怎么管理螺丝钉一样的零碎代码,这篇文章介绍一种方案,抛砖引玉。

观察

left-pad 组件并不复杂,有效代码也就十几行

源代码

function leftpad (str, len, ch) {  str = String(str);  var i = -1;  if (!ch && ch !== 0) ch = ' ';  len = len - str.length;  while (++i < len) {    str = ch + str;  }  return str;}
Copy after login

示例代码

leftpad = require('left-pad')leftpad('foo', 5)// => "  foo"leftpad('foobar', 6)// => "foobar"leftpad(1, 2, 0)// => "01"
Copy after login

这种功能随手实现

function leftpad2(str, len, ch) {  return new Array(    Math.max(0, len - String(str).length + 1)  ).join(ch === 0 ? 0 : (ch || ' ')) + str;}
Copy after login

问题

零碎代码管理成本

零碎代码虽然可以随手写出,但会牺牲稳定性和复用性。

而过多的零碎代码组件化也会导致新的问题 -- 依赖臃肿,下游依赖成本提高。

NPM 依赖变化的风险

组件开发者难顾及 NPM 较深依赖层级和依赖增量变化。

我们享受开源组件生态福利同时,也得面对这种组件依赖发生变化的风险。

思路

分析

一个项目的依赖简单分为两类:

*「运行依赖」发布(publish)后的依赖,在运行期中使用*「开发依赖」发布前的依赖,在开发期中使用

如: NPM package.json 声明

{  ...  "dependencies": { // 运行依赖类    ...  },  "devDependencies": { // 开发依赖类    ...  },  ...}
Copy after login

安装一个组件时其「运行依赖」都会被下载,包括嵌套「运行依赖」。而「开发依赖」则不会被下载。

通常「开发依赖」都是放一些开发工具,比如构建、测试、规范检查等。那么它只能放工具吗?

场景

不妨想象一种场景:「我的项目」依赖 animate.css 组件,但只用到其中一个文件 bounce.css 。

{  "name": "my-package",  ...  "dependencies": { // 运行依赖类    "animate.css": "^1.0.0"  },}
Copy after login

如果别的项目依赖「我的项目」,显然安装依赖的时候,逃离不了下载整个 animate.css 的命运。

于是我想到:把 animate.css 看作资源,只抽取 bounce.css 文件作为「我的项目」一部分一起发布。

实现也不复杂:构建时简单写一条复制命令。

{  "name": "my-package",  ...  "devDependencies": { // 运行依赖类    "animate.css": "^1.0.0"  },  "scripts": {    "dist": "cp node_modules/src/bounce.css vendor/bounce.css" // 构建复制  }  ...}
Copy after login

那么别的项目依赖「我的项目」就不用再下载完整的 animate.css ,妈妈再也不用担心我的磁盘满了。

核心思路

  • 项目资源按需打包发布,降低下游的依赖成本。
  • 「开发依赖」除了放工具也可以放资源包。

效果

  • 使用构建工具,可以降低零碎代码管理成本
  • 按需打包资源,可以避免依赖变化的风险

发散

依赖有三个形式:

  • [x] 依赖一个项目
  • [ ] 依赖一个项目的某几个文件
  • [ ] 依赖一个项目的某几个文件的某几个片段

通常大家都关注第一种形式,下文重点介绍第三种形式:零碎代码依赖

零碎代码依赖

造轮子和用轮子并不冲突,这是供需关系,共生走向繁荣。

现在已经很少见不需要构建过程项目,请大胆的使用构建工具,让开发期更自由自在。

jdists 介绍

jdists 是一款强大的代码块预处理工具

  • 支持代码块嵌套
  • 支持多种编程语言(类 HTML、类 C、类 Pascal、类 Python、类 Lua)
  • 支持自定义扩展

详情参考: jdists

声明零碎代码

jdists 使用一种类似 XML 标记的方式声明代码块。

如下代码,声明 tag 为 function 属性 name 为 encodeHTML 的代码片段 「来源 jstrs」

  /*<function name="encodeHTML">*/  var htmlEncodeDict = {    '"': 'quot',    '<': 'lt',    '>': 'gt',    '&': 'amp',    ' ': 'nbsp'  };  /**   * HTML编码   * @param {string} text 文本   '''</example>'''   */  function encodeHTML(text) {    return String(text).replace(/["<>& ]/g, function(all) {      return '&' + htmlEncodeDict[all] + ';';    });  }  /*</function>*/
Copy after login

引入零碎代码

引入时指定文件和依赖关系 「来源 jhtmls」

  • 构建前
  /*<jdists encoding="fndep" import="../node_modules/jstrs/jstrs.js"    depend="encodeHTML">*/  var jstrs = require('jstrs');  var encodeHTML = jstrs.encodeHTML;  /*</jdists>*/
Copy after login
  • 构建后
  /*<function name="encodeHTML">*/  var htmlEncodeDict = {    ...  };  ...  function encodeHTML(text) {    ...  }  /*</function>*/
Copy after login

截止我们已经完成第三种依赖形式的处理

  • [x] 依赖一个项目的某几个文件的某几个片段

总结

收益

  • 减少下游依赖成本,被依赖的项目按需加载
  • 控制力强,依赖管理可以控制在代码块粒度

成本

  • 学习成本,需掌握代码块标记工具
  • 使用成本,需声明代码块及相关配置

结束语

代码块粒度的按需加载是动态类型语言的痛点,部分代码的生命周期难以捕获。使用 jdists 管理碎片代码依赖,目前还是一个不错的选择。

参考资料

  • npmjs.org tells me that left-pad is not available (404 page) #4
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

See all articles