







为什么前端需要构建?
- 开发复杂化
- 框架去中心化
- 语言编译化
- 开发模块化
为什么Webpack?
- Vue-cli / React-starter / Angular-cli
- Code-splitting
- 天生的模块化
- ...
模块化开发
- JS 模块化
- CSS 模块化
JS 模块化
- 命名空间
- COMMONJS
- AMD/CMD/UMD
- ES 6 module
在很多年前,命名空间是考量一个人代码是否入门的一个基础问题,后来我们有了专门的前端模块化规范,从触角伸向服务端的 nodejs 开始,我们有了commonjs 规范,然后我们的社区为了在浏览器端也开始使用模块化方案,就开始有了 AMD, 国内由我们的淘宝的玉伯的seajs 提出了 CMD 规范

YUI 2 中大量使用了命名空间,在还没有模块化的世界里,通过命名空间,能极大缓解冲突。

YUI3 通过沙箱机制,解决了命名空间带来的问题。

- 1、1.0 -> 1.1.1
- 2、一个文件为一个模块
- 3、模块内的变量不能被访问到,只能通过exports方法暴露出的接口才能被外界访问到
- 4、通过require 同步加载模块


为了使得浏览器和 nodejs 一样具有模块化开发的特点,社区发明了AMD 规范,也就是Async Module Definition,在Commonjs 中,所有的模块是同步加载,服务端由于都是本地文件可以承受这样的一个加载开销,而我们的浏览器端呢?如果要求用户来承担这一个同步加载所有模块的开销,一定会影响到用户的浏览网页的速度。AMD 正是为了解决这一点而生。

第一幅图是AMD 规范中的定义一个模块,分别有三个参数,
第一个参数是模块名称,第二个是模块依赖,第三个是工厂函数。
第一个和第二个参数都可以省略
第二幅图是一个匿名模块的定义,省略第一个参数名,图中依赖了abcdef 6个模块,在AMD规范中,当引入A,B,C,D,E,F的时候, 这些模块内部的内容已经被浏览器执行了。即便还没有被使用他的模块真正用到。这个就是AMD 的依赖前置

- 1、CMD 全称是 common module definition
- 2、在CMD 规范中,一个文件为一个模块
- 3、也同样是通过define 和 require 来定义和加载一个模块
- 4、代表作是 seajs
- 5、宗旨是尽可能的懒执行
- 6、规范的地址








尽管之前我们有遇到过这么多类型的模块化规范,但是在webpack 中推荐使用的是ES6 module,所以在如今的开发过程中,我们可以选择ES6 模块规范深入了解掌握,就可以满足我们的使用。由于webpack 基于 nodejs 的工具,在 nodejs 中是采用的模块化规范是 CommonJS ,所以我们除去ES6 外再掌握 CommonJS 就可以了。所以老师推荐的是掌握 Commonjs 和 ES6 modules,而对于AMD & CMD 大家了解就可以了。


OOCSS是object-oriented CSS的缩写. 主要有两个意思:
结构和设计分离
容器和内容分离
使用这种结构, 开发人员获得可以在不同地方使用的CSS类.
通常这时候总是会有两个消息(一个好消息和一个不好的消息):
好消息: 通过复用来减少代码量(DRY原则)
不好的消息: 维护非常困难(复杂). 当你修改某一个具体的元素的样式的时候, 大部分情况下, 除了修改CSS本身(因为多数的CSS类是通用的), 你还不得不添加更多的标记类(markup).

SMACSS是可扩展和模块化结构CSS的简称. 该方法的主要目标是减少代码量并简化代码维护.
Jonathan Snook把它归纳为5个部分:
基本规则(Base rules): 这些是网站的主要元素的样式, 如body, input, button, ul, ol等. 在这一步中, 我们主要使用HTML标签和属性选择器, 在特殊情况下, 使用CSS类(如: 如果您有JavaScript-Style选择);
布局规则(Layout rules): 主要是些全局元素, 顶部, 页脚, 边栏等模块的大小. Jonathan建议使用ID选择器, 因为这些模块不太可能在同一个页面上出现多次. 然而, 本文作者认为这是个很不好的习惯(每当ID出现在样式文中, 感觉世界顿时变得灰暗, 有一股莫名的哀伤).
模块规则(Modules rules): 模块(类似于卡片布局)可以在一个页面中使用多次. 对于模块CSS类, 不建议使用ID和tag选择器(这是为了方便重用以及上下文独立).
状态规则(State rules): 在这一步中, 规定了模块的各种状态以及网站的基础部分. 这是唯一允许使用"!important"的地方.
主题规则(Theme rules): 设计您可能需要更换的样式.

Atomic CSS是CSS架构的一种方法, 它的好处是写出基于视觉功能的小的, 单用途CSS类.
使用Atomic CSS, 为每个可重用的属性创建单独的CSS类. 例如, margin-top: 1px; 就可以创建一个类似于mt-1的CSS类, 或者width: 200px; 对应的CSS类为w-200.
这种样式允许您通过重用声明来最大程度地减少您的CSS代码数量, 并且也能很轻松的更改模块, 例如, 更改以技术任务时.
然而, 这种方法有很大的缺点:
CSS类名是属性名称的描述, 而不是元素的自然语义. 这种想象很容易使人在开发过程中变得迷茫. 开发本身也十分容易复杂化.
直接在HTML中进行显示设置.





Webpack 中使用css modules非常简单是需要通过使用css-loader 开启 module 这个参数就可以了





















网友评论