Showing preview only (2,485K chars total). Download the full file or copy to clipboard to get everything.
Repository: xunuoi/gulpman
Branch: master
Commit: d12eb0fa1c71
Files: 149
Total size: 2.3 MB
Directory structure:
gitextract_0od9uxhv/
├── .gitignore
├── LICENSE
├── README.md
├── README_zh-CN.md
├── assets/
│ └── .babelrc
├── index.js
├── karma/
│ └── karma.conf.js
├── lib/
│ ├── assetsPathParser.js
│ ├── base64.js
│ ├── cdnProxy.js
│ ├── gmutil.js
│ ├── gulp-usemin/
│ │ ├── .npmignore
│ │ ├── .travis.yml
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── gulpfile.js
│ │ ├── index.js
│ │ ├── lib/
│ │ │ ├── blocksBuilder.js
│ │ │ ├── htmlBuilder.js
│ │ │ └── pipeline.js
│ │ ├── package.json
│ │ └── test/
│ │ ├── expected/
│ │ │ ├── app.js
│ │ │ ├── array-js-attributes.html
│ │ │ ├── build-remove-no-trailing-whitespace.html
│ │ │ ├── complex-path.html
│ │ │ ├── complex.html
│ │ │ ├── conditional-complex.html
│ │ │ ├── conditional-css.html
│ │ │ ├── conditional-inline-css.html
│ │ │ ├── conditional-inline-js.html
│ │ │ ├── conditional-js.html
│ │ │ ├── data/
│ │ │ │ ├── css/
│ │ │ │ │ ├── min-style.css
│ │ │ │ │ └── style.css
│ │ │ │ └── js/
│ │ │ │ ├── app.js
│ │ │ │ ├── app_min_concat.js
│ │ │ │ └── min-app.js
│ │ │ ├── glob-inline-css.html
│ │ │ ├── glob-inline-js.html
│ │ │ ├── many-blocks-removal.html
│ │ │ ├── min-app.js
│ │ │ ├── min-complex-path.html
│ │ │ ├── min-complex.html
│ │ │ ├── min-css-with-media-query.html
│ │ │ ├── min-html-simple-css.html
│ │ │ ├── min-html-simple-js.html
│ │ │ ├── min-html-simple-removal.html
│ │ │ ├── min-paths-with-querystring.html
│ │ │ ├── min-simple-css-path.html
│ │ │ ├── min-simple-css.html
│ │ │ ├── min-simple-js-path.html
│ │ │ ├── min-simple-js.html
│ │ │ ├── min-style.css
│ │ │ ├── multiple-alternative-paths.html
│ │ │ ├── multiple-files.html
│ │ │ ├── paths-with-querystring.html
│ │ │ ├── simple-css-path.html
│ │ │ ├── simple-css.html
│ │ │ ├── simple-inline-css.html
│ │ │ ├── simple-inline-js.html
│ │ │ ├── simple-js-path.html
│ │ │ ├── simple-js-removal.html
│ │ │ ├── simple-js.html
│ │ │ ├── single-quotes-css.html
│ │ │ ├── single-quotes-inline-css.html
│ │ │ ├── single-quotes-inline-js.html
│ │ │ ├── single-quotes-js.html
│ │ │ ├── style.css
│ │ │ └── subfolder/
│ │ │ ├── app.js
│ │ │ └── index.html
│ │ ├── fixtures/
│ │ │ ├── alternative/
│ │ │ │ └── js/
│ │ │ │ └── util.js
│ │ │ ├── array-js-attributes.html
│ │ │ ├── async-less.html
│ │ │ ├── build-remove-no-trailing-whitespace.html
│ │ │ ├── comment-js.html
│ │ │ ├── complex-path.html
│ │ │ ├── complex.html
│ │ │ ├── conditional-complex.html
│ │ │ ├── conditional-css.html
│ │ │ ├── conditional-inline-css.html
│ │ │ ├── conditional-inline-js.html
│ │ │ ├── conditional-js.html
│ │ │ ├── css/
│ │ │ │ ├── clear.css
│ │ │ │ └── main.css
│ │ │ ├── css-with-media-query-error.html
│ │ │ ├── css-with-media-query.html
│ │ │ ├── glob-css.html
│ │ │ ├── glob-inline-css.html
│ │ │ ├── glob-inline-js.html
│ │ │ ├── glob-js.html
│ │ │ ├── js/
│ │ │ │ ├── lib.js
│ │ │ │ └── main.js
│ │ │ ├── js2/
│ │ │ │ ├── lib2.js
│ │ │ │ └── main2.js
│ │ │ ├── less/
│ │ │ │ ├── clear.less
│ │ │ │ └── main.less
│ │ │ ├── many-blocks-removal.html
│ │ │ ├── many-blocks.html
│ │ │ ├── min-html-simple-css.html
│ │ │ ├── min-html-simple-js.html
│ │ │ ├── min-html-simple-removal.html
│ │ │ ├── multiple-alternative-paths-inline.html
│ │ │ ├── multiple-alternative-paths.html
│ │ │ ├── multiple-files.html
│ │ │ ├── paths-with-querystring.html
│ │ │ ├── simple-css-alternate-path.html
│ │ │ ├── simple-css-path.html
│ │ │ ├── simple-css.html
│ │ │ ├── simple-inline-css.html
│ │ │ ├── simple-inline-js.html
│ │ │ ├── simple-js-alternate-path.html
│ │ │ ├── simple-js-path.html
│ │ │ ├── simple-js-removal.html
│ │ │ ├── simple-js.html
│ │ │ ├── single-quotes-css.html
│ │ │ ├── single-quotes-inline-css.html
│ │ │ ├── single-quotes-inline-js.html
│ │ │ ├── single-quotes-js.html
│ │ │ └── subfolder/
│ │ │ ├── index.html
│ │ │ └── script.js
│ │ └── main.js
│ ├── htmlPathParser.js
│ ├── iconFonter.js
│ ├── inline.js
│ ├── revReplace.js
│ ├── spriter/
│ │ ├── README.md
│ │ ├── index.js
│ │ ├── lib/
│ │ │ ├── get-background-image-declarations.js
│ │ │ ├── get-meta-info-for-declaration.js
│ │ │ ├── map-over-styles-and-transform-background-image-declarations.js
│ │ │ ├── spriter-util.js
│ │ │ ├── transform-file-with-sprite-sheet-data.js
│ │ │ └── transform-map.js
│ │ └── package.json
│ └── store.js
├── meta/
│ └── home/
│ ├── index.html
│ ├── main.es6
│ └── main.scss
├── package.json
├── presetlib/
│ ├── jquery.js
│ ├── react-0.14.6/
│ │ └── build/
│ │ ├── react-dom-server.js
│ │ ├── react-dom.js
│ │ ├── react-with-addons.js
│ │ └── react.js
│ └── react.js
├── scripts/
│ ├── gulp/
│ │ └── gulpfile.js
│ ├── install.sh
│ ├── package.json
│ └── preinstall.sh
└── test.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
.npm
.bin
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright Lucas, Inc. and other contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
[](http://karat.cc/article/56a351c3e48d2d05682aa0ac/)
-----
[](http://badge.fury.io/js/gulpman)
<img src="https://raw.githubusercontent.com/xunuoi/gulpman/master/assets/build.png?style=flat-square" width="90" alt="Build status" />
# gulpman
[浏览简体中文文档](https://github.com/xunuoi/gulpman/blob/master/README_zh-CN.md)
- Create Modular Front-End Build System, organize the source by module, using relative path, `html/js/css/img/fonts/tpl` are in one same folder, like Baidu `FIS`. Good concept for FE source management / development.
- Concept Introduction: [前端工程之模块化](http://fex.baidu.com/blog/2014/03/fis-module/)
- Component Oriented Solution, based on `gulp`. More simple, flexible, expandable and stable. Everyone know gulp can do secondary development.
- Support `base64` image in `html/CSS`
- Support `JS/CSS` inlnied in html
- Support `require('main.css')`, require css file in js
- Intergrated with `spritesmith`, support auto sprite img
- Intergrated with `icon-font`, support SVG 2 Iconfont.
- Intergrated with `usemin`,support complex combo/package.
- Supoort FE Tpl embed function, the `.tpl` file will packaged into js file,support async js loading.
- Intergrated with `SCSS|ES6|ReactJS|Vuejs|Babel|Browserify|cssnano|uglify|imagmein` and other plugins,One-Stop Solution Service, very Simple and Strong
- High scalability, compatiable with almost `gulp` plugins, you can use them in `gulpman`. For example, you can put `browser-sync` in your gulpman build system
- Intergrated with `karma` framework,support `babel/es6` unit test and coverage result.
## Introduction
- Support Mac、Linux
- No full test under Windows. You can install `gulp`、`gulp-sass` manually
- Required Node >= 4.0.0
## Install
- `npm install gulpman --save-dev`
- Run `gulp gm:install` to finish the setup
- *If in China, please use `cnpm` to install it: `cnpm install gulpman --save-dev`
#### Note
* If `gulp-sass` install failed, please run `cnpm install gulp-sass gulp-imagemin` by manual to fix that.
* If error happened in npm install,such as `/usr/local/lib/node_modules` permission error, fix this by `sudo chown -R "$(whoami)"`+`Path`
* `sudo npm install` is not recommended
* The imagemin-pngquant module need`libpng-devel`,if in Linux, please run `yum install libpng-devel` at first
* If install failed, check the `npm-debug.log` to see if there are some `ENOMEM`errors
## Config
### 0. Support Auto Mode, no Config
* You can skip `Config`, and directly jump to `Usage`
### 1. Config gulpfile.js:
- require the `gulpman` in your gulpfile.js,then it will load `gm:publish`, `gm:develop` into gulp tasks.
- `gulp gm:publish` or `gulp gm:develop` in terminal then it will work
```Javascript
/**
* Gulpfile.js
*/
var gulp = require('gulp'),
gman = require('gulpman')
// your other tasks ...
// xxx ...
/**
* config gulpman ======================
* Use config API
* assets path, CDN, URL prefix
*/
gman.config({
// whether use absolute path, default `true`
'is_absolute': true,
// cdn prefix support[string|array|function]arguments
'cdn_prefix': '',
// url prefix, defautl `/static`. This involves the server config ,such as the static path of nginx
'url_prefix': '/static',
/** use spritesmith for css-img sprite
* Based on Spritesmith: https://github.com/Ensighten/spritesmith
* Automatecially generate Sprite Image & CSS
**/
//'spritesmith': { },
/** usemin config **/
// 'usemin': {}
// The COMPONENTS directory
'components': 'components',
// For development assets and templates folder, related to Server Config
'runtime_views': 'views',
'dist_views': 'views_dist',
// For production assets and templates folder, related to Server Config
'runtime_assets': 'assets',
'dist_assets': 'assets_dist',
// The js library dir, set as a global module. Also you can set as `bower_components`
'lib': 'lib',
// You can add one customer global directory, so you can require module name directly, like: `require ('xxx')`. The xxx is in this directory
'global': 'common'
})
```
### 2. How to config CDN better
* `cdn_prefix` support String, Array, Function
* if argument is array, the CDN will be an random value
* if argument is function,it would input one argument, `mediaFile`
```Javascript
'cdn_prefix': function (fileName) {
console.log(fileName)
var c_list = [
'http://s0.com',
'http://s1.com',
'http://s2.com',
'http://s3.com',
'http://s4.com'
]
// You can customized your strategy
if(hostFile.match(/\.html$/gm)){
return c_list[0]
}else {
return c_list[1]
}
},
```
### 3. About `is_absolute`
* `is_absolute` is the dist path of source in html. default true. the dist path is like `/static/home/main.js`
* [*]Need consistent config with Server, like nginx, apache
* If no local server, you can set is_absolute as false, use relative path. Like `../../assets/static/home/main.js`
### 4. gulpman directory
* Use gulpman to arrange your directory as component,The root component dir can be`./components`(default). If you have one component named foo, then `./components/foo`,all related assets such as `html|js|css|fonts|image` should be put in `foo` folder.
* This solution for assets can be high efficiency and easy to maintain.
* `gm:develop` to start `develop` mode, the `views` dir and `assets` dir can be generated automatically
* `gm:publish` to publish assets in production env. The `views_dist` and `assets_dist` can generated.
### 5. What is global directory
- For `Browserify` packing, the js module in `global dir` can be directly `require` or `import` in es6/js code
- In `gulpman.config`, the `lib`和`global` are global directory. Take an example:
* In `components/lib` directory, you have one module `foo.js`,then it is `components/lib/foo.js`. So when you use foo in your es6 file, you can use it like: `import foo from 'foo'`, no need write as `import foo from '../lib/foo'`
- similarly, `global` option can set your dir as global module dir. You can set `bower` dir as your `lib` dir.
- Please make no conficts in your global dir
### 6. Support for complex and multi level directory in config
* Such as:
```Javascript
gulpman.config({
'is_absolute': false,
'components': 'components/cc',
'runtime_views': 'runtime_views/rv',
'dist_views': 'dist_views/dv/dv',
'dist_assets': 'dist_assets/da',
'runtime_assets': 'runtime_assets/ra/ra',
})
```
## Usage
### 1. CLI run Task:
```Shell
# Create components directory and add one demo
# init components dir and a html demo
gulp gm:init
# develop and watch mode,watchings files changes and update files
gulp gm:develop
# Build and Watch one special component, other files are not compiled
gulp gm:develop -c component_name1,component_name2,component_name3...
# publish assets in production env
gulp gm:publish
# publish command support `-a`和`-v` parameters to set output assets/views path.
gulp gm:publish -v your_views_dist -a your_assets_dist
# clean dist files
gulp gm:clean
# clean dist files, including subfolders
gulp gm:clean-deep
# Generate one developing assets/views files, but not in watching mode
# compile for develop, not watch
gulp gm:compile
```
### 2. Watch one special component in development
* When the project become huge, if we watch all components assets, it will be slow and low efficiency, so we can only watch special component to get better performance
* Fox example, if we want watch the `home` component:
```Shell
# this will only build and watch `components/home` components
gulp gm:develop -c home
```
### 3. Use `React` in gulpman
* Install React: `npm install react react-dom`
* Use React in ES6:
```Javascript
import React from 'react';
import ReactDOM from 'react-dom';
// xxx
```
### 4. Use `tpl` file in js|es6|jsx
* Support `.tpl` file, it will be packaged in dist js files.
* Usage: `import dialogTpl from './dialog.tpl'` or `var dialogTpl = require('./dialog.tpl')`
### 5. Usge base64 img in HTML/CSS
* Just add `?_gm_inline` in assets src path in html/css
* The `base64` code will be inlined in html/css
##### html
```html
<p class="play">
<img width="480" alt="Karat 克拉" src="./img/testb64.png?_gm_inline" />
</p>
```
##### CSS/SCSS
```css
.test {
background: url(./img/testb64.png?_gm_inline) no-repeat;
}
```
### 6. Use inlined CSS/JS in html by querystring
* Like base64, just add `?_gm_inline` in url path
```html
<script src="./plugin.js?_gm_inline" type="text/javascript"></script>
<link href="./dialog.css?_gm_inline" rel="stylesheet" type="text/css" >
```
* The inlined sources will be auto updated when source files changed.
### 7. Use Sprite img in css
* Enable Sprite by `gulpman.config({ enableCSSSprite: true })`, the default is false.
* Based on spritesmith, you can transport usemin opts in gulpman.config.
* More detail about Spritesmith: [https://github.com/Ensighten/spritesmith](https://github.com/Ensighten/spritesmith)
* Usage: In scss file, just add `?_gm_sprite` to img url
```css
.demo {
background: url(./img/abc.png?_gm_sprite) no-repeat;
/* other style you can set ...*/
width: 50px;
height: 50px;
}
```
### 8. Use Usemin
* You can tranport usemin opts in gulpman.config
* More detail about usemin: [https://github.com/zont/gulp-usemin](https://github.com/zont/gulp-usemin)
* Uage: just add usemin build comments in html. Support `js`|`css`|`inlinejs`|`inlinecss` syntax
* Note: Just write relative path in usemin build comment. Then gulpman can calculate absolute path for assets.
* If you don't write output path, the gulpman will combo one new ouput file name automatically.
```html
<!-- build:css ./home.css -->
<link rel="stylesheet" type="text/css" href="./main.css">
<link rel="stylesheet" type="text/css" href="./fff.css">
<!-- endbuild -->
<!-- build:js ../lib/base_lib.js -->
<script type="text/javascript" src="../lib/jquery.js"></script>
<script type="text/javascript" src="../lib/react.js"></script>
<!-- endbuild -->
```
### 9. Use js tpl template
* Put the `.tpl` files in your component, and use `require` or `import` in ES6, then the tpl files will be packaged in js files.
* All tpl will be convertd to text string into js files.
* Base64 img and CSS/JS Embed are supported in Tpl
- import tpl in es6
```js
import dialogTpl from './dialog.tpl'
```
- require
```js
var dialogTpl = require('./dialog.tpl')
```
### 10. import css files into js/html
- Just import the css, then the gulpman will attach it on page automatically.
```js
import from './style.css';
```
```js
require('./style.css');
```
### 11. Use iconfont convert svg to fontface
* Convert SVG to icon-font, use `@font-face` in css
* Run `gulp gm:iconfont:install` before first running
* Put the svg files in `components/iconfonts/source` directory, then run `gulp gm:iconfont` to begin start convert
* The icon-font and css will generated in `iconfonts/gmicon` folder
### 12. Support LAB.js to load async js
* Add LAB.js in your project
* Use LAB API to load js, use `relative path`
* Example: `$LAB.script("../testload/test.js").wait(()=>{console.log('test loaded')})`
### 13. Require CSS in JS
* Require css files in your es6/js files
* The CSS contents will be packaged into js files, and automatically injected to html when page opend. Using style tag
* Should keep the .css extname
* Example: `require('./style.css')` or `import style from './style.css'`
### 14. Use karma for Unit Test
* Run `gulp gm:karma:install` before first running, it will install dependencies and generate `karma.conf.js`.
* In your one component folder, create one folder named `spec`, then put your spec es6 files in the `spec` folder, the file extname must be `.es6`
* Run `gulp gm:karma:start` in CLI to start Karma Unit Test, you can view the coverage result in `coverage` foloder
* Set one special spec folder、browsers and other karma options, you can set them in `karma.conf.js`
### Tutorial
[Tutorial Link](http://karat.cc/article/56a351c3e48d2d05682aa0ac "karat.cc")
### License
MIT
================================================
FILE: README_zh-CN.md
================================================
[](http://karat.cc/article/56a351c3e48d2d05682aa0ac/)
-----
[](http://badge.fury.io/js/gulpman)
<img src="https://raw.githubusercontent.com/xunuoi/gulpman/master/assets/build.png?style=flat-square" width="90" alt="Build status" />
# gulpman
[English Document](https://github.com/xunuoi/gulpman/blob/master/README.md)
- 支持资源模块化组织方式,通过相对路径运算,像百度的FIS一样,可以将`js/css/img/fonts/tpl`按照功能单位组织到同一个目录中,不再分散维护。Gulpman运行时会自动分发各种资源到正确目录。
- 概念介绍: [前端工程之模块化](http://fex.baidu.com/blog/2014/03/fis-module/)
- 基于`gulp`的前端组件化、模块化解决方案,更简单、灵活、可控性高,会gulp就会定制自己的方案
- 支持图片`base64`方式嵌入到`html/CSS`
- 支持`JS/CSS`内联方式嵌入html文件
- 整合`spritesmith`,简单生成sprite雪碧图
- 整合`icon-font`转换,支持svg转换
- 整合`usemin`,构建合并更加灵活强大
- 支持前端js模板嵌入,`tpl`格式的直接构建打包到最终js文件,支持异步加载js
- 集成`SCSS|ES6|ReactJS|Babel|Browserify|cssnano|uglify|imagmein`等常用组件,做到一站式自动化解决方案,同时清晰、可控,定制、修改简单
- 扩展性高,`gulp`现有的插件都可以拼装、加入到`gulpman`中使用,你可以自己根据实际情况组合、修改,比如可以轻松整合`browser-sync`到构建系统中。
- 整合`karma`单元测试框架,适配`babel和es6`的代码单元测试和`coverage`
## 说明
- 支持Mac、Linux环境下安装、使用
- Windows环境未做完整安装测试,由于安装脚本使用到shell,windows不支持shell,执行完`npm install gulpman --save-dev`后,可能需要手动安装`gulp`、`gulp-sass`模块
- 如果手动安装`gulp-sass`,建议使用淘宝的`cnpm`来完成,避免国内网络导致`npm`安装失败
- Node版本需要不低于4.0.0
## 安装
- `npm install gulpman --save-dev`
- 如果在中国,请使用cnpm安装:`cnpm install gulpman --save-dev`
- 完成后请运行 `gulp gm:install` 来完成安装
#### 注:
* 如果安装过程中提示 `gulp-sass` 安装失败, 运行 `cnpm install gulp-sass gulp-imagemin` 来修复。
* 安装中若npm报出目录权限导致的error,比如涉及到`/usr/local/lib/node_modules`权限的报错,请请检查其权限是否正常并用chown来修复,将拥有者修改为当前登录用户即可。
* 可以使用 `sudo chown -R "$(whoami)"`+`路径`来修复
* 不要使用`sudo npm install`来手工安装因为权限问题而失败的模块。请修改权限后,再用`npm install`来安装即可
* 如果你本地node和npm的安装和权限正常,那gulpman的安装过程应该都是顺利和成功的。
* 图片压缩模块imagemin-pngquant需要依赖`libpng-devel`,如果是Linux环境,建议先运行`yum install libpng-devel`来确保安装
* 安装过程中无故退出,请查看`npm-debug.log`,检查是否是内存不足`ENOMEM`导致。
## 配置
### 0. 支持自动默认模式,无需配置即使用
* 可直接跳过`Config 配置`处的说明,直接去看后面的`Usage 使用`内容
### 1. 配置 gulpfile.js:
- 只需要require gulpman模块,就会自动加载`gm:publish`, `gm:develop`(开发监视模式)等task到环境中
- 使用时在命令行中直接输入`gulp gm:publish`即可执行gulpman预置的任务
```Javascript
/**
* Gulpfile.js
*/
var gulp = require('gulp'),
gman = require('gulpman')
// your other tasks ...你的其他task
// xxx ...
/**
* 配置gulpman ======================
* Use config API
* 设置路径、CDN、资源URL前缀等,API简单
*/
gman.config({
// 是否使用绝对路径,默认值true, 推荐使用,方便服务器配置。比如`/static/home/main.js`这种风格。
// 如果无服务端情况下,本地调试,可以设置is_absolute为false, 那么会是类似`../../assets/static/home/main.js`这种风格
'is_absolute': true,
// cdn prefix 配置CDN, 支持[字符串|数组|函数] 3中传参方式
'cdn_prefix': '',
// 配置资源URL前缀,建议类似 /static这种
// usually set as /static, this involves the server config ,such as the static path of nginx
'url_prefix': '/static',
/** use spritesmith for css-img sprite
* 基于spritesmith实现, 详细参见https://github.com/Ensighten/spritesmith
* 传递自动生成雪碧图的spritesmit的options
**/
//'spritesmith': { },保持默认即可
/** usemin config 配置usemin,保持默认即可 **/
// 'usemin': {}
// 模块COMPONENTS目录,同一个模块的html和资源文件在一起。默认 'components'即可
'components': 'components',
// develop和publish下的views目录,跟服务端框架的views目录配置一致,比如express
'runtime_views': 'views',
'dist_views': 'views_dist',
// develop和publish下的assets静态目录,跟服务器配置有关,比如nginx的static目录指向,请保持与服务器设定一致。支持多级路径设定,比如assets/public
'runtime_assets': 'assets',
'dist_assets': 'assets_dist',
// 第三方JS类库、模块的目录,推荐设置为`lib`或`bower_components`(这样bower可以直接安装到这个目录)
// 这个目录默认打包时为全局模块目录,可以直接`import xxx from 'xxx'`,而不用加相对路径
// the js library dir, set as a global module. Also you can set as bower_components
'lib': 'lib',
// 可以添加一个自定的全局模块目录,该目录下的js模块,也作为全局模块来require,不需要相对路径。
// the global module dir
'global': 'common'
})
```
### 2. 如何更好的配置CDN
* `cdn_prefix`支持 字符串、数组、函数
* 如果传入数组,那么按照随机来分配
* 如果传入函数,函数会获1个参数,`mediaFile`, 就是当前被css或html中引用到的资源文件名,可以根据文件名做cdn分配
```Javascript
'cdn_prefix': function (fileName) {
console.log(fileName)
var c_list = [
'http://s0.com',
'http://s1.com',
'http://s2.com',
'http://s3.com',
'http://s4.com'
]
// 你自可以自实现分配策略
if(hostFile.match(/\.html$/gm)){
return c_list[0]
}else {
return c_list[1]
}
},
```
### 3. 对于`is_absolute`的说明
* `is_absolute`是指输出的html文件中的资源src/url,否使用绝对路径,默认值true,即启用绝对目录。
* [常用]当使用服务器配置静态目录的情况下,推荐使用绝对目录。比如配合nginx,指定某个目录为静态资源目录。类似`/static/home/main.js`这种风格。
* 如果无服务端情况下,有需要本地调试,推荐设置is_absolute为false, 即启用相对路径。类似`../../assets/static/home/main.js`这种风格。
* 当is_absolute为false(启用相对路径)的情况下,直接打开输出的views目录下的html文件,就可以正常浏览、运行、调试
### 4. gulpman目录说明
* 使用gulpman按照模块划分后,模块根目录可以是`./components`(默认,可配置),如果你有个模块是foo,那么应该有如下目录:`./components/foo`,然后跟foo模块相关的`html|js|css|fonts|image`等资源文件都放到`foo`下,这个结构下,做开发时非常清晰、高效,便于模块组织、资源定位等。
* 通过`gm:develop`命令进入`develop`开发模式后,会自动生成模板`views`目录,和静态资源`assets`目录。
* 通过`gm:publish`命令来构建发布资源,会自动生成生产环境下的模板目录`views_dist`,和静态资源目录`assets_dist`。
### 5. 什么是全局模块目录:
- 对应`Browserify`的打包功能,`全局目录`是指可以直接`require`或者`import`其下的js模块的目录
- `gulpman.config`的配置中,`lib`和`global`都是JS的全局模块目录。举个例子说明:
* 你的`components/lib`目录下有一个模块 `foo.js`,就是: `components/lib/foo.js`,那么你在你的es6文件中,就可以这样使用:`import foo from 'foo'`,不需要写成 `import foo from '../lib/foo'`
- 同理`global`那个配置也是这样的,推荐将lib目录设置成跟`bower`一致的,全部来存放第三方类库,而`global`设置的目录,比如叫`common`,可以存放自己的`公用模块`。这样开发会更加灵活、方便。
- 注意全局模块不要有同名冲突。
### 6. 支持复杂目录和多级目录设定
* 比如下面这种复杂路径:
```Javascript
gulpman.config({
'is_absolute': false,
'components': 'components/cc',
'runtime_views': 'runtime_views/rv',
'dist_views': 'dist_views/dv/dv',
'dist_assets': 'dist_assets/da',
'runtime_assets': 'runtime_assets/ra/ra',
})
```
## Usage 使用
### 1. CLI 执行Task:
```Shell
# 初始化目录,建立components目录并添加一份html的demo文件
# init components dir and a html demo
gulp gm:init
# develop and watch 开发模式,监视相关文件变动,增量更新
gulp gm:develop
# 指定编译和监视某个component, 提高性能和效率(其他文件不编译输出)
gulp gm:develop -c component_name1,component_name2,component_name3...
# publish 发布资源,包括合并、压缩资源、rev产生MD5等
gulp gm:publish
# publish命令支持`-a`和`-v`参数指定输出资源/模板目录(可选)
gulp gm:publish -v your_views_dist -a your_assets_dist
# clean 清理构建输出的目录和文件
gulp gm:clean
# clean 清理构建输出的目录和文件,包括自文件夹/目录
gulp gm:clean-deep
# 编译输出一份运行时资源文件,但是不进入监视状态
# compile for develop, not watch
gulp gm:compile
```
### 2. 开发中只监视某个component目录
* 随着项目变大,开发中如果全局监视所有component资源,效率将会降低,因此可使用gulpman提供的监视子component的方式来开发,提高性能
* 比如说,只监视components目录下的home模块:
```Shell
# this will only watch `components/home` components
gulp gm:develop -c home
```
### 3. 如何在gulpman下使用React
* 安装React: `npm install react react-dom`
* 在ES6文件中使用
```Javascript
import React from 'react';
import ReactDOM from 'react-dom';
// xxx
```
### 4. 如何在js|es6|jsx中使用tpl模板
* 目前支持.tpl扩展名的模板文件,直接打包到最终的js文件中
* 用法:`import dialogTpl from './dialog.tpl'` 或者 `var dialogTpl = require('./dialog.tpl')`
### 5. 如何在HTML/CSS中嵌入base64编码的图片
* 只需要图片资源后面添加`?_gm_inline`即可
* 打包时候会将图片生成`base64`编码替换到到html中
##### html
```html
<p class="play">
<img width="480" alt="Karat 克拉" src="./img/testb64.png?_gm_inline" />
</p>
```
##### CSS/SCSS
```css
.test {
background: url(./img/testb64.png?_gm_inline) no-repeat;
}
```
### 6. 如何在HTML中嵌入内联CSS/JS
* 类似图片base64,只需要资源后面添加`?_gm_inline`即可
```html
<script src="./plugin.js?_gm_inline" type="text/javascript"></script>
<link href="./dialog.css?_gm_inline" rel="stylesheet" type="text/css" >
```
* 注:所有内嵌嵌入的资源,包括图片/JS/CSS,在develop(监视)模式下,都已自动关联更新。即如果a.html文件中,内联嵌入了一个b.css,如果b.css发生了修改,那么a.html会自动编译更新。
### 7. 如何使用Sprite雪碧图
* 通过配置启用CSS Sprite `gulpman.config({ enableCSSSprite: true })` 默认false不启用
* 基于spritesmith实现,在gulpman.config 中可传入spritesmith配置opts
* 关于spritesmith详细参见:[https://github.com/Ensighten/spritesmith](https://github.com/Ensighten/spritesmith)
* 只需要在scss文件中的图片url资源后面添加`?_gm_sprite`即可
```css
.demo {
background: url(./img/abc.png?_gm_sprite) no-repeat;
/* other style you can set ...*/
width: 50px;
height: 50px;
}
```
### 8. 如何使用Usemin
* 整合usemin,在gulpman.config 中可传入usemin的配置opts
* 关于usemin详细参见:[https://github.com/zont/gulp-usemin](https://github.com/zont/gulp-usemin)
* 只需要在html文件中添加usemin的build注释即可。支持`js`|`css`|`inlinejs`|`inlinecss`等语法
* 注意build注释中配置的输出路径写相对路径即可,跟script、link等标签类似,gulpman会自动转换成最终输出路径
```html
<!-- build:css ./home.css -->
<link rel="stylesheet" type="text/css" href="./main.css">
<link rel="stylesheet" type="text/css" href="./fff.css">
<!-- endbuild -->
<!-- build:js ../lib/base_lib.js -->
<script type="text/javascript" src="../lib/jquery.js"></script>
<script type="text/javascript" src="../lib/react.js"></script>
<!-- endbuild -->
```
### 9. 如何使用前端js模板
* 支持tpl扩展名,放到components相关目录下即可,js 可以直接require或者import
* 最终会作为字符串格式打包进js
* tpl中仍然支持资源嵌入和图片base64等,如参照前面_gm_inline等语法即可
- import到es6中
```js
import dialogTpl from './dialog.tpl'
```
- 或者使用require语法
```js
var dialogTpl = require('./dialog.tpl')
```
### 10. 引入css文件到js/html
- 直接import即可,gulpman会自动加载到html页面中.
```js
import from './style.css';
```
```js
require('./style.css');
```
### 11. 使用iconfont转换
* 可以将svg转换成icon-font,用`@font-face`方式引用
* 初次使用先安装,运行`gulp gm:iconfont:install`
* 将svg文件放到`components/iconfonts/source`目录下,运行`gulp gm:iconfont`即可
* 自动生成的icon-font和css文件将会在`iconfonts/gmicon`目录下
### 12. 支持LAB.js来完成异步加载js
* 引入LAB.js到项目中
* 使用LAB的api来加载即可,使用相对路径
* 代码用例: `$LAB.script("../testload/test.js").wait(()=>{console.log('test loaded')})`
### 13. Require CSS in js
* 直接在js中require你的css文件(源文件时scss文件)
* The CSS contents will be packaged into js files, and automatically injected to html when page opend. Using style tag
* 使用时要确保添加 .css 扩展名
* 举例: `require('./style.css')` or `import style from './style.css'`
### 14. 如何启用karma单元测试
* 初次使用先安装,运行`gulp gm:karma:install`,会安装依赖和生成`karma.conf.js`文件
* 在您的components中的对应模块目录下,建立一个spec文件夹,将对应的spec文件放在里面,文件拓展名是.es6
* 运行 `gulp gm:karma:start` 来启动单元测试(watch模式),将会运行各spec文件,完成后可在生成的coverage文件夹中查看覆盖率结果
* 指定spec目录、browsers等karma的选项,可以在`karma.conf.js`中设置、定制等
### 教程
[浏览教程链接](http://karat.cc/article/56a351c3e48d2d05682aa0ac "karat.cc")
### License
MIT
================================================
FILE: assets/.babelrc
================================================
{
"presets": ["es2015", "react", "stage-3"]
}
================================================
FILE: index.js
================================================
/**
* Gulpman
* FOR MODULAR FRONT-END SOURCE COMPILE SYSTEM
*/
// =======================================
'use strict'
// system module
let path = require('path'),
j = path.join,
sh = require("shelljs")
// gulp module
let gulp = require('gulp'),
p = require('gulp-load-plugins')(),
// modules
pngquant = require('imagemin-pngquant'),
browserify = require('browserify'),
stringify = require('stringify'),
buffer = require('vinyl-buffer'),
source = require('vinyl-source-stream'),
es = require('event-stream'),
globby = require('globby'),
through = require('through2'),
// gulpman utils
gmutil = require('./lib/gmutil'),
base64 = require('./lib/base64'),
store = require('./lib/store'),
htmlInline = require('./lib/inline'),
revReplace = require('./lib/revReplace'),
gulpUsemin = require('./lib/gulp-usemin'),
assetsPathParser = require('./lib/assetsPathParser'),
htmlPathParser = require('./lib/htmlPathParser.js'),
// css spriter
spriter = require('./lib/spriter'),
// fix prefix for revAll and revReplace
cdnProxy = require('./lib/cdnProxy'),
specificComponents = [];
// define base vars ========================================
let isDevelop = true,
isWatching = false
// get the cwd
const _cwd = process.cwd()
const _echo_off = ' >/dev/null 2>&1'
let _opts = {
// is enable the absolute prefix url
'is_absolute': true,
// source url prefix
'cdn_prefix': '',
'url_prefix': '/static',
// define babel optionals
'babel': {
'presets': ['es2015', 'react', 'stage-3'],
'sourceMaps': 'inline'
},
// library path and global module path
'lib': 'lib',
'global': 'global',
// whether browserify `lib` directory
'compileLibFiles': false,
// enable css-sprite;
'enableCSSSprite': false,
// the components source dir
'components': './components',
'runtime_views': './views',
'dist_views': './views_dist',
'runtime_assets': './assets',
'dist_assets': './assets_dist',
// for sprite
// 'spritesmith': {}
// for usemin. No need rev here, by global rev.
'usemin': {
// css: [ p.rev ],
// html: [ function () {return minifyHtml({ empty: true });} ],
// js: [ p.uglify, p.rev ],
inlinejs: [ p.uglify ]
// inlinecss: [ p.cssnano ]
},
'iconfont': {},
'cssnano': {
discardUnused: {
fontFace: false
}
}
}
// define raw source type ===================================
const base_source_type = 'js,css',
img_source_type = 'png,PNG,jpg,JPG,gif,GIF,jpeg,JPEG,webp,WEBP,bmp,BMP',
img_source_reg = img_source_type.split(',').join('|'),
jstpl_source_type = 'tpl',
font_source_type = 'svg,SVG,tiff,ttf,woff,woff2,eot',
other_source_type = 'txt,mp3,mp4,ogg,webm,mpg,wav,wmv,mov,ico',
// the pure raw souce means the source do not need gulp deal at all!
pure_source_type = [font_source_type, other_source_type ].join(),
// all raw source
all_raw_source_type = [base_source_type, img_source_type, font_source_type, jstpl_source_type, other_source_type].join(),
all_raw_source_reg = all_raw_source_type.split(',').join('|')
// uncompiled source =====================================
let sass_source,
es6_source,
all_raw_source,
html_source,
// For publish source
js_source,
lib_source,
except_lib_source,
dist_lib_path,
dist_except_lib_path,
css_source,
// js templates file
tpl_source,
img_source,
pure_source,
dist_html_source,
dist_css_source,
dist_js_source,
dist_tpl_source,
dist_all_raw_source
// init vars
function initVars(){
_opts['usemin']['url_prefix'] = _opts['url_prefix']
_opts['dist_static'] = j(_opts['dist_assets'] /*, _opts['url_prefix']*/ )
_opts['runtime_static'] = j(_opts['runtime_assets'] /*, _opts['url_prefix']*/ )
_opts['runtime_static_tmp'] = j(_opts['runtime_assets'], '.tmp_raw_static')
// components sources
sass_source = j(_opts['components'], '**/*.{scss,sass}')
es6_source = j(_opts['components'], '**/*.{es6,jsx}')
all_raw_source = j(_opts['components'], '**/*.{'+all_raw_source_type+'}')
html_source = [j(_opts['components'],'**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')]
// to-be-published source ================================
js_source = j(_opts['runtime_static'], '**/*.js')
lib_source = j(_opts['runtime_static'], _opts['lib'], '**/*.*')
except_lib_source = '!' + lib_source
dist_lib_path = j(_opts['dist_static'], _opts['lib'])
dist_except_lib_path = '!' + dist_lib_path
css_source = j(_opts['runtime_static'], '**/*.css'),
//js tpl
tpl_source = j(_opts['runtime_static'], '**/*.tpl'),
img_source = j(_opts['runtime_static'],'**/*.{'+img_source_type+'}')
pure_source = j(_opts['runtime_static'], '**/*.{'+pure_source_type+'}')
// dist source path
dist_html_source = j(_opts['dist_views'], '**/*.html')
dist_css_source = j(_opts['dist_static'], '**/*.css')
dist_js_source = j(_opts['dist_static'], '**/*.js')
dist_tpl_source = j(_opts['dist_static'], '**/*.tpl')
dist_all_raw_source = j(_opts['dist_assets'], '**/*.{'+all_raw_source_type+'}')
// fix cdn prefix useage by proxy
_opts = cdnProxy.proxyPrefix(_opts)
}
// init vars before gulpman tasks
initVars()
// COMMON UTILS FN ========================================
function OSInform(title, _message, err){
let message = _message || title
try {
// call the os inform
sh.exec("osascript -e 'display notification \""+message+"\" with title \""+title+"\"'"+_echo_off)
}catch(err){
gmutil.warn('*Call System Inform Failed!')
}
if(err){
var errDesc = err['codeFrame'] || ''
// print the err messsage
err && err.message && gmutil.error('\n*'+err.plugin+': '+err.name+'\n' + err.message+'\n'+errDesc+'\n')
}
return {
then (cb){
cb && cb()
}
}
}
function OSInformError(title, err, errDesc){
let filePath = getRelativePathOfComponents(err.fileName)
var einfo = errDesc || filePath
if(einfo === undefined){
einfo = 'Interal Error Occured'
}
return OSInform(title, einfo, err)
}
function getB64ImgReg(){
return new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/]+?(\\.('+img_source_reg+')))(\\?_gm_inline)(?=[\'"]?)', 'gm')
}
// browserify
function browserified(fpath, sourceDir){
let _bOpts = {
entries: fpath,
debug: true,
extensions: ['.es6', '.jsx', '.js'],
//global modular
paths: [
j(sourceDir, _opts['lib']),
j(sourceDir, _opts['global'])
],
transform: [
stringify(['.tpl', '.txt']),
['browserify-css', {
global: true,
autoInject: true,
onFlush: function(options, done) {
// @debug
// here can do a function for calculate path
let fRelativeName = path.relative(_opts['runtime_static_tmp'], options.href)
let tmpSourceFilePath = path.join(_cwd, _opts['components'], fRelativeName)
let sourceFilePath = gmutil.convertSource(tmpSourceFilePath, 'css')
let tmpJSRelativePath = path.relative(_opts['runtime_static_tmp'], fpath)
let jsSoucefilePath = path.join(_opts['components'], tmpJSRelativePath)
// @debug the fpath is not real source path, but ignore this path becuase no use now.
store.save(sourceFilePath, jsSoucefilePath, 'requiredCSS')
done();
}
// for path src in css
/*processRelativeUrl: function(relativeUrl) {
if (_.contains(['.jpg','.png','.gif'], path.extname(relativeUrl))) {
// Embed image data with data URI
var DataUri = require('datauri');
var dUri = new DataUri(relativeUrl);
return dUri.content;
}
return relativeUrl;
}*/
}]
]
}
// use wathcify to browserify
// var watchifybOpts = Object.assign(_bOpts, watchify.args)
// return watchify(browserify(watchifybOpts)).bundle()
return browserify(_bOpts)
.bundle()
.on('error', function(err){
err.plugin = 'Browserify'
OSInformError('Browserify Error', err, err['message'])
console.log(err)
// browserify的流特殊,需要emti才能停止,否则会挂掉
this.emit('end')
})
.pipe(source(fpath))
.pipe(buffer())
}
function getDirFromTmpStaticToRuntimeStatic(p){
var diffDir = path.relative(_opts['runtime_static_tmp'], p.dirname),
newDirname = j(_opts['runtime_static'], diffDir)
return newDirname
}
// 根据代码的require等,打包js文件
function doBrowserify(){
// 这里不做增量打包,因为js有自身依赖机制,并非单一依赖,需要重新整体打包
// 此处如果是tpl发生变化,也会导致重新打包
// 此处取tmp目录,确保源文件干净没有被browserify过
let filesGlob = '';
if (specificComponents.length > 0) {
const browserifyComponentsList = [_opts['global']].concat(specificComponents);
// if enable compile `lib` files, then push it to browserify path;
if (_opts['compileLibFiles']) {
browserifyComponentsList.unshift(_opts['lib']);
}
filesGlob = '{' + browserifyComponentsList.join() + '}/';
}
var files = globby.sync(j(_opts['runtime_static_tmp'], filesGlob + '**/*.es6')),
tasks = files.map((entry)=>{
// 注意,此处dest目录必须和src目录不一致,否则dest打包后会把输出结果直接输出到src, 那么会影响后续打包的文件,后续打包的文件的require的文件已经不是srcw文件,而是被dest后的文件,因此会有require、define那块额外添加的代码的冗余
return browserified(entry, _opts['runtime_static_tmp'])
.pipe(p.rename(p=>{
/**
* 此处作用是,将.tmp_raw_static目录,
* 作为未打包备份目录,不被打包后文件覆盖
* 这样.tmp_raw_static目录可以被watch中触发的打包服务
*/
p.dirname = getDirFromTmpStaticToRuntimeStatic(p)
p.extname = '.js'
}))
.pipe(gulp.dest('./'))
})
return es.merge.apply(null, tasks)
}
function getComponentsPath(){
return j(_cwd, _opts['components'])
}
// get handler for relevancy update
function getRelevancyHandler() {
return {
// only the scss files in raw folder implemented increasement updates
'scss': compile_sass,
'html': function (rawHtmlFile){
// The html has implemented increaement updates for Base64
gmutil.tip('*Relevancy HTML: '+rawHtmlFile)
let basepath = getComponentsPath()
parseRawHTML(gulp.src(rawHtmlFile), basepath, true)
},
'requiredCSS': function(filePath, event) {
// here the filePath is related ES6 js file, not scss file
// the `event` comes from watcher
fireUpdate('es6', {
'type': 'changed',
'path': filePath,
})
},
'sprite': function (filePath, event) {
/**
* if the img is in sprite-relevancy, then fire the scss event to re-compile-css
*/
// the `event` comes from raw files watcher
fireUpdate('sprite', {
'type': 'changed',
'path': filePath,
})
},
'tpl': function(filePath){
// the current was changed scss file which is relevancy with the tpl file
var event = getUpdateEvent()
updateTplFile(filePath)
event['path'] = filePath
fireUpdate('tpl', event)
}
}
}
function updateTplFile(tmpFile){
// /Users/cloud/work/karat/k3/assets/.tmp_raw_static/home/dialog.tpl
var absTmpStatic = j(_cwd, _opts['runtime_static_tmp']),
tplRelPath = path.relative(absTmpStatic, tmpFile),
tplRelPathOfComponents = j(_opts['components'], tplRelPath)
sh.cp('-rf', tplRelPathOfComponents, tmpFile)
gmutil.warn('*Relink Tpl: '+tplRelPathOfComponents)
}
// for sprite
function spriteCSS(entry) {
// gmutil.alert('Sprite Entry: '+entry)
// 注意之前的问题: 检测到有sprite参数的css文件才会被push到下一个流,如果都没有,处理完这个流就是空的了。已经fix
return gulp.src(entry)
.pipe(spriter({
'cwd': _cwd,
// 'includeMode': 'explicit',
// The path and file name of where we will save the sprite sheet
'dist_root': _opts['runtime_static'],
// 'spriteSheet': j(_opts['dist_static'],'sprite_sheet.png'),
// Because we don't know where you will end up saving the CSS file at this point in the pipe,
// we need a litle help identifying where it will be.
// 'pathToSpriteSheetFromCSS': '../sprite_sheet.png'
// check if the spriter-img existed
'shouldVerifyImagesExist': true,
// throw error when occured
'silent': false,
'spritesmithOptions': _opts['spritesmith']
}))
.on('error', function(err){
OSInformError('CSS Spriter Error', err, err['message'])
this.end()
})
//这里用通用的traversal解决了
.pipe(gulp.dest('./'))
}
// wrap the store check fn
function storeCheck(filepath, dbType, handlerType, evtObj){
// check if the file is in relevancy data
return store.check(
filepath,
getRelevancyHandler(),
dbType,
handlerType,
evtObj
)
}
// Main Tasks =====================================
function safeClean(path) {
if (!path.replace(/[.\/]+/g, '')) {
return ''
} else {
return path
}
}
gulp.task('gm:clean', ()=>{
sh.rm('-rf', [
safeClean(_opts['runtime_views']),
safeClean(_opts['dist_views']),
safeClean(_opts['runtime_static']),
safeClean(_opts['dist_static']),
safeClean(_opts['runtime_static_tmp']),
safeClean(_opts['runtime_assets']),
safeClean(_opts['dist_assets']),
])
})
// clean dir includes components
gulp.task('gm:clean-deep', ['gm:clean'],()=>{
var pSep = '/' //path.sep
var runtime_assetsRoot = path.normalize(_opts['runtime_assets']).split(pSep)[0]
var dist_assetsRoot = path.normalize(_opts['dist_assets']).split(pSep)[0]
var runtime_viewsRoot = path.normalize(_opts['runtime_views']).split(pSep)[0]
var dist_viewsRoot = path.normalize(_opts['dist_views']).split(pSep)[0]
sh.rm('-rf', [
runtime_assetsRoot,
dist_assetsRoot,
runtime_viewsRoot,
dist_viewsRoot
])
})
// clean dir includes components
gulp.task('gm:clean-all', ['gm:clean'],()=>{
sh.rm('-rf', [
_opts['components'],
])
})
gulp.task('gm:compile-copy', ()=>{
return gulp.src(all_raw_source)
.pipe(gulp.dest(_opts['runtime_static']))
// 复制一份 非编译到static备份目录
.pipe(gulp.dest(_opts['runtime_static_tmp']))
})
function compile_sass(singleFile){
// 此处增量编译scss, 当处于监视状态,只编译修改了的scss文件
// 此处还没有关联到sass的增量,只关联了raw source中的css
// @todo
let _sass_source = singleFile || sass_source
// gmutil.tip('*Compile SCSS: '+_sass_source)
return gulp.src(_sass_source)
.pipe(p.sourcemaps.init())
.pipe(p.sass())
.on('error', function(err){
OSInformError('SCSS Compile Error', err, 'Compile Error')
this.emit('end')
})
.pipe(p.sourcemaps.write())
.pipe(base64({
'is_absolute': _opts['is_absolute'],
'baseDir': _opts['runtime_static'],
'url_prefix': _opts['url_prefix'],
'components': _opts['components'],
'isDevelop': isDevelop,
// the current files type
'type': 'css',
'rule': getB64ImgReg()
}))
.on('error', function(err){
OSInformError('CSS Img-Base64 Error', err, err['message'])
this.end()
})
.pipe(gulp.dest(_opts['runtime_static']))
// 这里没有复制到static的.tmp_raw_static备份目录
}
gulp.task('gm:compile-sass', ()=>{
return compile_sass()
})
// generate sprite if exist
gulp.task('gm:compile-css-sprite', ()=>{
if (!_opts['enableCSSSprite']) {
return;
}
// here generate sprite into css
// now sprite all css in runtime_static
let files = globby.sync([css_source, /*except_lib_source*/]),
// 每个css的sprite图路径可能是不一样的,所以要遍历的去sprite,每次动态修改sprite的config的输出sprite图的路径
tasks = files.map(entry=>spriteCSS(entry))
// @debug
// 现在问题是,spriteCSS还没运行完,下面就执行了,parsseHTML,所以导致html内容是spriteCSS之前的
return es.merge.apply(null, tasks)
// here can do optimization , continue use this pipe to do traversal
})
gulp.task('gm:compile-css-traversal', ()=>{
return gulp.src([css_source])
.pipe(assetsPathParser.absolutizePath({
// replace relative path to absolute path
'cwd': _cwd,
// add for tpl parse
'_opts': _opts,
// 跟资源最终url前缀有关
'_isRuntimeDir': false,
'all_raw_source_reg': all_raw_source_reg,
// end for tpl parse
'is_absolute': _opts['is_absolute'],
'static_dir': _opts['runtime_static'],
'cdn_prefix': _opts['cdn_prefix'],
'url_prefix': _opts['url_prefix'],
'components': _opts['components']
}))
.pipe(gulp.dest('./'))
// for css require in js
.pipe(p.rename(fpath=>{
let fRelativeDir = path.relative(_opts['runtime_static'], fpath.dirname)
let fTmpStaticDir = path.join(_opts['runtime_static_tmp'], fRelativeDir)
fpath.dirname = fTmpStaticDir
}))
.pipe(gulp.dest('./'))
})
gulp.task('gm:compile-css', cb=>{
return p.sequence(
'gm:compile-sass',
'gm:compile-css-sprite',
'gm:compile-css-traversal'
)(cb)
})
gulp.task('gm:compile-media-check', ['gm:compile-css'], function(){
// 此刻检查关联性,sprite那块还未处理,所有html更新的inline的css中,只有处理了base64,应该在sprite处理完css后,再检查
if(isWatching){
// store for relevancy scss
var curEvent = getUpdateEvent()
if(curEvent){
var epath = curEvent.path,
// solution是fireUpdate添加的,fire类型
solution = curEvent['solution']
if(solution == 'sprite' ) {
// 对于sprite引起改变的css
var tarFilePath = epath
}else {
// 其余的按照编译型资源处理
// 计算源文件(来自components的资源,计算出输出后的资源)
var tarPath = getAbsPathOfTarget(epath, _opts['runtime_static'])
var tarFilePath = translatePathExtname('css', tarPath)
}
gmutil.tip('*Modified File: '+epath)
gmutil.tip('*Target File: '+tarFilePath)
storeCheck(tarFilePath)
// check if it is requiredCSS
storeCheck(epath, 'requiredCSS', 'requiredCSS', curEvent)
// @debug 如果不remove,会有重复触发
removeUpdateEvent()
}else {
gmutil.warn('*Unhandled Event: '+JSON.stringify(curEvent))
}
}
})
/**
* THIS WILL TRIGGER `Trunk filled` Problem
*/
// for sass and sprite and inline(base64)
// gulp.task('gm:xxx', p.sequence('ttt','yyy'))
gulp.task('gm:compile-es6', ()=>{
return gulp.src(es6_source)
.pipe(p.babel(_opts['babel']))
.on('error', function(err) {
OSInformError('Babel Error', err)
this.end()
throw Error('*Compile Stopped for the Babel Error')
})
.pipe(p.rename(path=>{
// 这里有一部分是从es6转成的.js,也有一部分是jsx转成的.js
// 此处都统一扩展名设置为.es6,方便后面browserify打包
path.extname = '.es6'
}))
.pipe(assetsPathParser.absolutizePath({
// replace relative path to absolute path
'cwd': _cwd,
// add for tpl parse
'_opts': _opts,
// related to final url
'_isRuntimeDir': false,
'all_raw_source_reg': all_raw_source_reg,
// end for tpl parse
'is_absolute': _opts['is_absolute'],
'static_dir': _opts['runtime_static'],
'cdn_prefix': _opts['cdn_prefix'],
'url_prefix': _opts['url_prefix'],
'components': _opts['components']
}))
// 输出到tmp目录,是为了browserify文件时,源文件时干净的,避免被打包过的又打包一次
.pipe(gulp.dest(_opts['runtime_static_tmp']))
// 这个是输出目录
.pipe(gulp.dest(_opts['runtime_static']))
})
// 处理tpl,
gulp.task('gm:compile-tpl', cb=>{
// 这儿最好根据打包目录来拆分,这样publish后,打包和开发目录都是正常的
var _isRuntimeDir = isDevelop
var tb = gulp.src(j(_opts['runtime_static_tmp'], '**/*.tpl'))
.pipe(assetsPathParser.absolutizePath({
// replace relative path to absolute path
'cwd': _cwd,
// add for tpl parse
'_opts': _opts,
// 跟资源最终url前缀有关
'_isRuntimeDir': false,
'all_raw_source_reg': all_raw_source_reg,
// end for tpl parse
'is_absolute': _opts['is_absolute'],
'static_dir': _opts['runtime_static'],
'cdn_prefix': _opts['cdn_prefix'],
'url_prefix': _opts['url_prefix'],
'components': _opts['components']
}))
/**
* @debug
* 这里需要输出到tmp_runtime_static目录一份,提供干净打包
* 这样也导致一个问题,update-tpl的时候,源文件也是来自于tmp_runtime_static,
* 这样这块文件在develop的时候是脏的,可能跟components中的tpl不一致,需要修复
*
* 修复方法1,如果不再往tmp_static写入htmlParseFlow的tpl,tmp_static 就始终一个源tpl,从raw_watcher那儿监听,如果源tpl 修改了,tmp_static 中的tpl才会更新。这样有问题,因为browserify es6的时候,是从tmp_static 中取文件的(为了保持干净),那么嵌入到js中的tpl就是源文件内容,没有处理过的,嵌入资源也没有
* 修复方式2 每次打包前从raw的components目录中复制一份tpl到tmp_static,这样来更新(htmlParseFlow后又回覆盖这个tpl文件)
*
*/
var rsB = htmlParseFlow(tb, _isRuntimeDir)
.pipe(gulp.dest('./'))// 不能根据修复1取消,有错误,用修复2
.pipe(p.rename(p=>{
// 输出到正式runtime_static
p.dirname = getDirFromTmpStaticToRuntimeStatic(p)
}))
// 输出到正式目录供使用
.pipe(gulp.dest('./'))
if(isDevelop){
return rsB
}else {
// 再输出到dist_static中做备用比如js中可能异步加载?
return rsB.pipe(p.rename(p=>{
// 输出到正式runtime_static
var diffDir = path.relative(_opts['runtime_static'], p.dirname),
newDirname = j(_opts['dist_static'], diffDir)
p.dirname = newDirname
}))
.pipe(gulp.dest('./'))
}
})
gulp.task('gm:compile-browserify', ['gm:compile-tpl', 'gm:compile-es6'], ()=>{
return doBrowserify()
})
gulp.task('gm:compile-html', cb=>{
return parseRawHTML(gulp.src(html_source), null, true)
})
// only used for publish
gulp.task('gm:publish-html', cb=>{
// the `null` is basepath
// the `false` is isRuntimeDir
return parseRawHTML(gulp.src(html_source), null, false)
})
gulp.task('gm:publish-usemin', ()=>{
let html_src = j(_opts['dist_views'], '**/*.html')
if(_opts['is_absolute']){
_opts['usemin']['path'] = _opts['dist_assets']
var diffPath = path.relative(_opts['dist_views'], _opts['dist_assets'])
_opts['usemin']['outputRelativePath'] = diffPath
}
return gulp.src(html_src)
.pipe(gulpUsemin(_opts['usemin']))
.pipe(gulp.dest(_opts['dist_views']))
})
gulp.task('gm:compile', cb => {
updateSpecificComponentsSource();
return p.sequence(
'gm:clean',
'gm:compile-copy',
'gm:compile-css',
// 由于tpl 中可能需要嵌入css,因此将compile-css和compile-browserify 变成串行
'gm:compile-browserify',
'gm:compile-html'
)(cb)
});
/**
* FOR DEVELOP WATCHT ================================
*/
/**
* 因为task不能传参,这里用全局变量来实现,
* 后续考虑优化
* @type {[type]}
*/
let _g_update_evt = {
'_current_event': null,
'scss': {
'event': null,
'task': 'gm:compile-media-check'
},
'sprite': {
'event': null,
'task': 'gm:compile-media-check'
},
'es6': {
'event': null,
'task': 'gm:update-js'
},
// need browserify
'tpl': {
'event': null,
'task': 'gm:update-tpl'
}
}
function fireUpdate(type, event){
event['solution'] = type
_g_update_evt['_current_event'] = _g_update_evt[type]['event'] = event
let _task = _g_update_evt[type]['task']
_task && gulp.start(_task)
}
function getUpdateEvent(type){
if(type){
return _g_update_evt[type]['event']
}else {
return _g_update_evt['_current_event']
}
}
function removeUpdateEvent(type){
if(type){
_g_update_evt[type] && (_g_update_evt[type]['event'] = null)
}else {
_g_update_evt['_current_event'] = null
}
}
function htmlParseFlow(b, _isRuntimeDir){
return b.pipe(base64({// 第二步,替换生成html原本内容本身中的base64图片路径, 比如img标签中有?_gm_inline则被替换为base64
'is_absolute': _opts['is_absolute'],
'baseDir': _opts['runtime_assets'],
'url_prefix': _opts['url_prefix'],
'views': _isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'],
'dist_assets': _opts['dist_assets'],
'isDevelop': isDevelop,
'type': 'html',
'rule': getB64ImgReg()
}))
.on('error', function(err){
OSInformError('HTML Img-Base64 Error', err, err['message'])
this.end()
})
.pipe(htmlInline({// 第三步,向html中替换插入行内标记的内容
'is_runtime': _isRuntimeDir,
'absoluteRoot': _opts['is_absolute'] ? (_isRuntimeDir ? _opts['runtime_assets'] : _opts['dist_assets']) : false,
queryKey: '_gm_inline',
// 选择是否压缩css
minifyCss: _isRuntimeDir ? false : true,
// 选择是否压缩js,
minifyJs: _isRuntimeDir ? false : true,
'dist_dir': _opts['dist_assets'],
'runtime_dir': _opts['runtime_assets'],
'url_prefix': _opts['url_prefix'],
'root': _cwd
}))
.on('error', function(err){
OSInformError('htmlInline Error', err)
this.end()
})
}
// 解析html文件中的资源路径和做处理
function parseRawHTML(b, basepath, _isRuntimeDir) {
/**
* @debug 未完成inline后的路径转换
*
* 1. 这里inline后需要一个路径转换,比如css中./a.png 当inline到html中,可能变成了 ../../assets/static/home/a.png,不转换将可能404。
* 2. 如果将行内内容或者components中全部内容中(可能主要是css的资源引用,js现在没有做资源嵌入)的资源引用都做成绝对路径,那么没有这个问题了。也可以考虑在做inline的时候,转换路径,也就是1。
*/
// 第一步先计算并替换html的相关路径
var tb = b.pipe(htmlPathParser({
'_opts': _opts,
'basepath': basepath,
'_isRuntimeDir': _isRuntimeDir,
'all_raw_source_reg': all_raw_source_reg
}))
.on('error', function(err) {
OSInformError('ParseHtml Error', err)
this.end()
})
return htmlParseFlow(tb, _isRuntimeDir)
.pipe(gulp.dest(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views']))
}
function getRelativePathOfComponents(epath) {
if(epath === undefined) return;
let comsPath = getComponentsPath()
return path.relative(comsPath, epath)
}
function translatePathExtname(type, _path){
var d = {
'js': function(){
return _path.replace(/\.(es6|jsx)$/gm, '.js')
},
'css': function(){
return _path.replace(/\.(scss|sass)$/gm, '.css')
}
}
return d[type]()
}
function delChangedFile(epath, delOutDir, type){
let relPath = getRelativePathOfComponents(epath)
// 这里可以用path的api来处理后重新生成,用正则不准确可能
// 删除文件,首先判断类型,来处理拓展名
if(type == 'js'){
// relPath = relPath.replace(/\.(es6|jsx)$/gm, '.js')
relPath = translatePathExtname('js', relPath)
}else if(type == 'css'){
// relPath = relPath.replace(/\.(scss|sass|css)$/gm, '.css')
relPath = translatePathExtname('css', relPath)
}else {
// relPath is relPath,keep the extname
}
let delFilePath = j(delOutDir, relPath)
gmutil.tip('Delete File: '+ delFilePath)
// 删除输出的文件
sh.rm('-rf', delFilePath)
}
function getRelativePathOfTarget(epath, tarBaseDir){
let relPath = getRelativePathOfComponents(epath),
tarPath = j(tarBaseDir, relPath),
dirPath = path.dirname(tarPath)
return {
'tarPath': tarPath,
'dirPath': dirPath
}
}
function getAbsPathOfTarget(epath, tarBaseDir){
return j(_cwd, getRelativePathOfTarget(epath, tarBaseDir)['tarPath'])
}
// check file dep
function _checkRelevancy(filePath, event){
// check for raw sources
storeCheck(filePath)
storeCheck(filePath, 'sprite', 'sprite', event)
}
function getSpecificComponentsList() {
if (process.argv[4]) {
return process.argv[4].split(',');
}
return [];
}
function updateSpecificComponentsSource() {
const componentsList = getSpecificComponentsList();
if (componentsList.length > 0) {
// should filter the `lib` html files;
const htmlList = componentsList.concat(_opts['global']);
specificComponents = [].concat(componentsList);
;
const sourceComponents = [_opts['lib'], _opts['global']].concat(componentsList).join();
all_raw_source = j(_opts['components'], '{' + sourceComponents + '}/**/*.{'+all_raw_source_type+'}');
html_source = [j(_opts['components'],'{' + htmlList.join() + '}/**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')];
gmutil.warn('\n');
gmutil.warn('Components Source: \n -> '+ componentsList.join(', '));
gmutil.warn('\n');
}
}
// tasks
gulp.task('gm:update-es6', ()=>{
//这里用增量更新处理了已经,只babel转换有变动的es6
var _evt = getUpdateEvent('es6')
let epath = _evt.path,
etype = _evt.type
return gulp.src(epath)
.pipe(p.babel(_opts['babel']))
.on('error', function(err){
OSInformError('Babel Error', err)
this.end()
})
.pipe(p.rename(path=>{
// 这里算法可能需要优化简化一下
let relPath = getRelativePathOfComponents(epath)
let namePt = new RegExp(`${path.basename}\.(es6|jsx)$`, 'gm')
relPath = relPath.replace(namePt, '')
/**
* 输出到 未打包备份目录中,
* 而不是输出到已经打包的目录,
* 否则会覆盖正式的static目录中打包后的js文件)
*/
path.dirname = j(_opts['runtime_static_tmp'], relPath)
path.extname = '.es6'
gmutil.tip('*ES6 File Changed: ' + epath)
}))
.pipe(gulp.dest('./'))
})
gulp.task('gm:update-js', ['gm:update-es6'], ()=>{
return doBrowserify()
})
// for browserify and tpl refresh
gulp.task('gm:update-tpl', ['gm:compile-tpl'], ()=>{
return doBrowserify()
})
gulp.task('gm:develop', ['gm:compile'], ()=>{
let _cmdBase = {
'component': {
'-c': true,
'-component': true
}
}
let _how = process.argv[3];
let _watch_es6_source = es6_source,
_watch_css_source = sass_source,
_watch_html_source = html_source,
_watch_all_raw_source = all_raw_source;
const _specificList = getSpecificComponentsList();
const _whatList = [_opts['lib'], _opts['global']].concat(_specificList);
const _what = '{' + _whatList.join() + '}';
if(_how in _cmdBase['component'] && _specificList.length > 0){
gmutil.warn('\n*Watch Component: ' + _what)
_watch_es6_source = j(_opts['components'], _what, '**/*.{es6,jsx}')
_watch_css_source = j(_opts['components'], _what, '**/*.{scss,sass}')
_watch_html_source = [j(_opts['components'], _what, '**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')]
_watch_all_raw_source = j(_opts['components'], _what, '**/*.{'+all_raw_source_type+'}')
}
gmutil.warn('\n*Source Compiled Succeed. \n*Loading source. Waiting ...\n')
// watch es6\js ----------------------------------
let js_watcher = gulp.watch(_watch_es6_source)
js_watcher.on('change', event=>{
switch(event.type){
case 'deleted':
delChangedFile(event.path, _opts['runtime_static'], 'js')
delChangedFile(event.path, _opts['runtime_static_tmp'], 'js')
break
// for added changed
default:
fireUpdate('es6', event)
}
})
// watch scss ----------------------------------
let css_watcher = gulp.watch(_watch_css_source)
// 目前watch scss并没有做成增量,因为sass有自身模块依赖机制
css_watcher.on('change', event=>{
let epath = event.path,
etype = event.type
switch(event.type){
case 'deleted':
delChangedFile(epath, _opts['runtime_static'], 'css')
break
default:
fireUpdate('scss', event)
}
return false
})
// watch html --------------------------------------
let html_watcher = gulp.watch(_watch_html_source)
html_watcher.on('change', event=>{
let epath = event.path,
etype = event.type,
f = getRelativePathOfTarget(epath, _opts['runtime_views'])
if(etype == 'changed' || etype == 'added'){
let relPath = getRelativePathOfComponents(epath)
let htmlFilePathOfCwd = j(_opts['components'], relPath)
let basepath = getComponentsPath()
parseRawHTML(gulp.src(htmlFilePathOfCwd), basepath, true)
}else if(etype == 'deleted'){
delChangedFile(epath, _opts['runtime_views'])
}else if(etype == 'renamed'){
let oldPath = event.old,
oldf = getRelativePathOfTarget(oldPath, _opts['runtime_views'])
sh.cp('-rf', epath, f.dirPath)
sh.rm('-rf', oldf.tarPath)
gmutil.tip('Rename HTML File: '+oldf.tarPath)
}else {
// ddd
}
})
// raw source -------------------------------------
let raw_watcher = gulp.watch(_watch_all_raw_source)
raw_watcher.on('change', function(event) {
let epath = event.path,
file_extname = path.extname(epath),
f = getRelativePathOfTarget(epath, _opts['runtime_static']),
tmp_f = getRelativePathOfTarget(epath, _opts['runtime_static_tmp'])
let runtimeFile = gmutil.pathInAssets(_cwd, epath, _opts['components'], _opts['runtime_static'])
if(event.type == 'added' || event.type == 'changed'){
sh.cp('-rf', epath, f.dirPath)
gmutil.tip('*Copy Raw File To: '+f.tarPath)
// 复制js和tpl模板文件
if(file_extname == '.js' || file_extname == '.tpl') {
// for the reason of browserify-pack, so need copy to tmp_static
sh.cp('-rf', epath, tmp_f.dirPath)
gmutil.tip('*Copy Raw File To: '+tmp_f.tarPath)
if(file_extname == '.tpl'){
// the tpl need re-browserify
fireUpdate('tpl', event)
}
}
}else if(event.type == 'deleted'){
sh.rm('-rf', f.tarPath)
gmutil.tip('*Delete Raw File: '+f.tarPath)
if(file_extname == '.js') {
sh.rm('-rf', tmp_f.tarPath)
gmutil.tip('*Delete Raw File: '+f.tarPath)
}
}else if(event.type == 'renamed'){
let oldPath = event.old,
oldf = getRelativePathOfTarget(oldPath, _opts['runtime_static']),
old_tmpf = getRelativePathOfTarget(oldPath, _opts['runtime_static_tmp'])
gmutil.tip('*Rename Raw File: '+oldf.tarPath)
sh.cp('-rf', epath, f.dirPath)
sh.rm('-rf', oldf.tarPath)
if(file_extname == '.js') {
sh.cp('-rf', epath, tmp_f.dirPath)
sh.rm('-rf', old_tmpf.tarPath)
gmutil.tip('*Delete Raw File: '+f.tarPath)
}
}else {
gmutil.warn('Other Event: \n' + event)
}
// check dep
_checkRelevancy(runtimeFile, event)
})
.on('error', function(err){
gmutil.error('Error: ', err['message'])
console.log(err)
this.end()
})
// ready for watch --------------------------------
isWatching = true
gmutil.tip('\n*Now Watching For Development:\n')
OSInform('Ready For Development', 'Start')
})
/**
* FOR PUBLISH SOURCE ================================
*/
// utils
function setRevReplace(){
let manifest = gulp.src(j(_opts['dist_assets'],'rev-manifest.json'))
return revReplace({
'manifest': manifest,
// 如果is_absolute为false, 那么不启用cdn_prefix
'prefix': _opts['is_absolute'] ? _opts['cdn_prefix'] : '',
'url_prefix': _opts['url_prefix']
})
}
// tasks
gulp.task('gm:cssmin', ()=>{
// 除去lib
return gulp.src([css_source, except_lib_source])
.pipe(p.cssnano(_opts['cssnano']))
.pipe(gulp.dest(_opts['dist_static']))
})
gulp.task('gm:imagemin', ()=>{
// 除去lib
return gulp.src([img_source, except_lib_source])
.pipe(p.imagemin({
progressive: true,
debug: true,
svgoPlugins: [{
'removeViewBox': false
}],
use: [pngquant()]
}))
.pipe(gulp.dest(_opts['dist_static']))
})
gulp.task('gm:jsmin', ()=>{
// 除去lib
return gulp.src([js_source, except_lib_source])
.pipe(p.uglify())
.on('error', function (err){
gmutil.error('*Warning \n*Jsmin Error: \n')
console.log(err);
gmutil.warn('*Failed ...')
this.end();
})
.pipe(gulp.dest(_opts['dist_static']))
})
gulp.task('gm:rev-js', ()=>{
return gulp.src(dist_js_source)
.pipe(setRevReplace())
.pipe(gulp.dest(_opts['dist_static']))
})
/**
* Rev Generate MD5 for Source and File name
* =================================
*/
gulp.task('gm:rev', p.sequence(
'gm:rev-lib-pre',
// for usemin
'gm:publish-usemin',
'gm:rev-source',
['gm:rev-html', 'gm:rev-css', 'gm:rev-js'])
)
/**
* 由于lib属于第三方模块的特殊性,在处理uglify js的时候会导致错误等,
* 因此特殊处理,只压缩css
*/
// for the lib prepare
gulp.task('gm:rev-lib-pre', p.sequence('gm:rev-copy-lib', ['gm:lib-mincss', 'gm:lib-uglify']))
// copy lib source to dist lib dir
gulp.task('gm:rev-copy-lib', ()=>{
return gulp.src(lib_source)
.pipe(gulp.dest(dist_lib_path))
})
// minify the lib css
gulp.task('gm:lib-mincss', ()=>{
return gulp.src(j(dist_lib_path, '**/*.css'))
.pipe(p.cssnano(_opts['cssnano']))
.pipe(gulp.dest(dist_lib_path))
})
// minify the lib js
gulp.task('gm:lib-uglify', ()=>{
return gulp.src(j(dist_lib_path, '**/*.js'))
// uglify libjs常会导致错误,某些第三方类库uglify导致的
// .pipe(p.uglify())
.pipe(gulp.dest(dist_lib_path))
})
/**
* 将dist目录的所有编译后资源,包括css,js,img,font等,做md5
*/
gulp.task('gm:rev-source', ()=>{
const revOpts = {
// 禁止参与重命名的文件
'dontRenameFile': ['.html', /^\/favicon.ico$/],
// 无需关联处理文件
'dontGlobal': [ /^\/favicon.ico$/, '.txt' /*'.tpl'*/],
// 该项配置只影响当前src的静态资源中 绝对路径的资源引用地址
'prefix': _opts['transformPath'] ? '' : (_opts['is_absolute'] ? _opts['cdn_prefix'] : ''),
// 如果prefix传入的是函数,那么将在rev-all中执行transformPath
'transformPath': _opts['transformPath']
};
return gulp.src(dist_all_raw_source)
.pipe(p.revAll.revision(revOpts))
/**
* 这里因为assets_url的缘故,
* dist_all_raw_source的路径要不带static,
* 否则最终发布的html,assets_url会跑到_opts['cdn_prefix']前面。
*/
.pipe(gulp.dest(_opts['dist_assets']))
// 输出manifest文件
.pipe(p.revAll.manifestFile())
.pipe(gulp.dest(_opts['dist_assets']))
})
gulp.task('gm:rev-html', ()=>{
return gulp.src(dist_html_source)
.pipe(setRevReplace())
.pipe(gulp.dest(_opts['dist_views']))
})
gulp.task('gm:rev-css', ()=>{
/**
* debug
* 这个rev插件有个bug,对于css中,以emma-wat-012.jpg这种中划线格式的图片,md5后,css中资源未被替换...
*/
return gulp.src(dist_css_source)
.pipe(setRevReplace())
.pipe(gulp.dest(_opts['dist_static']))
})
// create ../assets_dist
gulp.task('gm:create-assets-dist-dir', ()=>{
// 目前由于browserify可能已经不需要了(这一步之前已经生成了)
sh.exec('mkdir ' + _opts['dist_assets']+ _echo_off)
})
gulp.task('gm:copy-pure-source', ()=>{
return gulp.src([pure_source, except_lib_source])
.pipe(gulp.dest(_opts['dist_static']))
})
// for compile publish
gulp.task('gm:copy', [
'gm:create-assets-dist-dir',
'gm:copy-pure-source',
'gm:publish-html'
],()=>{
// 从 runtime的views目录内容,拷贝到dist的views目录
// return gulp.src(j(_opts['runtime_views'], '**/*.*'))
// .pipe(gulp.dest(_opts['dist_views']))
})
//set Mode in Publish
gulp.task('gm:publish-mode', ()=>{
let args = process.argv.slice(3),
r = {}
// 如果在CLI指定了输出目录
if(args.length){
args.forEach((v,i)=>i%2 == 0 && (r[v] = args[i+1]))
let _dist_views = r['-v'] || r['-views']
let _dist_assets = r['-a'] || r['-assets']
gmutil.warn('*Dist Path Config\n*dist_assets: '+(_dist_assets || '@config')+'\n*dist_views: '+(_dist_views || '@config'));
(_dist_assets || _dist_views) && updateConf(gmutil.validateObj({
'dist_assets': _dist_assets,
'dist_views': _dist_views
}))
}
isDevelop = false
})
gulp.task('gm:osinform', ()=>{
OSInform('Publish Succeed', 'Completed')
})
// publish source ,based on the runtime source
gulp.task('gm:publish', p.sequence(
'gm:publish-mode',
'gm:compile',
'gm:copy',
['gm:jsmin', 'gm:cssmin', 'gm:imagemin'],
'gm:rev',
'gm:osinform'
))
// For init demo and constructure ===============
// init dir and create some meta files
gulp.task('gm:generate-config', ()=>{
let conf_path = j(__dirname ,'./assets/.babelrc')
return gulp.src(conf_path)
.pipe(gulp.dest('./'))
})
// create componetns dir
gulp.task('gm:generate-components', ()=>{
// May invalid for windows
sh.exec('mkdir '+_opts['components']+_echo_off)
})
// init dir and create some meta files
gulp.task('gm:generate-lib', ()=>{
let prelib_path = j(__dirname ,'./presetlib/**/*.*')
return gulp.src(prelib_path)
.pipe(gulp.dest(j(_opts['components'], _opts['lib'])))
})
// init dir and create some meta files
gulp.task('gm:generate-meta', ()=>{
let meta_path = j(__dirname ,'./meta/**/*.*')
return gulp.src(meta_path)
.pipe(gulp.dest(_opts['components']))
})
// open demo html file
gulp.task('gm:open-demo', ()=>{
sh.exec('open '+j(_opts['runtime_views'], 'home/index.html')+_echo_off)
OSInform('Init Succeed', 'Completed')
})
// init the proj
gulp.task('gm:init', p.sequence(
'gm:clean',
'gm:generate-components',
['gm:generate-meta', 'gm:generate-lib'],
// 'gm:generate-config',
'gm:compile',
'gm:open-demo'
))
// init the proj
gulp.task('gm:install', () => {
sh.exec('cd node_modules/gulpman && npm install gulp-sass --save');
sh.exec('npm install babel-preset-es2015 babel-preset-react babel-preset-stage-3 browserify-css --save-dev');
})
/**
* FOR karma ut test and coverage =====
*/
gulp.task('gm:karma:install', ()=>{
sh.exec('npm install karma karma-browserify karma-coverage karma-jasmine karma-chrome-launcher browserify-istanbul babel-preset-es2015 babel-preset-react babel-preset-stage-3 babelify babel-istanbul watchify stringify --save-dev')
sh.cp('./node_modules/gulpman/karma/karma.conf.js', './')
})
gulp.task('gm:karma:start', ()=>{
sh.exec('./node_modules/karma/bin/karma start')
});
/**
* For plugins tasks
*/
gulp.task('gm:iconfont:install', ()=>{
sh.exec('npm install gulp-iconfont gulp-iconfont-css --save-dev')
})
require('./lib/iconFonter').registerTask(gulp, _opts)
// API ================================
// config the dir
function updateConf(opts){
Object.assign(_opts, opts)
initVars()
return _opts
}
exports['config'] = updateConf
// return the _opts
exports['getConfig'] = function(){
return _opts
}
exports['util'] = gmutil
================================================
FILE: karma/karma.conf.js
================================================
var stringify = require('stringify');
var ignore_files = '**/lib/**',
spec_files = '**/spec/**',
tpl_files = '**/*.tpl',
node_modules_files = '**/node_modules/**';
var babelOpts = {
presets: ['es2015', 'react'],
// sourceMap: 'inline',
ignore: [node_modules_files, ignore_files, tpl_files]
}
module.exports = function(config) {
config.set({
basePath: '',
frameworks: [ 'browserify', 'jasmine' ],
files: [
"./components/**/*.es6",
],
browsers: ['Chrome'],
preprocessors: {
"./components/**/*.es6": ['browserify']
},
browserify: {
debug: true,
paths: ['./components/lib'],
transform: [
stringify(['.tpl', '.txt']),
["babelify", babelOpts],
['browserify-istanbul', {
instrumenter: require('babel-istanbul'),
instrumenterConfig: {
// embedSource: true,
babel: babelOpts,
},
ignore: [
spec_files,
tpl_files,
node_modules_files,
ignore_files
],
}]
],
extensions: ['.es6', '.jsx', '.js']
},
// logLevel: config.LOG_DEBUG,
reporters: ['progress', 'coverage'],
coverageReporter: {
type : 'html',
dir : './coverage'
},
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
================================================
FILE: lib/assetsPathParser.js
================================================
/**
* For path replace into abs path
*/
'use strict'
var through = require('through2'),
path = require('path'),
j = path.join,
gmutil = require('./gmutil')
/*
var ct = ';saasdfasf url()\n\r background: url ( "./img/1.png?_gm_inline&sd=32" ) no-repeat; \n\t; .d{ background-image: url(sss.png?_gm_sprite ) }'*/
var cssUrlReg = /url\s*\(\s*['"]?(.+?)['"]?\s*\)/gm
var opts = {}
function parseCSS(content, file){
var tList = content.match(cssUrlReg)
if(tList){
tList.forEach(t=>{
var url = t.replace(/[\n\r\b\t\s'"]+/gm, '').replace(/^url\(/gm, '').replace(/\)$/gm, '')
// 如果是相对路径,那么替换
if(gmutil.isUrl('relative', url) ){
var baseDir = j(opts['cwd'], opts['static_dir'])
// gmutil.alert('Base: '+baseDir)
var fileRelativeDirOfComponents = path.relative(baseDir, file.path)
// var hostFileAbsPath = j()
var relativeDir = path.dirname(fileRelativeDirOfComponents)
// gmutil.alert('relativeDir: '+relativeDir)
var mediaRelPath = j(relativeDir, url)
// gmutil.alert('mediaRelPath: '+mediaRelPath)
var absUrl = j(opts['url_prefix'], mediaRelPath)
// gmutil.alert('absUrl: '+absUrl)
var tarStr = 'url('+absUrl+')'
content = content.replace(t, tarStr)
}
})
}
return content
}
function parseTpl(conf, contents, file){
let _opts = conf['_opts'],
basepath = conf['basepath'],
_isRuntimeDir = conf['_isRuntimeDir'],
all_raw_source_reg = conf['all_raw_source_reg'],
fdirname = path.dirname(file.relative),
_urlPrefix // set assets url prefix
if(_opts['is_absolute']) {
_urlPrefix = _opts['url_prefix']
}else {
// 判断打包资源中的url路径前缀
let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname)
let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static']
_urlPrefix = path.relative(_fPath, _staticPath)
}
// 所有格式都要处理
let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm')
// httpReg = /^http(s)?\:/
let tmp_rs_list = [],
rs_list = []
// 提取单标签和双标签
tmp_rs_list = tmp_rs_list
.concat(contents.match(gmutil.reg['tagMedia']))
.concat(contents.match(gmutil.reg['closeTagMedia']))
// 首先提取标签,然后从标签中提取href或者src
tmp_rs_list.length && (
rs_list = tmp_rs_list
.filter(r=>(r && r.match(srcQuoteReg)))
.map(v=>v.match(srcQuoteReg)[0])
.filter(r=>{
// remove the http:xxx.com/xx and base64 data url
// 只处理相对路径
// 不处理绝对路径、http、dataURL
return gmutil.isUrl('relative', r)
})
.filter(r=>!r.match(/^(['"]\/)/gm))
)
// 这里利用set做去重
let rs_set = new Set(rs_list),
srcPrefix = j(_urlPrefix, fdirname)
// 替换url的的path和前缀
rs_set.size && rs_set.forEach(epath=>{
// 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64
let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm')
contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2')
})
// dealing with usemin build mark syntax
// when in publish, not runtime-dir
if(!_isRuntimeDir) {
// 这里处理usemin 的build的注释内容
contents = gmutil.replaceBuildBlock(contents, srcPrefix)
}
return contents
}
function parseJS(conf, contents, file){
let _opts = conf['_opts'],
basepath = conf['basepath'],
_isRuntimeDir = conf['_isRuntimeDir'],
all_raw_source_reg = conf['all_raw_source_reg'],
fdirname = path.dirname(file.relative),
_urlPrefix // set assets url prefix
if(_opts['is_absolute']) {
_urlPrefix = _opts['url_prefix']
}else {
// 判断打包资源中的url路径前缀
let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname)
let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static']
_urlPrefix = path.relative(_fPath, _staticPath)
}
// for all src "xxx.yy" format path
let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm')
// httpReg = /^http(s)?\:/
let tmp_rs_list = [],
rs_list = []
// 提取单标签和双标签
tmp_rs_list = tmp_rs_list
.concat(contents.match(gmutil.reg['requireAsync']))
.concat(contents.match(gmutil.reg['jsAsyncLoad']))
// 首先提取标签,然后从标签中提取href或者src
tmp_rs_list.length && (
rs_list = tmp_rs_list
.filter(r=>(r && r.match(srcQuoteReg)))
.map(v=>v.match(srcQuoteReg)[0])
.filter(r=>{
// remove the http:xxx.com/xx and base64 data url
// 只处理相对路径
// 不处理绝对路径、http、dataURL
return gmutil.isUrl('relative', r)
})
.filter(r=>!r.match(/^(['"]\/)/gm))
)
// 这里利用set做去重
let rs_set = new Set(rs_list),
srcPrefix = j(_urlPrefix, fdirname)
// 替换url的的path和前缀
rs_set.size && rs_set.forEach(epath=>{
// 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64
let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm')
contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2')
})
// dealing with usemin build mark syntax
// when in publish, not runtime-dir
if(!_isRuntimeDir) {
// 这里处理usemin 的build的注释内容
contents = gmutil.replaceBuildBlock(contents, srcPrefix)
}
return contents
}
function _absolutizePath(_opts){
opts = Object.assign(opts, _opts)
return through.obj(function(file, enc, cb){
if (file.isNull()) {
this.push(file);
return cb()
}
if (file.isStream()) {
gmutil.error('*PathParser Error: Streaming not supported')
return cb()
}
var fileType = path.extname(file.path).slice(1)
if(opts['is_absolute']){
var content = file.contents.toString()
if(fileType == 'css'){
var rc = parseCSS(content, file)
}else if(fileType == 'tpl'){
var rc = parseTpl(opts, content, file)
}else if(fileType == 'js' || fileType == 'es6'){
var rc = parseJS(opts, content, file)
}else{
throw Error("Unknown Type: "+fileType)
}
file.contents = new Buffer(rc)
}
// gmutil.error(file.base)
// gmutil.error(file.relative)
// this will dest in right path
if(fileType != 'js' && fileType != 'es6') {
file.base = opts['cwd']
}
this.push(file)
return cb()
})
}
exports.absolutizePath = _absolutizePath
================================================
FILE: lib/base64.js
================================================
/**
* FOR BASE 64 UTILS
*/
var path = require('path'),
j = path.join,
fs = require('fs'),
gutil = require('gulp-util'),
through = require('through2')
var store = require('./store'),
gmutil = require('./gmutil')
var bError = null
var opts
const PLUGIN_NAME = 'Base64'
function purifyUrlPrefix(str){
return str.replace(opts['url_prefix'], '');
}
function purify(str){
return str.split('?')[0]
// return str.replace(/\?_gm_inline/gm, '')
}
function parseSource(images, file, refType, content, baseDir){
var fileDir = path.dirname(file.relative)
var status = true
// gmutil.alert('debug: '+fileDir)
images.forEach(function(item) {
// remove url() in css
var imageURL = item
.replace(/\(|\)|\'/g, '')
.replace(/^url/g, '')
// 这里路经计算,需要后续优化
// 现在相对路径计算繁琐了
var pureFilePath;
// console.log('item:', item)
// // 如果url是相对路径,那么解析
// if(!gmutil.isUrl('relative', imageURL)){
// // imageURL = imageURL.replace(opts['url_prefix'], '')
// }
if(refType == 'css'){
if(opts['isDevelop']){
file.base = opts['components']
fileDir = path.dirname(file.relative)
}
pureFilePath = j(
file.cwd,
baseDir,
fileDir,
imageURL
)
// html or other source
}else {
var srcPath = purify(j(file.cwd, opts['views'], fileDir, imageURL))
// 输出资源在HMTL是相对路径情况下
if(opts['is_absolute'] === false){
// develop模式下
if(opts['isDevelop']){
pureFilePath = srcPath
}else {
// publish 模式下
var dist_assets_path = j(file.cwd, opts['dist_assets']),
runtime_assets_path = j(file.cwd, baseDir)
pureFilePath = srcPath.replace(dist_assets_path, runtime_assets_path)
}
// 绝对路径情况下,比如/static/home/main.css
}else {
pureFilePath = j(baseDir, imageURL)
}
// remove url_prefix
pureFilePath = purifyUrlPrefix(pureFilePath)
}
// 如果url是绝对路径,那么解析
// }else {
// }
// remove base64 params
pureFilePath = purify(pureFilePath)
// gmutil.warn('pureFilePath: \n\n\n'+pureFilePath+'\n\n')
// check if exist
try {
var filepath = fs.realpathSync(pureFilePath);
}catch(err){
bError = err
gmutil.error(err['message'])
gmutil.error('\n*Check Your Component: '+fileDir)
status = false
return false
}
var extname = purify(path.extname(imageURL).slice(1))
var imageContent = new Buffer(fs.readFileSync(filepath)).toString('base64')
content = content.replace(
item,
'data:image/' +
extname.toLowerCase() +
';base64,' +
imageContent
)
// generate json file of relevance
store.save(filepath, gmutil.convertSource(file.path, refType))
gmutil.log('*Convert to Base64: ' + filepath, 'green')
})
if(status) {
return content
}else {
return false
}
}
function toBase64(_opts) {
opts = _opts || {}
var rule = opts.rule || /url\([^\)]+\)/g
var refType = opts.type || 'css',
baseDir = opts.baseDir || './'
opts['dist_assets'] || (opts['dist_assets'] = '')
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file)
return cb()
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'))
return cb()
}
var content = file.contents.toString()
var images = content.match(rule)
if(images){
content = parseSource(images, file, refType, content, baseDir, this)
// 如果出现错误返回了false
if(content === false){
var errMes = 'File Not Exist'
if(bError){
errMes = bError['message']
}
this.emit('error', new gutil.PluginError(PLUGIN_NAME, errMes))
}else {
file.contents = new Buffer(content)
}
}
this.push(file)
cb()
})
}
module.exports = toBase64;
================================================
FILE: lib/cdnProxy.js
================================================
/**
* FOR CDN PREFIX CONFIG
*
* FIX gulp-rev-all and revReplace about `prefix`
*/
/**
* Another Proxy code in revReplace.js,
* include random url of list and function
*/
var gmutil = require('./gmutil')
function proxyPrefix(obj){
// fix prefix options for gulp-rev-all
// 注意: 这了可能会干预到rev-replace里的变量
obj['cdn_prefix'] = obj['cdn_prefix'] || ''
obj['_prefix'] = obj['cdn_prefix']
// fix array
if(obj['cdn_prefix'] instanceof Array){
// console.log('Array: \n', obj['cdn_prefix'])
function _getRandPrefixFromList(){
return obj['_prefix'][gmutil.randomNum(0, obj['_prefix'].length-1)]
}
// rewrite replace of array
obj['cdn_prefix'].replace = function(a, b){
var p = _getRandPrefixFromList().replace(a, b)
return p
}
// rewrite toString of array
obj['cdn_prefix'].toString = function(){
return _getRandPrefixFromList()
}
}else if(obj['cdn_prefix'] instanceof Function){
// !! only for gulp-rev-all
obj['transformPath'] = function (rev, source, file) {
return obj['_prefix'](source, rev, file)+rev
// on the remote server, image files are served from `/images`
// return rev.replace('/img', '/images')
}
}else if(typeof obj['cdn_prefix'] == 'string'){
// no handle
// obj['_all_prefix'].add(obj['cdn_prefix'])
}else {
throw Error('Unknown Type: '+ (typeof obj['cdn_prefix']))
}
return obj
}
exports.proxyPrefix = proxyPrefix
================================================
FILE: lib/gmutil.js
================================================
/**
* FOR UTILS
*/
'use strict'
var colors = require('colors'),
path = require('path'),
j = path.join
function _log (str, color) {
str += ''
var color = color || 'blue'
console.log(str[color])
}
function _error (str){
return _log(str, 'red')
}
function _alert(str) {
return _log(str, 'red')
}
function _tip (str){
return _log(str, 'green')
}
function _warn (str){
return _log(str, 'yellow')
}
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function byLongestUnreved(a, b) {
return b.unreved.length - a.unreved.length;
}
function pathInAssets(_cwd, fpath, componentsDir, runStaticDir){
var componentsAbsPath = j(_cwd, componentsDir),
imgRelPath = fpath.replace(componentsAbsPath, ''),
imgAbsPath = j(_cwd, runStaticDir, imgRelPath)
return imgAbsPath
}
function validateObj(obj){
var a
for(a in obj){
if(obj.hasOwnProperty(a) && obj[a] === undefined) {
delete obj[a]
}
}
return obj
}
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
function convertSource(rawSource, refType){
let tarType
if(refType == 'css'){
tarType = 'scss'
}
var repReg = new RegExp('\\.'+refType+'$', 'g'),
rsList = []
if(!rawSource.match(repReg)) {
return rawSource
}
if(typeof tarType == 'string'){
return rawSource.replace(repReg, '.'+tarType)
}else {
return rawSource
}
}
function isUrl(urlType, str){
var _d = {
'absolute': /^\//g,
'http': /^http(s)?\:/g,
'dataURL': /^data\:/g,
}
var t = _d[urlType]
if(urlType == 'relative'){
return !isUrl('absolute', str) &&
!isUrl('http', str) &&
!isUrl('dataURL', str)
}
if(!t){
throw Error('Unknow Type: '+t)
}
return str.match(_d[urlType])
}
function joinUrl (a, b){
if(!b.match(/\/$/g)) {
b = b + '/'
}
if(!a.match(/\/$/g) && !b.match(/^\//g)) {
return a + '/' + b;
}else if(a.match(/\/$/g) && b.match(/^\//g)){
return a.replace(/\/$/g, '') + b;
}else{
return a + b;
}
}
function replaceBuildBlock(content, srcPrefix) {
var startReg = /<!--\s*build:(\w+)(?:(?:\(([^\)]+?)\))?\s+(\/?([^\s]+?))?)?\s*-->/gim;
var endReg = /<!--\s*endbuild\s*-->/gim;
var sections = content.split(endReg)
sections.forEach((e, i)=>{
var block
if( (block = e.match(startReg)) && (block = block[0])){
var section = e.split(startReg)
// var block = e.match(startReg)[0]
var outputPathParam = section[4];
if(!outputPathParam) {
// not set output path in usemin, build:js/css
var srcStr = section[5]
var doExec = true
var comboNameList = []
var comboExtFileName
while(doExec) {
let oneFile = _reg['sourceUrl'].exec(srcStr)
let ofname
if(oneFile && (ofname = oneFile[2])){
let oneFileName = path.basename(ofname);
let extFileName = path.extname(ofname)
if(!comboExtFileName) {
comboExtFileName = extFileName
}
comboNameList.push(oneFileName.replace(extFileName, ''))
}else {
doExec = false
}
}
if(!comboExtFileName) {
comboExtFileName = '.unknown'
_warn('*Found Unknown Extname, check your assets files!')
}
// add 80 as max combo name length
var comboNameStr = comboNameList.join('_').slice(0, 80) + comboExtFileName
var outputPathParam = comboNameStr.split('?')[0]
_warn('*Not set build file name, use combo name: ' + outputPathParam)
// _error(outputPathParam)
}
var newOutPath = j(srcPrefix, outputPathParam)
// _alert('Usemin Build: '+newOutPath)
// section[2]: alternative search path
// section[3]: nameInHTML: section[3]
// section[4]: relative out path
content = content.replace(block, '<!-- build:' + section[1] + (section[2] ? section[2] : ' ') + newOutPath + ' -->')
}
})
return content
}
// source reg
var _reg = {
link: new RegExp('<link\\s+[\\s\\S]*?>[\\s\\S]*?<*\\/*>*', 'gi'),
img: new RegExp('<img\\s+[\\s\\S]*?>[\\s\\S]*?<*\\/*>*', 'gi'),
href: new RegExp('\\s*(href)=["\']+([\\s\\S]*?)["\']'),
style:new RegExp('<style\\s*[\\s\\S]*?>[\\s\\S]*?<\\/style>', 'gi'),
script: new RegExp('<script\\s*[\\s\\S]*?>[\\s\\S]*?<\\/script>', 'gi'),
src: new RegExp('\\s*(src)=["\']+([\\s\\S]*?)["\']'),
sourceUrl: new RegExp('\\s*(src|href)=["\']+([\\s\\S]*?)["\']', 'gi'),
jsAsyncLoad: new RegExp('\\s*(\\.script\\()["\']+([\\s\\S]*?)["\']\\)', 'gi'),
requireAsync: new RegExp('\\s*(require\\.async\\()["\']+([\\s\\S]*?)["\']\\)', 'gi'),
tagMedia: new RegExp('<(img|link|source|input)\\s+[\\s\\S]*?>[\\s\\S]*?<*\\/*>*', 'gi'),
closeTagMedia: new RegExp('<(script|iframe|frame|audio|video|object)\\s*[\\s\\S]*?>[\\s\\S]*?<\\/(script|iframe|frame|audio|video|object)>', 'gi'),
useminBuild: new RegExp('<\\!\\-\\-\\s+build\\:\\w+\\s+([\\w\\.\\/\\-\\?\\=&]+)\\s+\\-\\->', 'gm')
}
// log
exports.log = _log
exports.error = _error
exports.alert = _alert
exports.tip = _tip
exports.warn = _warn
exports.reg = _reg
// for rev replace
exports.byLongestUnreved = byLongestUnreved
exports.joinUrl = joinUrl
// utils
exports.randomNum = randomNum
exports.isArray = isArray
exports.pathInAssets = pathInAssets
exports.validateObj = validateObj
exports.convertSource = convertSource
// for usemin build
exports.replaceBuildBlock = replaceBuildBlock
exports.isUrl = isUrl
================================================
FILE: lib/gulp-usemin/.npmignore
================================================
/node_modules
/*.log
.idea/
*~
================================================
FILE: lib/gulp-usemin/.travis.yml
================================================
language: node_js
node_js:
- "4.0"
before_script:
- npm install
================================================
FILE: lib/gulp-usemin/LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014 Alexander Zonov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: lib/gulp-usemin/README.md
================================================
[](https://travis-ci.org/zont/gulp-usemin)
# gulp-usemin
> Replaces references to non-optimized scripts or stylesheets into a set of HTML files (or any templates/views).
This task is designed for gulp >= 3 and node >= 4.0.
> Attention: v0.3.0 options is not compatible with v0.2.0.
## Usage
First, install `gulp-usemin` as a development dependency:
```shell
npm install --save-dev gulp-usemin
```
Then, add it to your `gulpfile.js`:
```javascript
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var minifyHtml = require('gulp-minify-html');
var minifyCss = require('gulp-minify-css');
var rev = require('gulp-rev');
gulp.task('usemin', function() {
return gulp.src('./*.html')
.pipe(usemin({
css: [ rev() ],
html: [ minifyHtml({ empty: true }) ],
js: [ uglify(), rev() ],
inlinejs: [ uglify() ],
inlinecss: [ minifyCss(), 'concat' ]
}))
.pipe(gulp.dest('build/'));
});
```
If you need to call the same pipeline twice, you need to define each task as a function that returns the stream object that should be used.
```javascript
gulp.task('usemin', function() {
return gulp.src('./*.html')
.pipe(usemin({
css: [ rev ],
html: [ function () {return minifyHtml({ empty: true });} ],
js: [ uglify, rev ],
inlinejs: [ uglify ],
inlinecss: [ minifyCss, 'concat' ]
}))
.pipe(gulp.dest('build/'));
});
```
## API
### Blocks
Blocks are expressed as:
```html
<!-- build:<pipelineId>(alternate search path) <path> -->
... HTML Markup, list of script / link tags.
<!-- endbuild -->
```
- **pipelineId**: pipeline id for options or *remove* to remove a section
- **alternate search path**: (optional) By default the input files are relative to the treated file. Alternate search path allows one to change that
- **path**: the file path of the optimized file, the target output
An example of this in completed form can be seen below:
```html
<!-- build:css style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:htmlimport components-packed.html -->
<link rel="import" href="components-a.html">
<link rel="import" href="components-b.html">
<!-- endbuild -->
<!-- build:js js/lib.js -->
<script src="../lib/angular-min.js"></script>
<script src="../lib/angular-animate-min.js"></script>
<!-- endbuild -->
<!-- build:js1 js/app.js -->
<script src="js/app.js"></script>
<script src="js/controllers/thing-controller.js"></script>
<script src="js/models/thing-model.js"></script>
<script src="js/views/thing-view.js"></script>
<!-- endbuild -->
<!-- build:remove -->
<script src="js/localhostDependencies.js"></script>
<!-- endbuild -->
<!-- build:inlinejs -->
<script src="../lib/angular-min.js"></script>
<script src="../lib/angular-animate-min.js"></script>
<!-- endbuild -->
<!-- build:inlinecss -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
```
### Options
#### assetsDir
Type: `String`
Alternate root path for assets. New concated js and css files will be written to the path specified in the build block, relative to this path. Currently asset files are also returned in the stream.
#### path
Type: `String`
Default alternate search path for files. Can be overridden by the alternate search path option for a given block.
#### any pipelineId
Type: `Array`
If exist used for modify files. If does not contain string 'concat', then it added as first member of pipeline
#### outputRelativePath
Type: `String`
Relative location to html file for new concatenated js and css.
#### enableHtmlComment
Type: `Boolean`
Keep HTML comment when processing
#### jsAttributes
Type: `Object`
Attach HTML attributes to the output js file.
For Example :
```js
gulp.task('usemin', function() {
return gulp.src('./index.html')
.pipe(usemin({
html: [],
jsAttributes : {
async : true,
lorem : 'ipsum',
seq : [1, 2, 1]
},
js: [ ],
js1:[ ],
js2:[ ]
}))
.pipe(gulp.dest('./'));
});
```
Will give you :
```html
<script src="./lib.js" async lorem="ipsum" seq="1"></script>
<script src="./app.js" async lorem="ipsum" seq="2"></script>
<script src="./extra.js" async lorem="ipsum" seq="1"></script>
```
As your built script tag.
## Use case
```
|
+- app
| +- index.html
| +- assets
| +- js
| +- foo.js
| +- bar.js
| +- css
| +- clear.css
| +- main.css
+- dist
```
We want to optimize `foo.js` and `bar.js` into `optimized.js`, referenced using relative path. `index.html` should contain the following block:
```
<!-- build:css style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:js js/optimized.js -->
<script src="assets/js/foo.js"></script>
<script src="assets/js/bar.js"></script>
<!-- endbuild -->
```
We want our files to be generated in the `dist` directory. `gulpfile.js` should contain the following block:
```javascript
gulp.task('usemin', function () {
return gulp.src('./app/index.html')
.pipe(usemin({
js: [uglify()]
// in this case css will be only concatenated (like css: ['concat']).
}))
.pipe(gulp.dest('dist/'));
});
```
This will generate the following output:
```
|
+- app
| +- index.html
| +- assets
| +- js
| +- foo.js
| +- bar.js
+- dist
| +- index.html
| +- js
| +- optimized.js
| +- style.css
```
`index.html` output:
```
<link rel="stylesheet" href="style.css"/>
<script src="js/optimized.js"></script>
```
## Changelog
#####0.3.23
- Added support array value for cssAttributes (by MillerRen)
#####0.3.22
- Added html import support (by linfaxin)
#####0.3.21
- Added support paths with querystring or hash (by Lanfei)
#####0.3.20
- Added support array value for jsAttributes (by kuitos)
#####0.3.18
- Fixed relative path for script in subfolder bug
#####0.3.17
- Fixed block output when stream returns multiple files (by maksidom)
#####0.3.16
- Added feature to assign attributes to js script tags (by sohamkamani)
#####0.3.15
- Allow proper html output when blocks are empty (by ppowalowski)
#####0.3.14
- fixed #91
#####0.3.13
- works fine only with gulp-foreach
#####0.3.12
- fixed #121. Depending on the node >= 0.12.
#####0.3.11
- fixed #88
#####0.3.10
- fixed uppercase Q bug (on case-sensetive file systems)
#####0.3.9
- async tasks support
#####0.3.8
- allow removal option (by tejohnso)
- added support for single quotes (by adicirstei)
#####0.3.7
- ouputRelativePath renamed outputRelativePath
#####0.3.6
- ouputRelativePath option (by bhstahl)
#####0.3.5
- Support for conditional comments inside build blocks (by simplydenis)
#####0.3.4
- When a file does not exist an error containing the missing path is thrown
#####0.3.3
- fixed dependencies
- Add support for multiple alternative paths (by peleteiro)
#####0.3.2
- fixed assetsDir option (by rovjuvano)
#####0.3.1
- fixed fails to create source map files by uglify({outSourceMap: true})
#####0.3.0
- new version of options
#####0.2.3
- fixed html minify bug
#####0.2.2
- allow gulp-usemin to work with minified source HTML (by CWSpear)
- fixed alternate path bug (by CWSpear)
- add assetsDir option (by pursual)
- add rev option (by pursual)
#####0.2.1
- fixed subfolders bug
#####0.2.0
- no minification by default. New options API
#####0.1.4
- add alternate search path support
#####0.1.3
- add support for absolute URLs (by vasa-chi)
#####0.1.1
- fixed aggressive replace comments
#####0.1.0
- fixed some bugs. Add tests.
#####0.0.2
- add minification by default
#####0.0.1
- initial release
================================================
FILE: lib/gulp-usemin/gulpfile.js
================================================
/* jshint node:true */
'use strict';
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
gulp.task('lint', function() {
return gulp.src('test/main.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(mocha());
});
gulp.task('default', ['lint']);
================================================
FILE: lib/gulp-usemin/index.js
================================================
module.exports = function(options) {
var through = require('through2');
var gutil = require('gulp-util');
var blocksBuilder = require('./lib/blocksBuilder.js');
var htmlBuilder = require('./lib/htmlBuilder.js');
return through.obj(function(file, enc, callback) {
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-usemin', 'Streams are not supported!'));
callback();
}
else if (file.isNull())
callback(null, file); // Do nothing if no contents
else {
try {
var blocks = blocksBuilder(file, options);
htmlBuilder(file, blocks, options, this.push.bind(this), callback);
} catch(e) {
this.emit('error', e);
callback();
}
}
});
};
================================================
FILE: lib/gulp-usemin/lib/blocksBuilder.js
================================================
var fs = require('fs');
var glob = require('globby');
var path = require('path');
var gutil = require('gulp-util');
module.exports = function(file, options) {
options = options || {};
var startReg = /<!--\s*build:(\w+)(?:(?:\(([^\)]+?)\))?\s+(\/?([^\s]+?))?)?\s*-->/gim;
var endReg = /<!--\s*endbuild\s*-->/gim;
var jsReg = /<\s*script\s+.*?src\s*=\s*['"]?([^'"?# ]+).*?><\s*\/\s*script\s*>/gi;
var cssReg = /<\s*link\s+.*?href\s*=\s*['"]?([^'"?# ]+).*?>/gi;
var cssMediaReg = /<\s*link\s+.*?media\s*=\s*['"]?([^'" ]+).*?>/gi;
var startCondReg = /<!--\[[^\]]+\]>/gim;
var endCondReg = /<!\[endif\]-->/gim;
var basePath = file.base;
var mainPath = path.dirname(file.path);
var outputPath = options.outputRelativePath || '';
var content = String(file.contents);
var sections = content.split(endReg);
var blocks = [];
var cssMediaQuery = null;
function getFiles(content, reg, alternatePath) {
var paths = [];
var files = [];
cssMediaQuery = null;
content
.replace(startCondReg, '')
.replace(endCondReg, '')
.replace(/<!--(?:(?:.|\r|\n)*?)-->/gim, function (a) {
return options.enableHtmlComment ? a : '';
})
.replace(reg, function (a, b) {
var tmpfileRelPath = b.replace(/^'|^"/, '').replace(/'$/, '').replace(/"$/, '');
if(options['url_prefix']){
var fileRelativePath = path.relative(options['url_prefix'], tmpfileRelPath);
}else {
var fileRelativePath = tmpfileRelPath;
}
var filePath = path.resolve(path.join(
alternatePath || options.path || mainPath,
fileRelativePath
));
if (options.assetsDir)
filePath = path.resolve(path.join(options.assetsDir, path.relative(basePath, filePath)));
paths.push(filePath);
});
if (reg === cssReg) {
content.replace(cssMediaReg, function(a, media) {
media = media.replace(/^'|^"/, '').replace(/'$/, '').replace(/"$/, '');
if (!cssMediaQuery) {
cssMediaQuery = media;
} else {
if (cssMediaQuery != media)
throw new gutil.PluginError('gulp-usemin', 'incompatible css media query for ' + a + ' detected.');
}
});
}
for (var i = 0, l = paths.length; i < l; ++i) {
var filepaths = glob.sync(paths[i]);
if(filepaths[0] === undefined) {
throw new gutil.PluginError('gulp-usemin', 'Path ' + paths[i] + ' not found!');
}
filepaths.forEach(function (filepath) {
files.push(new gutil.File({
path: filepath,
contents: fs.readFileSync(filepath)
}));
});
}
return files;
}
for (var i = 0, l = sections.length; i < l; ++i) {
if (sections[i].match(startReg)) {
var section = sections[i].split(startReg);
blocks.push(section[0]);
var startCondLine = section[5].match(startCondReg);
var endCondLine = section[5].match(endCondReg);
if (startCondLine && endCondLine)
blocks.push(startCondLine[0]);
if (section[1] !== 'remove') {
if(section[1] === 'htmlimport'){
blocks.push({
type: 'htmlimport',
nameInHTML: section[3],
name: path.join(outputPath || path.relative(basePath, mainPath), section[4]),
files: getFiles(section[5], cssReg, section[2]),
tasks: options[section[1]]
});
}else if (jsReg.test(section[5])) {
if (section[1].indexOf('inline') !== -1) {
blocks.push({
type: 'inlinejs',
files: getFiles(section[5], jsReg, section[2]),
tasks: options[section[1]]
});
}
else {
blocks.push({
type: 'js',
nameInHTML: section[3],
name: path.join(outputPath || path.relative(basePath, mainPath), section[4]),
files: getFiles(section[5], jsReg, section[2]),
tasks: options[section[1]]
});
}
}
else {
if (section[1].indexOf('inline') !== -1) {
blocks.push({
type: 'inlinecss',
files: getFiles(section[5], cssReg, section[2]),
tasks: options[section[1]],
mediaQuery: cssMediaQuery
});
}
else {
blocks.push({
type: 'css',
nameInHTML: section[3],
name: path.join(outputPath || path.relative(basePath, mainPath), section[4]),
files: getFiles(section[5], cssReg, section[2]),
tasks: options[section[1]],
mediaQuery: cssMediaQuery
});
}
}
}
if (startCondLine && endCondLine)
blocks.push(endCondLine[0]);
} else
blocks.push(sections[i]);
}
return blocks;
};
================================================
FILE: lib/gulp-usemin/lib/htmlBuilder.js
================================================
module.exports = function(file, blocks, options, push, callback) {
var path = require('path');
var gutil = require('gulp-util');
var pipeline = require('./pipeline.js');
var basePath = file.base;
var name = path.basename(file.path);
var mainPath = path.dirname(file.path);
function createFile(name, content) {
var filePath = path.join(path.relative(basePath, mainPath), name);
return new gutil.File({
path: filePath,
contents: new Buffer(content)
})
}
function createHTMLAttributes(attributes, index){
if(!attributes){
return '';
}
var attrArray = [];
Object.keys(attributes).forEach(function (attribute) {
var attributeValue = attributes[attribute];
if (attributeValue === true) {
attrArray.push(attribute);
return;
}
if (attributeValue === false) {
return;
}
if (Array.isArray(attributeValue)) {
attrArray.push(attribute + '="' + attributeValue[index] + '"');
} else {
attrArray.push(attribute + '="' + attributeValue + '"');
}
});
return ' ' + attrArray.join(' ');
}
// fix for revReplace url, if not fix then get: /http://s.cdn.com/public/a/b.js
function _fixUrlForRevReplace(str){
return str;
// return str ? str.replace(/^\//g, '') : str;
}
function _fixFilePath(name, file){
var realRelativeFilePath = '/' + path.relative(options['url_prefix'], name);
file.path = file.path.replace(name, realRelativeFilePath);
return file;
}
var html = [];
var jsCounter = 0;
var cssCounter = 0;
var promises = blocks.map(function(block, i) {
return new Promise(function(resolve) {
html[i] = '';
if (typeof block == 'string') {
html[i] = block;
resolve();
}
else if (block.files.length == 0){
resolve();
}
else if (block.type == 'js') {
pipeline(block.name, block.files, block.tasks, function(name, file) {
_fixFilePath(name, file);
push(file);
var jsAttributes = options ? options.jsAttributes : null;
if (path.extname(file.path) == '.js')
html[i] += '<script src="' + _fixUrlForRevReplace(name.replace(path.basename(name), path.basename(file.path))) + '"' + createHTMLAttributes(jsAttributes, jsCounter++) +'></script>';
resolve();
}.bind(this, block.nameInHTML));
}
else if (block.type == 'css') {
pipeline(block.name, block.files, block.tasks, function(name, file) {
_fixFilePath(name, file);
push(file);
var cssAttributes = options ? options.cssAttributes : null;
html[i] += '<link rel="stylesheet" href="' + _fixUrlForRevReplace(name.replace(path.basename(name), path.basename(file.path))) + '"'
+ (block.mediaQuery ? ' media="' + block.mediaQuery + '"' : '') + createHTMLAttributes(cssAttributes, cssCounter++) +'/>';
resolve();
}.bind(this, block.nameInHTML));
}
else if (block.type == 'inlinejs') {
pipeline(block.name, block.files, block.tasks, function(file) {
html[i] = '<script>' + String(file.contents) + '</script>';
resolve();
}.bind(this));
}
else if (block.type == 'inlinecss') {
pipeline(block.name, block.files, block.tasks, function(file) {
html[i] = '<style' + (block.mediaQuery ? ' media="' + block.mediaQuery + '"' : '') + '>'
+ String(file.contents) + '</style>';
resolve();
}.bind(this));
}
else if (block.type == 'htmlimport') {
pipeline(block.name, block.files, block.tasks, function(name, file) {
_fixFilePath(name, file);
push(file);
html[i] += '<link rel="import" href="' + _fixUrlForRevReplace(name.replace(path.basename(name), path.basename(file.path))) + '"/>';
resolve();
}.bind(this, block.nameInHTML));
}
});
});
Promise.all(promises).then(function() {
var createdFile = createFile(name, html.join(''));
pipeline(createdFile.path, [createdFile], options && options['html'], function(file) {
callback(null, file);
});
});
};
================================================
FILE: lib/gulp-usemin/lib/pipeline.js
================================================
module.exports = function(name, files, tasks, push) {
var through = require('through2');
var concat = require('gulp-concat')(name || 'filename.temp', {newLine: '\n'});
/* PREPARE TASKS */
tasks = (tasks || []).slice();
var concatIndex = tasks.indexOf('concat');
if (concatIndex == -1)
tasks.unshift(concat);
else
tasks[concatIndex] = concat;
tasks.push(through.obj(function(file, enc, streamCallback) {
streamCallback(null, file);
push(file);
}));
/* PREPARE TASKS END */
var stream = through.obj(function(file, enc, streamCallback) {
streamCallback(null, file);
});
var newStream = stream;
tasks.forEach(function(task) {
newStream = newStream.pipe(typeof(task) == 'function' ? task(): task);
});
files.forEach(stream.write.bind(stream));
stream.end();
};
================================================
FILE: lib/gulp-usemin/package.json
================================================
{
"name": "gulp-usemin",
"version": "0.3.23",
"description": "Replaces references to non-optimized scripts or stylesheets into a set of HTML files (or any templates/views).",
"main": "index.js",
"dependencies": {
"gulp-util": "~2.2.14",
"through2": "~0.5.1",
"glob": "~4.0.4",
"gulp-concat": "~2.4.1"
},
"devDependencies": {
"event-stream": "~3.1.0",
"vinyl-fs": "~2.3.1",
"gulp": "~3.8.6",
"gulp-jshint": "~1.7.0",
"gulp-mocha": "~0.5.1",
"gulp-uglify": "~0.3.1",
"gulp-minify-html": "~0.1.1",
"gulp-minify-css": "~0.3.0",
"gulp-rev": "~0.4.2",
"gulp-less": "2.0.1"
},
"scripts": {
"test": "gulp"
},
"repository": {
"type": "git",
"url": "git://github.com/zont/gulp-usemin.git"
},
"keywords": [
"gulpplugin",
"usemin",
"gulp-usemin"
],
"author": {
"name": "Alexander Zonov",
"email": "zont@pochta.ru"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/zont/gulp-usemin/issues"
},
"engines": {
"node": ">=0.12"
},
"gitHead": "81bff9fd6d46f9fbedea53e349001d0fa7bcb49c",
"homepage": "https://github.com/zont/gulp-usemin#readme",
"_id": "gulp-usemin@0.3.23",
"_shasum": "9f451546e4ac53a00119c7343d36c42d6a5ce6f0",
"_from": "gulp-usemin@>=0.3.21 <0.4.0",
"_resolved": "https://registry.npm.taobao.org/gulp-usemin/download/gulp-usemin-0.3.23.tgz",
"_npmVersion": "3.3.10",
"_nodeVersion": "5.0.0",
"_npmUser": {
"name": "alexander.zonov",
"email": "zont@pochta.ru"
},
"dist": {
"shasum": "9f451546e4ac53a00119c7343d36c42d6a5ce6f0",
"size": 12939,
"noattachment": false,
"tarball": "http://registry.npm.taobao.org/gulp-usemin/download/gulp-usemin-0.3.23.tgz"
},
"maintainers": [
{
"name": "alexander.zonov",
"email": "zont@pochta.ru"
}
],
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/gulp-usemin-0.3.23.tgz_1462364006265_0.13037881650961936"
},
"directories": {},
"publish_time": 1462364007542,
"_cnpm_publish_time": 1462364007542
}
================================================
FILE: lib/gulp-usemin/test/expected/app.js
================================================
var sample = 111;
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/array-js-attributes.html
================================================
<script src="/dist/index.js" seq="1" color="blue"></script>
<script src="/dist/index1.js" seq="2" color="red"></script>
<script src="/dist/index2.js" seq="1" color="yellow"></script>
<script src="/dist/index3.js" seq="3" color="pink"></script>
================================================
FILE: lib/gulp-usemin/test/expected/build-remove-no-trailing-whitespace.html
================================================
<div></div>
================================================
FILE: lib/gulp-usemin/test/expected/complex-path.html
================================================
<link rel="stylesheet" href="data/css/style.css"/>
<script src="/data/js/app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/complex.html
================================================
<link rel="stylesheet" href="style.css"/>
<script src="app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/conditional-complex.html
================================================
<!--[if IE 8]><link rel="stylesheet" href="style.css"/><![endif]-->
<!--[if lt IE 9]><script src="app.js"></script><![endif]-->
================================================
FILE: lib/gulp-usemin/test/expected/conditional-css.html
================================================
<!--[if lt IE 9]><link rel="stylesheet" href="/style.css"/><![endif]-->
================================================
FILE: lib/gulp-usemin/test/expected/conditional-inline-css.html
================================================
<!--[if lt IE 9]><style>* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}</style><![endif]-->
================================================
FILE: lib/gulp-usemin/test/expected/conditional-inline-js.html
================================================
<!--[if lt IE 9]><script>var sample = 111;
console.log(sample);</script><![endif]-->
================================================
FILE: lib/gulp-usemin/test/expected/conditional-js.html
================================================
<!--[if lt IE 9]><script src="app.js"></script><![endif]-->
================================================
FILE: lib/gulp-usemin/test/expected/data/css/min-style.css
================================================
*{margin:0;padding:0}body{margin:10px}
================================================
FILE: lib/gulp-usemin/test/expected/data/css/style.css
================================================
* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}
================================================
FILE: lib/gulp-usemin/test/expected/data/js/app.js
================================================
var sample = 111;
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/data/js/app_min_concat.js
================================================
var sample=111;
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/data/js/min-app.js
================================================
var sample=111;console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/glob-inline-css.html
================================================
<style>* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}</style>
================================================
FILE: lib/gulp-usemin/test/expected/glob-inline-js.html
================================================
<script>var sample = 111;
console.log(sample);</script>
================================================
FILE: lib/gulp-usemin/test/expected/many-blocks-removal.html
================================================
<link rel="stylesheet" href="data/css/style.css"><script src="/data/js/app1.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-app.js
================================================
var sample=111;console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/min-complex-path.html
================================================
<link rel=stylesheet href=data/css/style.css><script src=/data/js/app.js></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-complex.html
================================================
<link rel=stylesheet href=style.css><script src=app.js></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-css-with-media-query.html
================================================
<link rel=stylesheet href=/style.css media=screen>
================================================
FILE: lib/gulp-usemin/test/expected/min-html-simple-css.html
================================================
<link rel="stylesheet" href="/style.css"/>
================================================
FILE: lib/gulp-usemin/test/expected/min-html-simple-js.html
================================================
<script src="app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-html-simple-removal.html
================================================
================================================
FILE: lib/gulp-usemin/test/expected/min-paths-with-querystring.html
================================================
<link rel=stylesheet href=style.css><script src=app.js></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-simple-css-path.html
================================================
<link rel=stylesheet href=data/css/style.css>
================================================
FILE: lib/gulp-usemin/test/expected/min-simple-css.html
================================================
<link rel=stylesheet href=/style.css>
================================================
FILE: lib/gulp-usemin/test/expected/min-simple-js-path.html
================================================
<script src=data/js/app.js></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-simple-js.html
================================================
<script src=app.js></script>
================================================
FILE: lib/gulp-usemin/test/expected/min-style.css
================================================
*{margin:0;padding:0}body{margin:10px}
================================================
FILE: lib/gulp-usemin/test/expected/multiple-alternative-paths.html
================================================
<script src="data/js/app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/multiple-files.html
================================================
<link rel="stylesheet" href="data/css/style.css"/><link rel="stylesheet" href="data/css/style.css"/>
<script src="/data/js/app.js"></script><script src="/data/js/app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/paths-with-querystring.html
================================================
<link rel="stylesheet" href="style.css"/>
<script src="app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/simple-css-path.html
================================================
<link rel="stylesheet" href="data/css/style.css"/>
================================================
FILE: lib/gulp-usemin/test/expected/simple-css.html
================================================
<link rel="stylesheet" href="/style.css"/>
================================================
FILE: lib/gulp-usemin/test/expected/simple-inline-css.html
================================================
<style>* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}</style>
================================================
FILE: lib/gulp-usemin/test/expected/simple-inline-js.html
================================================
<script>var sample = 111;
console.log(sample);</script>
================================================
FILE: lib/gulp-usemin/test/expected/simple-js-path.html
================================================
<script src="data/js/app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/simple-js-removal.html
================================================
<div></div><div></div>
================================================
FILE: lib/gulp-usemin/test/expected/simple-js.html
================================================
<script src="app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/single-quotes-css.html
================================================
<link rel="stylesheet" href="data/css/style.css"/>
================================================
FILE: lib/gulp-usemin/test/expected/single-quotes-inline-css.html
================================================
<style>* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}</style>
================================================
FILE: lib/gulp-usemin/test/expected/single-quotes-inline-js.html
================================================
<script>var sample = 111;
console.log(sample);</script>
================================================
FILE: lib/gulp-usemin/test/expected/single-quotes-js.html
================================================
<script src="data/js/app.js"></script>
================================================
FILE: lib/gulp-usemin/test/expected/style.css
================================================
* {
margin: 0;
padding: 0;
}
body {
margin: 10px;
}
================================================
FILE: lib/gulp-usemin/test/expected/subfolder/app.js
================================================
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/expected/subfolder/index.html
================================================
<script src="app.js"></script>
================================================
FILE: lib/gulp-usemin/test/fixtures/alternative/js/util.js
================================================
alert(1);
================================================
FILE: lib/gulp-usemin/test/fixtures/array-js-attributes.html
================================================
<!--build:js /dist/index.js -->
<script src="js/lib.js"></script>
<!--endbuild-->
<!--build:js1 /dist/index1.js -->
<script src="js/main.js"></script>
<!--endbuild-->
<!--build:js2 /dist/index2.js -->
<script src="js2/lib2.js"></script>
<!--endbuild-->
<!--build:js3 /dist/index3.js -->
<script src="js2/main2.js"></script>
<!--endbuild-->
================================================
FILE: lib/gulp-usemin/test/fixtures/async-less.html
================================================
<!-- build:less /style.css -->
<link rel="stylesheet" href="less/clear.less"/>
<link rel="stylesheet" href="less/main.less"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/build-remove-no-trailing-whitespace.html
================================================
<div>
<!-- build:remove-->
<p>lorem ipsum</p>
<p>lorem ipsum</p>
<!-- endbuild-->
<!-- build:remove -->
<p>lorem ipsum</p>
<p>lorem ipsum</p>
<!-- endbuild-->
<!--build:remove-->
<p>lorem ipsum</p>
<p>lorem ipsum</p>
<!--endbuild-->
<!--build:remove -->
<p>lorem ipsum</p>
<p>lorem ipsum</p>
<!--endbuild-->
</div>
================================================
FILE: lib/gulp-usemin/test/fixtures/comment-js.html
================================================
<!-- build:js app.js -->
<!--
<script src="js/*.js"></script>
-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/complex-path.html
================================================
<!-- build:css data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:js /data/js/app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/complex.html
================================================
<!-- build:css style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:js app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/conditional-complex.html
================================================
<!-- build:css style.css -->
<!--[if IE 8]>
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<![endif]-->
<!-- endbuild -->
<!-- build:js app.js -->
<!--[if lt IE 9]>
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<![endif]-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/conditional-css.html
================================================
<!-- build:css /style.css -->
<!--[if lt IE 9]>
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<![endif]-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/conditional-inline-css.html
================================================
<!-- build:inlinecss -->
<!--[if lt IE 9]>
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<![endif]-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/conditional-inline-js.html
================================================
<!-- build:inlinejs -->
<!--[if lt IE 9]>
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<![endif]-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/conditional-js.html
================================================
<!-- build:js app.js -->
<!--[if lt IE 9]>
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<![endif]-->
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/css/clear.css
================================================
* {
margin: 0;
padding: 0;
}
================================================
FILE: lib/gulp-usemin/test/fixtures/css/main.css
================================================
body {
margin: 10px;
}
================================================
FILE: lib/gulp-usemin/test/fixtures/css-with-media-query-error.html
================================================
<!-- build:css /style.css -->
<link rel="stylesheet" href="css/clear.css" media="screen"/>
<link rel="stylesheet" href="css/main.css" media="print"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/css-with-media-query.html
================================================
<!-- build:css /style.css -->
<link rel="stylesheet" href="css/clear.css" media="screen"/>
<link rel="stylesheet" media="screen" href="css/main.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/glob-css.html
================================================
<!-- build:css /style.css -->
<link rel="stylesheet" href="css/*.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/glob-inline-css.html
================================================
<!-- build:inlinecss -->
<link rel="stylesheet" href="css/*.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/glob-inline-js.html
================================================
<!-- build:inlinejs -->
<script src="js/*.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/glob-js.html
================================================
<!-- build:js app.js -->
<script src="js/*.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/js/lib.js
================================================
var sample = 111;
================================================
FILE: lib/gulp-usemin/test/fixtures/js/main.js
================================================
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/fixtures/js2/lib2.js
================================================
var sample = 111;
================================================
FILE: lib/gulp-usemin/test/fixtures/js2/main2.js
================================================
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/fixtures/less/clear.less
================================================
@zero: 0;
* {
margin: @zero;
padding: @zero;
}
================================================
FILE: lib/gulp-usemin/test/fixtures/less/main.less
================================================
body {
margin: 10px;
}
================================================
FILE: lib/gulp-usemin/test/fixtures/many-blocks-removal.html
================================================
<!-- build:css1 data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:remove -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
<!-- build:js1 /data/js/app1.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/many-blocks.html
================================================
<!-- build:css1 data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:js /data/js/app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
<!-- build:js1 /data/js/app1.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
<!-- build:js1 /data/js/app2.js -->
<script src="js2/lib2.js"></script>
<script src="js2/main2.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/min-html-simple-css.html
================================================
<!-- build:css /style.css --><link rel="stylesheet" href="css/clear.css"/><link rel="stylesheet" href="css/main.css"/><!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/min-html-simple-js.html
================================================
<!-- build:js app.js --><script src="js/lib.js"></script><script src="js/main.js"></script><!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/min-html-simple-removal.html
================================================
<!-- build:remove --><script src="js/lib.js"></script><script src="js/main.js"></script><!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/multiple-alternative-paths-inline.html
================================================
<!-- build:inlinejs(test/fixtures{,/alternative}) -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<script src="js/util.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/multiple-alternative-paths.html
================================================
<!-- build:js(test/fixtures{,/alternative}) data/js/app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<script src="js/util.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/multiple-files.html
================================================
<!-- build:css data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
<!-- build:js /data/js/app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/paths-with-querystring.html
================================================
<!-- build:css style.css -->
<link rel="stylesheet" href="css/clear.css?v=1"/>
<link rel="stylesheet" href="css/main.css?v=2"/>
<!-- endbuild -->
<!-- build:js app.js -->
<script src="js/lib.js?v=1"></script>
<script src="js/main.js?v=2"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-css-alternate-path.html
================================================
<!-- build:css(test/fixtures) data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-css-path.html
================================================
<!-- build:css data/css/style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link href=css/main.css rel="stylesheet"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-css.html
================================================
<!-- build:css /style.css -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-inline-css.html
================================================
<!-- build:inlinecss -->
<link rel="stylesheet" href="css/clear.css"/>
<link rel="stylesheet" href="css/main.css"/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-inline-js.html
================================================
<!-- build:inlinejs -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-js-alternate-path.html
================================================
<!-- build:js(test/fixtures/) data/js/app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-js-path.html
================================================
<!-- build:js data/js/app.js -->
<script src="js/lib.js"></script>
<script src=js/main.js></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-js-removal.html
================================================
<div></div>
<!-- build:remove -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
<div></div>
================================================
FILE: lib/gulp-usemin/test/fixtures/simple-js.html
================================================
<!-- build:js app.js -->
<script src="js/lib.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/single-quotes-css.html
================================================
<!-- build:css data/css/style.css -->
<link rel='stylesheet' href='css/clear.css'/>
<link rel='stylesheet' href='css/main.css'/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/single-quotes-inline-css.html
================================================
<!-- build:inlinecss -->
<link rel='stylesheet' href='css/clear.css'/>
<link rel='stylesheet' href='css/main.css'/>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/single-quotes-inline-js.html
================================================
<!-- build:inlinejs -->
<script src='js/lib.js'></script>
<script src='js/main.js'></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/single-quotes-js.html
================================================
<!-- build:js data/js/app.js -->
<script src='js/lib.js'></script>
<script src='js/main.js'></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/subfolder/index.html
================================================
<!-- build:js app.js -->
<script src="script.js"></script>
<!-- endbuild -->
================================================
FILE: lib/gulp-usemin/test/fixtures/subfolder/script.js
================================================
console.log(sample);
================================================
FILE: lib/gulp-usemin/test/main.js
================================================
/* jshint node: true */
/* global describe, it */
'use strict';
var assert = require('assert');
var fs = require('fs');
var gutil = require('gulp-util');
var PassThrough = require('stream').PassThrough;
var path = require('path');
var usemin = require('../index');
var vfs = require('vinyl-fs');
function getFile(filePath) {
return new gutil.File({
path: filePath,
base: path.dirname(filePath),
contents: fs.readFileSync(filePath)
});
}
function getFixture(filePath) {
return getFile(path.join('test', 'fixtures', filePath));
}
function getExpected(filePath) {
return getFile(path.join('test', 'expected', filePath));
}
describe('gulp-usemin', function() {
describe('allow removal sections', function() {
function compare(name, expectedName, done) {
var htmlmin = require('gulp-minify-html');
var stream = usemin({html: [htmlmin({empty: true, quotes: true})]});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.write(getFixture(name));
}
it('simple js block', function(done) {
compare('simple-js-removal.html', 'simple-js-removal.html', done);
});
it('minified js block', function(done) {
compare('min-html-simple-removal.html', 'min-html-simple-removal.html', done);
});
it('many blocks', function(done) {
compare('many-blocks-removal.html', 'many-blocks-removal.html', done);
});
it('robust pattern recognition (no whitespace after build:remove)', function(done) {
compare('build-remove-no-trailing-whitespace.html', 'build-remove-no-trailing-whitespace.html', done);
});
});
describe('negative test:', function() {
it('shouldn\'t work in stream mode', function(done) {
var stream = usemin();
var t;
var fakeStream = new PassThrough();
var fakeFile = new gutil.File({
contents: fakeStream
});
fakeStream.end();
stream.on('error', function() {
clearTimeout(t);
done();
});
t = setTimeout(function() {
assert.fail('', '', 'Should throw error', '');
done();
}, 1000);
stream.write(fakeFile);
});
it('html without blocks', function(done) {
var stream = usemin();
var content = '<div>content</div>';
var fakeFile = new gutil.File({
path: 'test.file',
contents: new Buffer(content)
});
stream.on('data', function(newFile) {
assert.equal(content, String(newFile.contents));
done();
});
stream.write(fakeFile);
});
});
describe('should work in buffer mode with', function() {
describe('minified HTML:', function() {
function compare(name, expectedName, done, fail) {
var htmlmin = require('gulp-minify-html');
var stream = usemin({
html: [function() {
return htmlmin({empty: true});
}]
});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.on('error', function() {
if (fail)
fail();
});
stream.write(getFixture(name));
}
it('simple js block', function(done) {
compare('simple-js.html', 'min-simple-js.html', done);
});
it('simple js block with path', function(done) {
compare('simple-js-path.html', 'min-simple-js-path.html', done);
});
it('simple css block', function(done) {
compare('simple-css.html', 'min-simple-css.html', done);
});
it('css block with media query', function(done) {
compare('css-with-media-query.html', 'min-css-with-media-query.html', done);
});
it('css block with mixed incompatible media queries should error', function(done) {
compare('css-with-media-query-error.html', 'min-css-with-media-query.html', function() {
assert.fail('', '', 'should error', '');
done();
}, done);
});
it('simple css block with path', function(done) {
compare('simple-css-path.html', 'min-simple-css-path.html', done);
});
it('complex (css + js)', function(done) {
compare('complex.html', 'min-complex.html', done);
});
it('complex with path (css + js)', function(done) {
compare('complex-path.html', 'min-complex-path.html', done);
});
it('paths with querystring', function(done) {
compare('paths-with-querystring.html', 'min-paths-with-querystring.html', done);
});
});
describe('not minified HTML:', function() {
function compare(name, expectedName, done) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.write(getFixture(name));
}
it('simple js block with single quotes', function (done) {
compare('single-quotes-js.html', 'single-quotes-js.html', done);
});
it('simple css block with single quotes', function (done) {
compare('single-quotes-css.html', 'single-quotes-css.html', done);
});
it('simple (js block)', function(done) {
compare('simple-js.html', 'simple-js.html', done);
});
it('simple (js block) (html minified)', function(done) {
compare('min-html-simple-js.html', 'min-html-simple-js.html', done);
});
it('simple with path (js block)', function(done) {
compare('simple-js-path.html', 'simple-js-path.html', done);
});
it('simple (css block)', function(done) {
compare('simple-css.html', 'simple-css.html', done);
});
it('simple (css block) (html minified)', function(done) {
compare('min-html-simple-css.html', 'min-html-simple-css.html', done);
});
it('simple with path (css block)', function(done) {
compare('simple-css-path.html', 'simple-css-path.html', done);
});
it('complex (css + js)', function(done) {
compare('complex.html', 'complex.html', done);
});
it('complex with path (css + js)', function(done) {
compare('complex-path.html', 'complex-path.html', done);
});
it('multiple alternative paths', function(done) {
compare('multiple-alternative-paths.html', 'multiple-alternative-paths.html', done);
});
it('paths with querystring', function(done) {
compare('paths-with-querystring.html', 'paths-with-querystring.html', done);
});
});
describe('minified CSS:', function() {
function compare(fixtureName, name, expectedName, end) {
var cssmin = require('gulp-minify-css');
var stream = usemin({css: ['concat', cssmin()]});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('simple (css block)', function(done) {
var name = 'style.css';
var expectedName = 'min-style.css';
compare('simple-css.html', name, expectedName, done);
});
it('simple with path (css block)', function(done) {
var name = 'style.css';
var expectedName = path.join('data', 'css', 'min-style.css');
compare('simple-css-path.html', name, expectedName, done);
});
it('simple with alternate path (css block)', function(done) {
var name = 'style.css';
var expectedName = path.join('data', 'css', 'min-style.css');
compare('simple-css-alternate-path.html', name, expectedName, done);
});
});
describe('not minified CSS:', function() {
function compare(fixtureName, expectedName, end) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(expectedName)) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('simple (css block)', function(done) {
compare('simple-css.html', 'style.css', done);
});
it('simple (css block) (minified html)', function(done) {
compare('min-html-simple-css.html', 'style.css', done);
});
it('simple with path (css block)', function(done) {
compare('simple-css-path.html', path.join('data', 'css', 'style.css'), done);
});
it('simple with alternate path (css block)', function(done) {
compare('simple-css-alternate-path.html', path.join('data', 'css', 'style.css'), done);
});
});
describe('minified JS:', function() {
function compare(fixtureName, name, expectedName, end) {
var jsmin = require('gulp-uglify');
var stream = usemin({js: [jsmin()]});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(name)) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('simple (js block)', function(done) {
compare('simple-js.html', 'app.js', 'min-app.js', done);
});
it('simple with path (js block)', function(done) {
var name = path.join('data', 'js', 'app.js');
var expectedName = path.join('data', 'js', 'min-app.js');
compare('simple-js-path.html', name, expectedName, done);
});
it('simple with alternate path (js block)', function(done) {
var name = path.join('data', 'js', 'app.js');
var expectedName = path.join('data', 'js', 'min-app.js');
compare('simple-js-alternate-path.html', name, expectedName, done);
});
});
describe('not minified JS:', function() {
function compare(fixtureName, expectedName, end) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(expectedName)) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('simple (js block)', function(done) {
compare('simple-js.html', 'app.js', done);
});
it('simple (js block) (minified html)', function(done) {
compare('min-html-simple-js.html', 'app.js', done);
});
it('simple with path (js block)', function(done) {
compare('simple-js-path.html', path.join('data', 'js', 'app.js'), done);
});
it('simple with alternate path (js block)', function(done) {
compare('simple-js-alternate-path.html', path.join('data', 'js', 'app.js'), done);
});
});
it('many html files', function(done) {
var cssmin = require('gulp-minify-css');
var jsmin = require('gulp-uglify');
var rev = require('gulp-rev');
var stream = usemin({
css: ['concat', cssmin],
js: ['concat', jsmin]
});
var nameCss = 'style.css';
var expectedNameCss = 'min-style.css';
var nameJs = 'app.js';
var expectedNameJs = 'min-app.js';
var cssExist = false;
var jsExist = false;
var htmlCount = 0;
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(nameCss)) {
cssExist = true;
assert.equal(String(getExpected(expectedNameCss).contents), String(newFile.contents));
}
else if (path.basename(newFile.path) === path.basename(nameJs)) {
jsExist = true;
assert.equal(String(getExpected(expectedNameJs).contents), String(newFile.contents));
}
else {
htmlCount += 1;
}
});
stream.on('end', function() {
assert.equal(htmlCount, 2);
assert.ok(cssExist);
assert.ok(jsExist);
done();
});
stream.write(getFixture('simple-css.html'));
stream.write(getFixture('simple-js.html'));
stream.end();
});
it('many blocks', function(done) {
var cssmin = require('gulp-minify-css');
var jsmin = require('gulp-uglify');
var rev = require('gulp-rev');
var stream = usemin({
css1: ['concat', cssmin],
js1: [jsmin, 'concat', rev]
});
var nameCss = path.join('data', 'css', 'style.css');
var expectedNameCss = path.join('data', 'css', 'min-style.css');
var nameJs = path.join('data', 'js', 'app.js');
var expectedNameJs = path.join('data', 'js', 'app.js');
var nameJs1 = 'app1';
var expectedNameJs1 = path.join('data', 'js', 'app_min_concat.js');
var nameJs2 = 'app2';
var expectedNameJs2 = path.join('data', 'js', 'app_min_concat.js');
var cssExist = false;
var jsExist = false;
var js1Exist = false;
var js2Exist = false;
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(nameCss)) {
cssExist = true;
assert.equal(String(getExpected(expectedNameCss).contents), String(newFile.contents));
}
else if (path.basename(newFile.path) === path.basename(nameJs)) {
jsExist = true;
assert.equal(String(getExpected(expectedNameJs).contents), String(newFile.contents));
}
else if (newFile.path.indexOf(nameJs1) != -1) {
js1Exist = true;
assert.equal(String(getExpected(expectedNameJs1).contents), String(newFile.contents));
}
else if (newFile.path.indexOf(nameJs2) != -1) {
js2Exist = true;
assert.equal(String(getExpected(expectedNameJs2).contents), String(newFile.contents));
}
else {
assert.ok(cssExist);
assert.ok(jsExist);
assert.ok(js1Exist);
assert.ok(js2Exist);
done();
}
});
stream.write(getFixture('many-blocks.html'));
});
describe('assetsDir option:', function() {
function compare(assetsDir, done) {
var stream = usemin({assetsDir: assetsDir});
var expectedName = 'style.css';
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === expectedName) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.write(getFixture('simple-css.html'));
}
it('absolute path', function(done) {
compare(path.join(process.cwd(), 'test', 'fixtures'), done);
});
it('relative path', function(done) {
compare(path.join('test', 'fixtures'), done);
});
});
describe('conditional comments:', function() {
function compare(name, expectedName, done) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.write(getFixture(name));
}
it('conditional (js block)', function(done) {
compare('conditional-js.html', 'conditional-js.html', done);
});
it('conditional (css block)', function(done) {
compare('conditional-css.html', 'conditional-css.html', done);
});
it('conditional (css + js)', function(done) {
compare('conditional-complex.html', 'conditional-complex.html', done);
});
it('conditional (inline js block)', function(done) {
compare('conditional-inline-js.html', 'conditional-inline-js.html', done);
});
it('conditional (inline css block)', function(done) {
compare('conditional-inline-css.html', 'conditional-inline-css.html', done);
});
});
describe('globbed files:', function() {
function compare(fixtureName, name, end) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(newFile.contents), String(getExpected(name).contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('glob (js block)', function(done) {
compare('glob-js.html', 'app.js', done);
});
it('glob (css block)', function(done) {
compare('glob-css.html', 'style.css', done);
});
it('glob inline (js block)', function(done) {
compare('glob-inline-js.html', 'glob-inline-js.html', done);
});
it('glob inline (css block)', function(done) {
compare('glob-inline-css.html', 'glob-inline-css.html', done);
});
});
describe('comment files:', function() {
function compare(name, callback) {
var stream = usemin({enableHtmlComment: true});
stream.on('data', callback);
stream.write(getFixture(name));
}
it('comment (js block)', function(done) {
var expectedName = 'app.js';
compare(
'comment-js.html',
function(newFile) {
if (path.basename(newFile.path) === expectedName) {
assert.equal(String(newFile.contents), String(getExpected(expectedName).contents));
done();
}
}
);
});
});
describe('inline Sources:', function() {
function compare(fixtureName, name, end) {
var stream = usemin();
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(newFile.contents), String(getExpected(name).contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('simple inline js block', function (done) {
compare('simple-inline-js.html', 'simple-inline-js.html', done);
});
it('simple inline css block', function (done) {
compare('simple-inline-css.html', 'simple-inline-css.html', done);
});
it('simple inline js block width single quotes', function (done) {
compare('single-quotes-inline-js.html', 'single-quotes-inline-js.html', done);
});
it('simple inline css block with single quotes', function (done) {
compare('single-quotes-inline-css.html', 'single-quotes-inline-css.html', done);
});
});
describe('array jsAttributes:', function() {
function compare(fixtureName, name, end) {
var stream = usemin({
jsAttributes: {
seq: [1, 2, 1, 3],
color: ['blue', 'red', 'yellow', 'pink']
},
js: [],
js1: [],
js2: [],
js3: []
});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === name) {
assert.equal(String(newFile.contents), String(getExpected(name).contents));
end();
}
});
stream.write(getFixture(fixtureName));
}
it('js attributes with array define', function (done) {
compare('array-js-attributes.html', 'array-js-attributes.html', done);
});
});
it('async task', function(done) {
var less = require('gulp-less');
var cssmin = require('gulp-minify-css');
var stream = usemin({
less: [less(), 'concat', cssmin()]
});
var name = 'style.css';
var expectedName = 'min-style.css';
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(name)) {
assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
done();
}
});
stream.write(getFixture('async-less.html'));
});
it('subfolders', function(done) {
var stream = usemin();
var jsExist = false;
var nameJs = path.join('subfolder', 'app.js');
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename(nameJs)) {
jsExist = true;
assert.equal(path.relative(newFile.base, newFile.path), nameJs);
assert.equal(String(getExpected(nameJs).contents), String(newFile.contents));
}
else {
assert.ok(jsExist);
done();
}
});
vfs.src('test/fixtures/**/index.html')
.pipe(stream);
});
});
it('multiple files in stream', function(done) {
var multipleFiles = function() {
var through = require('through2');
var File = gutil.File;
return through.obj(function(file) {
var stream = this;
stream.push(new File({
cwd: file.cwd,
base: file.base,
path: file.path,
contents: new Buffer('test1')
}));
stream.push(new File({
cwd: file.cwd,
base: file.base,
path: file.path,
contents: new Buffer('test2')
}));
});
};
var stream = usemin({
css: [multipleFiles],
js: [multipleFiles]
});
stream.on('data', function(newFile) {
if (path.basename(newFile.path) === path.basename('multiple-files.html')) {
assert.equal(String(getExpected('multiple-files.html').contents), String(newFile.contents));
done();
}
});
stream.write(getFixture('multiple-files.html'));
});
});
================================================
FILE: lib/htmlPathParser.js
================================================
/**
* FOR PARSE HTML REF PATH
*/
'use strict'
var through = require('through2'),
path = require('path'),
j = path.join,
// gulpman utils
gmutil = require('./gmutil')
function _dealHTML(conf){
let _opts = conf['_opts'],
basepath = conf['basepath'],
_isRuntimeDir = conf['_isRuntimeDir'],
all_raw_source_reg = conf['all_raw_source_reg']
return through.obj(function (file, enc, cb){
if (file.isNull()) {
this.push(file);
return cb()
}
if (file.isStream()) {
gmutil.error('*ParseHtml Error: Streaming not supported')
return cb()
}
let contents = file.contents.toString()
// file.relative 是根据path.base自动生成的
if(basepath) file.base = basepath
let fdirname = path.dirname(file.relative)
// set assets url prefix
let _urlPrefix
if(_opts['is_absolute']) {
_urlPrefix = _opts['url_prefix']
}else {
// 判断打包资源中的url路径前缀
let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname)
let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static']
_urlPrefix = path.relative(_fPath, _staticPath)
}
// 所有格式都要处理
let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm')
// httpReg = /^http(s)?\:/
let tmp_rs_list = [],
rs_list = []
// 提取单标签和双标签
tmp_rs_list = tmp_rs_list
.concat(contents.match(gmutil.reg['tagMedia']))
.concat(contents.match(gmutil.reg['closeTagMedia']))
// 首先提取标签,然后从标签中提取href或者src
tmp_rs_list.length && (
rs_list = tmp_rs_list
.filter(r=>(r && r.match(srcQuoteReg)))
.map(v=>v.match(srcQuoteReg)[0])
.filter(r=>{
// remove the http:xxx.com/xx and base64 data url
// 只处理相对路径
// 不处理绝对路径、http、dataURL
return gmutil.isUrl('relative', r)
})
.filter(r=>!r.match(/^(['"]\/)/gm))
)
// 这里利用set做去重
let rs_set = new Set(rs_list),
srcPrefix = j(_urlPrefix, fdirname)
// 替换url的的path和前缀
rs_set.size && rs_set.forEach(epath=>{
// 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64
let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm')
contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2')
})
// dealing with usemin build mark syntax
// when in publish, not runtime-dir
if(!_isRuntimeDir) {
// 这里处理usemin 的build的注释内容
contents = gmutil.replaceBuildBlock(contents, srcPrefix)
}
file.contents = new Buffer(contents)
gmutil.tip('*Raw HTML File Parsed: '+file.relative)
this.push(file)
cb()
})
}
module.exports = _dealHTML
================================================
FILE: lib/iconFonter.js
================================================
// Copyright (c) 2015 App Annie Inc. All rights reserved.
'use strict';
var path = require('path'),
j = path.join;
var sh = require("shelljs")
var fontName = 'gmicon';
function registerTask(gulp, opts) {
var runTimestamp = Math.round(Date.now() / 1000);
if(!opts['iconfont']) {
opts['iconfont'] = {
}
}
var _iconConf = opts['iconfont'];
var svgSource = _iconConf['source'] || j(opts['components'], 'iconfonts/source')
var iconPath = _iconConf['icon'] || j(opts['components'], 'iconfonts', fontName)
// var iconCSSPath = _iconConf['css'] || j(opts['components'], 'iconfonts')
var svgSource = j(svgSource, '/*.svg');
gulp.task('gm:iconfont', function() {
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
return gulp.src(svgSource)
.pipe(iconfontCss({
fontName: fontName,
// path: 'app/assets/css/templates/_icons.scss',
targetPath: 'gmicon.css',
fontPath: './',
cssClass: 'gmicon'
}))
.pipe(iconfont({
fontName: fontName, // required
formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
normalize: true,
fontHeight: 500,
timestamp: runTimestamp // recommended to get consistent builds when watching files
}))
.pipe(gulp.dest(iconPath))
});
}
exports.registerTask = registerTask;
================================================
FILE: lib/inline.js
================================================
/**
* Created by Rodey on 2015/11/5.
*/
var fs = require('fs'),
path = require('path'),
through2 = require('through2'),
uglifycss = require('uglifycss'),
jsmin = require('jsmin2'),
PluginError = require('gulp-util').PluginError,
gmutil = require('./gmutil'),
store = require('./store')
var PLUGIN_NAME = 'gulp-html-inline';
var linkRegx = new RegExp('<link\\s+[\\s\\S]*?>[\\s\\S]*?<*\\/*>*', 'gi'),
hrefRegx = new RegExp('\\s*(href)="+([\\s\\S]*?)"'),
styleRegx = new RegExp('<style\\s*[\\s\\S]*?>[\\s\\S]*?<\\/style>', 'gi'),
jsRegx = new RegExp('<script\\s+[\\s\\S]*?>[\\s\\S]*?<\\/script>', 'gi'),
scriptRegx = new RegExp('<script\\s*[\\s\\S]*?>[\\s\\S]*?<\\/script>', 'gi'),
srcRegx = new RegExp('\\s*(src)="+([\\s\\S]*?)"');
var joint = function(tag, content){
return '<'+ tag +'>' + content + '</'+ tag +'>';
};
// add for gulpman
var _file;
/**
* 获取get模式下url中的指定参数值
* @param name 参数名
* @param url 传入的url地址
* @returns {*}
*/
var getParams = function(name, url) {
var reg = new RegExp('(^|&)' + name + '=?([^&]*)(&|$)', 'i'), search = '';
if(url && url !== ''){
search = (url.split('?')[1] || '').match(reg);
}else{
search = window.location.search.substr(1).match(reg);
}
if(search && search[0].indexOf(name) !== -1) {
return search[2] ? decodeURI(search[2]) : null;
}
};
//压缩内联css代码 | js脚本
var miniInline = function(content, type, options){
var isMinifyCss = options && !!options.minifyCss,
isMinifyJs = options && !!options.minifyJs,
ignore = options['ignore'] || 'ignore',
basePath = options['basePath'] || '',
queryKey = options['queryKey'] || '_gm_inline',
queryRegx = new RegExp('&*'+ queryKey +'[=|&]?', 'i'),
code = content,
tags;
tags = content.match(/<[\s\S]*?<*\/*[\s\S]*?>/gi);
if(tags && tags[0] && tags[0].indexOf(ignore) !== -1)
return content;
if('css' === type){
if(!isMinifyCss) return content;
code = uglifycss.processString(content, options);
}
else if('js' === type){
if(!isMinifyJs) return content;
/**
* FIX BUGS FOR replace
*/
// gmutil.alert('content: \n'+content)
// gmutil.alert('opts: \n'+JSON.stringify(options))
var pt = /(?=['"]?)([\w\/\-\?\&\=]*?\.js)(?=['"]?)/gm,
item
// 如果没有标记inline,那么不处理
if((item = content.match(pt)) && (item = item[0])){
if(!item.match(queryRegx)) return content
}
// gmutil.alert(jsmin(content, options).code)
code = jsmin(content, options).code.replace(/\n*\t*/gi, '');
}
return code;
};
//replace callback src | href
var replaceCallback = function(sourceRegx, match, parentFile, type, options){
var ms = sourceRegx.exec(match),
code = '',
query,
isMinifyCss = options && !!options.minifyCss,
isMinifyJs = options && !!options.minifyJs,
ignore = options['ignore'] || 'ignore',
basePath = options['basePath'] || '',
queryKey = options['queryKey'] || '_gm_inline',
queryRegx = new RegExp('&*'+ queryKey +'[=|&]?', 'i');
if(!ms || !ms[2] || '' === ms[2]){
return miniInline(match, type, options);
}
var attr = ms[1] || '',
href = ms[2] || '';
if(match.indexOf(ignore) !== -1)
return match.replace(queryRegx, '');
//在url地址上加上 _gm_inline_字段就可以直接嵌入网页
query = getParams(queryKey, href);
if(query === undefined){
return match.replace(queryRegx, '');
}
// 如果使用绝对路径
if(options['absoluteRoot']){
var sourceFile = path.join(options['root'], options['absoluteRoot'], href.split('?')[0])
}else {
var sourceFile = path.normalize(path.dirname(parentFile) + path.sep + basePath + href.split('?')[0])
}
if(!options['is_runtime']){
var url_runtime_dir = path.join(options['root'], options['runtime_dir']),
url_dist_dir = path.join(options['root'], options['dist_dir']),
sourceFile = sourceFile.replace(url_dist_dir, url_runtime_dir)
}
// remove the url prefix for once
// the url is abs url
sourceFile = sourceFile.replace(options['url_prefix'], '')
if(!fs.existsSync(sourceFile)){
gmutil.error('\n*Error: \n*Inline File Not Exist: '+sourceFile+'\n')
return match;
}
content = getFileContent(sourceFile);
// add for gulpman store save
store.save(sourceFile, _file.path)
if('css' === type){
if(!isMinifyCss)
return joint('style', content);
code = uglifycss.processString(content, options);
code = joint('style', code);
}
else if('js' === type){
if(!isMinifyJs)
return joint('script', content);
code = jsmin(content, options).code.replace(/\n*\t*/gi, '');
code = joint('script', code);
}
return code;
};
//根据标签类型获取内容并压缩
var execture = function(file, options){
var parentFile = path.normalize(file.path);
var fileContents = file.contents.toString('utf8');
if(typeof fileContents === 'undefined'){
fileContents = getFileContent(file.path);
}
// get the single tag replace-content (mined)
var content = fileContents
.replace(linkRegx, function($1){
//like: <link rel="stylesheet" href="assets/css/a.css" />
return replaceCallback(hrefRegx, $1, parentFile, 'css', options);
}).replace(jsRegx, function($1){
//like: <script src="assets/js/a.js"></script>
return replaceCallback(srcRegx, $1, parentFile, 'js', options);
}).replace(styleRegx, function($1){
//like:
// <style ignore>
// #app{
// width: 80%;
// padding: 10px;
// }
// </style>
//console.log($1);
return miniInline($1, 'css', options);
}).replace(scriptRegx, function($1){
//like:
// <script ignore>
// var a = 0,
// b = 0;
// var arr = [];
// arr.push(a);
// arr.push(b);
// </script>
/**
* @debug for replace bug
* this trigger the src with type joined together
* lead into miniInline
*/
return miniInline($1, 'js', options);
});
return content;
};
//get the content of files
var getFileContent = function(file){
if(!fs.existsSync(file)) throw new Error('File not find: ' + file);
var fileContent = fs.readFileSync(file, { encoding: 'utf8' });
return fileContent;
//file.contents = new Buffer(uglifycss.processString(fileContent, options));
};
//get the mined files content
var getContent = function(file, options){
var content = execture(file, options);
return content;
};
//将压缩后的内容替换到html中
var inline = function(options){
var options = options || {},
basePath = options.basePath;
//是否压缩css, 默认压缩
options.minifyCss = 'undefined' === typeof(options.minifyCss) ? true : options.minifyCss;
//是否压缩js, 默认压缩
options.minifyJs = 'undefined' === typeof(options.minifyJs) ? true : options.minifyJs;
return through2.obj(function(file, enc, next){
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Stream content is not supported'));
return next(null, file);
}
_file = file
if (file.isBuffer()) {
try {
var content = getContent(file, options);
file.contents = new Buffer(content);
}
catch (err) {
this.emit('error', new PluginError(PLUGIN_NAME, err['message']));
}
}
this.push(file);
return next();
});
};
module.exports = inline;
================================================
FILE: lib/revReplace.js
================================================
'use strict';
var path = require('path');
var gutil = require('gulp-util');
var through = require('through2');
var gmutil = require('./gmutil');
function plugin(options) {
var renames = [];
var cache = [];
options = options || {};
if (!options.canonicalUris) {
options.canonicalUris = true;
}
options.replaceInExtensions = options.replaceInExtensions || ['.js', '.css', '.html', '.hbs'];
// @debug add for gulpman
options.prefix = options.prefix || '';
options['_prefix'] = options['prefix']
options['_all_prefix'] = new Set()
var _url_prefix = options['url_prefix']
// @add prefix array and fn support
// @Lucas
if(typeof options.prefix == 'string'){
options['_all_prefix'].add(options.prefix)
}else if(options.prefix instanceof Array){
// 虽然在gulpman/index中已经做了proxy,但是目前注释掉这块,会导致/http://xx的问题,需要处理下
Object.defineProperty(options, 'prefix',{
get: function () {
var p = this['_prefix'][gmutil.randomNum(0, options['_prefix'].length-1)]
options['_all_prefix'].add(p)
return p
},
set : function (val) {
this['_prefix'] = val
},
configurable : true
})
// if the param is a function
}else if(options.prefix instanceof Function){
Object.defineProperty(options, 'prefix',{
get: function () {
var p = this['_prefix'](options['_tmpMediaFilePath'], options['_tmpMediaFilePath'])
options['_all_prefix'].add(p)
return p;
},
set : function (val) {
this['_prefix'] = val
},
configurable : true
})
}else {
// default
}
return through.obj(function collectRevs(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-rev-replace', 'Streaming not supported'));
return cb();
}
// 此处file是宿主文件
options['_file'] = file
// Collect renames from reved files.
if (file.revOrigPath) {
// @add for gulpman hooks
options['_tmpHostFilePath'] = file.path
var mediaFilePath = fmtPath(file.revOrigBase, file.revOrigPath)
// media file ,js css,egg.
options['_tmpMediaFilePath'] = mediaFilePath
// 此处触发一次运行函数
var availablePrefix = options.prefix
renames.push({
unreved: mediaFilePath,
reved: availablePrefix + fmtPath(file.base, file.path)
});
}
if (options.replaceInExtensions.indexOf(path.extname(file.path)) > -1) {
// file should be searched for replaces
cache.push(file);
} else {
// nothing to do with this file
this.push(file);
}
cb();
}, function replaceInFiles(cb) {
var stream = this;
if (options.manifest) {
// Read manifest file for the list of renames.
options.manifest.on('data', function (file) {
var manifest = JSON.parse(file.contents.toString());
Object.keys(manifest).forEach(function (srcFile) {
// @add for gulpman hooks
var unrevedFilePath = canonicalizeUri(srcFile)
//if want delete source file, can do delete here
options['_tmpMediaFilePath'] = unrevedFilePath
if(options['_file']){
options['_tmpHostFilePath'] = options['_file'].path
}
// 此处每次get prefix,都会运行一次产生函数,每次结果可能不同
var availablePrefix = options.prefix
renames.push({
unreved: unrevedFilePath,
reved: availablePrefix + canonicalizeUri(manifest[srcFile])
});
});
});
options.manifest.on('end', replaceContents);
}
else {
replaceContents();
}
function replaceContents() {
renames = renames.sort(gmutil.byLongestUnreved);
// Once we have a full list of renames, search/replace in the cached
// files and push them through.
cache.forEach(function replaceInFile(file) {
var contents = file.contents.toString();
renames.forEach(function replaceOnce(rename) {
var unreved = options.modifyUnreved ? options.modifyUnreved(rename.unreved) : rename.unreved;
var reved = options.modifyReved ? options.modifyReved(rename.reved) : rename.reved;
contents = contents.split(unreved).join(reved);
options['_all_prefix'].size && options['_all_prefix'].forEach((availablePrefix)=>{
// add for gulpman hooks
// 这块需要遍历所有prefix,每次prefix可能会变,导致替换失败
if (availablePrefix) {
var _tmp_full_url_prefix = _url_prefix + '/'+ availablePrefix;
var _full_url_prefix = gmutil.joinUrl(availablePrefix, _url_prefix);
contents = contents.split(_tmp_full_url_prefix).join(_full_url_prefix)
}
})
});
file.contents = new Buffer(contents);
stream.push(file);
});
cb();
}
});
function fmtPath(base, filePath) {
var newPath = path.relative(base, filePath);
return canonicalizeUri(newPath);
}
// 标准化url
function canonicalizeUri(filePath) {
if (path.sep !== '/' && options.canonicalUris) {
filePath = filePath.split(path.sep).join('/');
}
return filePath;
}
}
/**
* Export API
* @type {[type]}
*/
module.exports = plugin;
================================================
FILE: lib/spriter/README.md
================================================
[](http://badge.fury.io/js/gulp-css-spriter)
# gulp-css-spriter
`gulp-css-spriter`, a [gulp](http://gulpjs.com/) plugin, looks through the CSS you pipe in and gathers all of the background images. It then creates a sprite sheet and updates the references in the CSS.
You can easily exclude/include certain background image declarations using meta info in your styles([*see meta section below*](#meta-options)) and `includeMode` option([*see options section below*](#options)) depending on your use case.
# Install
### Latest Version: 0.3.3
`npm install gulp-css-spriter`
# About
`gulp-css-spriter` uses [spritesmith](https://www.npmjs.com/package/spritesmith) behind the scenes for creating the sprite sheet.
# Usage
## Basic usage
This is most likely the setup you will probably end up using.
```
var gulp = require('gulp');
var spriter = require('gulp-css-spriter');
gulp.task('css', function() {
return gulp.src('./src/css/styles.css')
.pipe(spriter({
// The path and file name of where we will save the sprite sheet
'spriteSheet': './dist/images/spritesheet.png',
// Because we don't know where you will end up saving the CSS file at this point in the pipe,
// we need a litle help identifying where it will be.
'pathToSpriteSheetFromCSS': '../images/spritesheet.png'
}))
.pipe(gulp.dest('./dist/css'));
});
```
## Barebones usage
The slimmest usage possible.
```
var gulp = require('gulp');
var spriter = require('gulp-css-spriter');
gulp.task('css', function() {
return gulp.src('./styles.css')
.pipe(spriter())
.pipe(gulp.dest('./'));
});
```
## Minify CSS output usage
If you want to use [@meta data](#meta-options) but are using a preprocessor such as Sass or Less, you will need to use a output style that doesn't strip comments. After piping the CSS through `gulp-css-spriter`, you can then run it through a CSS minifier(separate plugin), such as [`gulp-minify-css`](https://www.npmjs.com/package/gulp-minify-css).
```
var gulp = require('gulp');
var spriter = require('gulp-css-spriter');
var minifyCSS = require('gulp-minify-css'); // https://www.npmjs.com/package/gulp-minify-css
gulp.task('css', function() {
return gulp.src('./styles.css')
.pipe(spriter())
.pipe(minifyCSS())
.pipe(gulp.dest('./'));
});
```
# Options
- `options`: object - hash of options
- `includeMode`: string - Determines whether meta data is necessary or not
- Values: 'implicit', 'explicit'
- Default: 'implicit'
- For example, if `explicit`, you must have meta `include` as `true` in order for the image declarations to be included in the spritesheet: `/* @meta {"spritesheet": {"include": true}} */`
- If left default at `implicit`, all images will be included in the spritesheet; except for image declarations with meta `include` as `false`: `/* @meta {"spritesheet": {"include": false}} */`
- `spriteSheet`: string - The path and file name of where we will save the sprite sheet
- Default: 'spritesheet.png'
- `pathToSpriteSheetFromCSS`: string - Because we don't know where you will end up saving the CSS file at this point in the pipe, we need a litle help identifying where it will be. We will use this as the reference to the sprite sheet image in the CSS piped in.
- Default: 'spritesheet.png'
- `spriteSheetBuildCallback`: function - Same as the [spritesmith callback](https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback-)
- Default: null
- Callback has a parameters as so: `function(err, result)`
- `result.image`: Binary string representation of image
- `result.coordinates`: Object mapping filename to {x, y, width, height} of image
- `result.properties`: Object with metadata about spritesheet {width, height}
- `silent`: bool - We ignore any images that are not found but are supposed to be sprited by default
- Default: true
- `shouldVerifyImagesExist`: bool - Check to make sure each image declared in the CSS exists before passing it to the spriter. Although silenced by default(`options.silent`), if an image is not found, an error is thrown.
- Default: true
- `spritesmithOptions`: object - Any option you pass in here, will be passed through to spritesmith. [See spritesmith options documenation](https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback-)
- Default: {}
- `outputIndent`: bool - Used to format output CSS. You should be using a separate beautifier plugin. The reason the output code is reformatted is because it is easier to "parse->stringify" than "replace in place".
- Default: '\t'
# What we emit
`gulp-css-spriter` emits the transformed CSS with updated image references to the sprite sheet as a normal Gulp [vinyl file](https://www.npmjs.com/package/vinyl).
We also attach the binary sprite sheet image in `chunk.spriteSheet` in case you want to consume it later down the pipe.
# Meta info
`gulp-css-spriter` uses a JSON format to add info onto CSS declarations.
The example below will exclude this declaration from the spritesheet.
```
/* @meta {"spritesheet": {"include": false}} */
background: url('../images/dummy-blue.png');
```
Please note that if you are compiling from Sass/Less and are not getting correct results, to check the outputted CSS and make sure the comments are still in tact and on the line you expect. For Sass, use multiline `/* */` comment syntax and put them above declarations. This is because gulp-sass/node-sass/libsass removes single line comments and puts mult-line comments that are on the same line as a declaration, below the declaraton.
The `@meta` comment data can be above or on the same line as the declaration for it to apply.
```
/* @meta {"spritesheet": {"include": false}} */
background: url('../images/dummy-blue.png'); /* @meta {"spritesheet": {"include": false}} */
```
## Meta options
- `spritesheet`: object - hash of options that `gulp-css-spriter` will factor in
- `include`: bool - determines whether or not the declaration should be included in the spritesheet. This can be left undefined if the `includeMode` is 'implicit'
# What we emit
`gulp-css-spriter` transforms your CSS image paths to the spritesheet appropriately then emits the CSS as a normal Gulp [vinyl file](https://www.npmjs.com/package/vinyl).
- Gulp [vinyl file](https://www.npmjs.com/package/vinyl). We emit the CSS you passed in with transformed image paths
## Events
### `.on('log', function(message) { })`
We emit log messages such as when a image defined in the CSS can't be found on disk.
### `.on('error', function(err) { })`
A normal gulp error. There are a variety of errors. See source code for more details.
# Testing
We have a series of unit tests. We use [Mocha](http://mochajs.org/).
Install Mocha globally:
```
npm install -g mocha
```
Run tests with: `mocha` or `npm test`
================================================
FILE: lib/spriter/index.js
================================================
// gulp-css-spriter: https://www.npmjs.com/package/gulp-css-spriter
// Sprite Sheet Generation from CSS source files.
//
// By: Eric Eastwood: EricEastwood.com
//
// Meta info looks like: `/* @meta {"spritesheet": {"include": false}} */`
var fs = require('fs-extra');
var path = require('path');
var Promise = require('bluebird');
var outputFile = Promise.promisify(fs.outputFile);
var stat = Promise.promisify(fs.stat);
var through = require('through2');
var extend = require('extend')
var gutil = require('gulp-util');
var css = require('css');
var spritesmith = require('spritesmith');
var spritesmithBuild = Promise.promisify(spritesmith);
var spriterUtil = require('./lib/spriter-util');
var getBackgroundImageDeclarations = require('./lib/get-background-image-declarations');
var transformFileWithSpriteSheetData = require('./lib/transform-file-with-sprite-sheet-data');
var gmutil = require('../gmutil'),
store = require('../store')
// consts
const PLUGIN_NAME = 'gulp-css-spriter';
const gm_sprite_img_dir = 'gm_sprite_img'
const gm_sprite_subfix = '_sprite_sheet.png'
var spriter = function(options) {
var defaults = {
// ('implicit'|'explicit')
'includeMode': 'implicit',
// The path and file name of where we will save the sprite sheet
'spriteSheet': 'spritesheet.png',
// Because we don't know where you will end up saving the CSS file at this point in the pipe,
// we need a litle help identifying where it will be.
'pathToSpriteSheetFromCSS': 'spritesheet.png',
// Same as the spritesmith callback `function(err, result)`
// result.image: Binary string representation of image
// result.coordinates: Object mapping filename to {x, y, width, height} of image
// result.properties: Object with metadata about spritesheet {width, height}
'spriteSheetBuildCallback': null,
// If true, we ignore any images that are not found on disk
// Note: this plugin will still emit an error if you do not verify that the images exist
'silent': true,
// Check to make sure each image declared in the CSS exists before passing it to the spriter.
// Although silenced by default(`options.silent`), if an image is not found, an error is thrown.
'shouldVerifyImagesExist': true,
// Any option you pass in here, will be passed through to spritesmith
// https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback-
'spritesmithOptions': {},
// Used to format output CSS
// You should be using a separate beautifier plugin
'outputIndent': '\t'
};
var settings = extend({}, defaults, options);
// Keep track of all the chunks that come in so that we can re-emit in the flush
var chunkList = [];
// We use an object for imageMap so we don't get any duplicates
var imageMap = {};
// Check to make sure all of the images exist(`options.shouldVerifyImagesExist`) before trying to sprite them
var imagePromiseArray = [];
// var currentChunkFile;
var stream = through.obj(function(chunk, enc, cb) {
// http://nodejs.org/docs/latest/api/stream.html#stream_transform_transform_chunk_encoding_callback
//console.log('transform');
// Each `chunk` is a vinyl file: https://www.npmjs.com/package/vinyl
// chunk.cwd
// chunk.base
// chunk.path
// chunk.contents
var self = this;
if (chunk.isStream()) {
self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Cannot operate on stream'));
}
else if (chunk.isBuffer()) {
var contents = String(chunk.contents);
var styles;
try {
styles = css.parse(contents, {
'silent': settings.silent,
'source': chunk.path
});
}
catch(err) {
err.message = 'Something went wrong when parsing the CSS: ' + err.message;
self.emit('log', err.message);
// Emit an error if necessary
if(!settings.silent) {
self.emit('error', err);
}
}
var fileDir = path.relative(settings['dist_root'], chunk.base)
var fileName = path.basename(chunk.relative)
// add for gulpman
chunk.base = settings['cwd']
// currentChunkFile = chunk
var relDistPath = path.join(
gm_sprite_img_dir,
fileName+gm_sprite_subfix
)
var distSpritePath = path.join(settings['dist_root'], fileDir, relDistPath)
settings['spriteSheet'] = distSpritePath
settings['pathToSpriteSheetFromCSS'] = relDistPath
// Gather a list of all of the image declarations
var chunkBackgroundImageDeclarations = getBackgroundImageDeclarations(styles, settings.includeMode);
// Go through each declaration and gather the image paths
// We find the new images that we found in this chunk verify they exist below
// We use an object so we don't get any duplicates
var newImagesfFromChunkMap = {};
var backgroundURLMatchAllRegex = new RegExp(spriterUtil.backgroundURLRegex.source, "gi");
chunkBackgroundImageDeclarations.forEach(function(declaration) {
// Match each background image in the declaration (there could be multiple background images per value)
spriterUtil.matchBackgroundImages(declaration.value, function(imagePath) {
imagePath = path.join(path.dirname(chunk.path), imagePath);
// If not already in the overall list of images collected
// Add to the queue/list of images to be verified
if(!imageMap[imagePath]) {
newImagesfFromChunkMap[imagePath] = true;
}
// Add it to the main overall list to keep track
imageMap[imagePath] = true;
});
});
// Filter out any images that do not exist depending on `settings.shouldVerifyImagesExist`
Object.keys(newImagesfFromChunkMap).forEach(function(imagePath) {
var filePromise;
if(settings.shouldVerifyImagesExist) {
filePromise = stat(imagePath).then(function() {
return {
doesExist: true,
path: imagePath
};
}, function() {
return {
doesExist: false,
path: imagePath
};
});
}
else {
// If they don't want us to verify it exists, just pass it on with a undefined `doesExist` property
filePromise = Promise.resolve({
doesExist: undefined,
path: imagePath
});
}
imagePromiseArray.push(filePromise);
});
// Keep track of each chunk and what declarations go with it
// Because the positions/line numbers pertain to that chunk only
chunkList.push(chunk);
}
// "call callback when the transform operation is complete."
cb();
}, function(cb) {
// http://nodejs.org/docs/latest/api/stream.html#stream_transform_flush_callback
//console.log('flush');
var self = this;
// @debug
// Create an verified image list when all of the async checks have finished
var imagesVerifiedPromise = Promise.settle(imagePromiseArray).then(function(results) {
var imageList = [];
Array.prototype.forEach.call(results, function(result) {
imageInfo = result.value();
if(imageInfo.doesExist === true || imageInfo.doesExist === undefined) {
imageList.push(imageInfo.path);
}
else {
// Tell them that we could not find the image
var logMessage = 'Image could not be found: ' + imageInfo.path;
self.emit('log', logMessage);
// Emit an error if necessary
if(!settings.silent) {
self.emit('error', {
'name': 'NotFound',
'message': logMessage,
'plugin': PLUGIN_NAME
});
}
}
});
return imageList;
});
// Start spriting once we know the true list of images that exist
imagesVerifiedPromise.then(function(imageList) {
// fix the invalid png files when no-sprite-img
// @debug ..可能有问题。。
if(!imageList.length) {
chunkList.forEach(chunk=>{
self.push(chunk)
})
return cb();
}
// Generate the spritesheet
var spritesmithOptions = extend({}, settings.spritesmithOptions, { src: imageList });
var spriteSmithBuildPromise = spritesmithBuild(spritesmithOptions);
spriteSmithBuildPromise.then(function(result) {
var whenImageDealtWithPromise = new Promise(function(resolve, reject) {
// Save out the spritesheet image
if(settings.spriteSheet) {
var spriteSheetSavedPromise = outputFile(settings.spriteSheet, result.image, 'binary').then(function() {
//console.log("The file was saved!");
// Push all of the chunks back on the pipe
chunkList.forEach(function(chunk) {
var transformedChunk = chunk.clone();
// gmutil.alert('IMG: '+imageList)
// save into relevancy store
store.save(imageList, chunk.path, 'sprite')
try {
transformedChunk = transformFileWithSpriteSheetData(transformedChunk, result.coordinates, settings.pathToSpriteSheetFromCSS, settings.includeMode, settings.silent, settings.outputIndent);
}
catch(err) {
err.message = 'Something went wrong when transforming chunks: ' + err.message;
self.emit('log', err.message);
// Emit an error if necessary
if(!settings.silent) {
self.emit('error', err);
}
reject(err);
}
// Attach the spritesheet in case someone wants to use it down the pipe
transformedChunk.spritesheet = result.image;
// Push it back on the main pipe
self.push(transformedChunk);
});
}, function() {
settings.spriteSheetBuildCallback(err, null);
reject(err);
});
spriteSheetSavedPromise.finally(function() {
// Call a callback from the settings the user can hook onto
if(settings.spriteSheetBuildCallback) {
settings.spriteSheetBuildCallback(null, result);
}
resolve();
});
}
else {
resolve();
}
});
whenImageDealtWithPromise.finally(function() {
// "call callback when the flush operation is complete."
cb();
});
}, function(err) {
if(err) {
err.message = 'Error creating sprite sheet image:\n' + err.message;
self.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
}
});
});
});
// returning the file stream
return stream;
};
module.exports = spriter;
================================================
FILE: lib/spriter/lib/get-background-image-declarations.js
================================================
var mapOverStylesAndTransformBackgroundImageDeclarations = require('./map-over-styles-and-transform-background-image-declarations');
// Pass in a styles object from `css.parse`
// See main module for `includeMode` values
function getBackgroundImageDeclarations(styles, includeMode) {
includeMode = includeMode || 'implicit';
// First get all of the background image declarations
var backgroundImageDeclarations = [];
mapOverStylesAndTransformBackgroundImageDeclarations(styles, includeMode, function(declaration) {
backgroundImageDeclarations.push(declaration);
});
return backgroundImageDeclarations;
}
module.exports = getBackgroundImageDeclarations;
================================================
FILE: lib/spriter/lib/get-meta-info-for-declaration.js
================================================
var extend = require('extend');
function getMetaInfoForDeclaration(declarations, declarationIndex) {
var resultantMetaData = {};
if(declarationIndex > 0 && declarationIndex < declarations.length) {
var mainDeclaration = declarations[declarationIndex];
if(mainDeclaration) {
// Meta data can exist before or on the same line as the declaration.
// Both Meta blocks are valid for the background property
// ex.
// /* @meta {"spritesheet": {"include": false}} */
// background: url('../images/aenean-purple.png'); /* @meta {"sprite": {"skip": true}} */
var beforeDeclaration = declarations[declarationIndex-1];
var afterDeclaration = declarations[declarationIndex+1];
if(beforeDeclaration) {
// The before declaration should be valid no matter what (even if multiple lines above)
// The parse function does all the nice checking for us
extend(resultantMetaData, parseCommentDecarationForMeta(beforeDeclaration));
}
if(afterDeclaration) {
//console.log(mainDeclaration);
//console.log(afterDeclaration);
//console.log(afterDeclaration.position.start.line, mainDeclaration.position.start.line);
// Make sure that the comment starts on the same line as the main declaration
if((((afterDeclaration || {}).position || {}).start || {}).line === (((mainDeclaration || {}).position || {}).start || {}).line) {
extend(resultantMetaData, parseCommentDecarationForMeta(afterDeclaration));
}
}
}
}
return resultantMetaData;
}
function parseCom
gitextract_0od9uxhv/ ├── .gitignore ├── LICENSE ├── README.md ├── README_zh-CN.md ├── assets/ │ └── .babelrc ├── index.js ├── karma/ │ └── karma.conf.js ├── lib/ │ ├── assetsPathParser.js │ ├── base64.js │ ├── cdnProxy.js │ ├── gmutil.js │ ├── gulp-usemin/ │ │ ├── .npmignore │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── README.md │ │ ├── gulpfile.js │ │ ├── index.js │ │ ├── lib/ │ │ │ ├── blocksBuilder.js │ │ │ ├── htmlBuilder.js │ │ │ └── pipeline.js │ │ ├── package.json │ │ └── test/ │ │ ├── expected/ │ │ │ ├── app.js │ │ │ ├── array-js-attributes.html │ │ │ ├── build-remove-no-trailing-whitespace.html │ │ │ ├── complex-path.html │ │ │ ├── complex.html │ │ │ ├── conditional-complex.html │ │ │ ├── conditional-css.html │ │ │ ├── conditional-inline-css.html │ │ │ ├── conditional-inline-js.html │ │ │ ├── conditional-js.html │ │ │ ├── data/ │ │ │ │ ├── css/ │ │ │ │ │ ├── min-style.css │ │ │ │ │ └── style.css │ │ │ │ └── js/ │ │ │ │ ├── app.js │ │ │ │ ├── app_min_concat.js │ │ │ │ └── min-app.js │ │ │ ├── glob-inline-css.html │ │ │ ├── glob-inline-js.html │ │ │ ├── many-blocks-removal.html │ │ │ ├── min-app.js │ │ │ ├── min-complex-path.html │ │ │ ├── min-complex.html │ │ │ ├── min-css-with-media-query.html │ │ │ ├── min-html-simple-css.html │ │ │ ├── min-html-simple-js.html │ │ │ ├── min-html-simple-removal.html │ │ │ ├── min-paths-with-querystring.html │ │ │ ├── min-simple-css-path.html │ │ │ ├── min-simple-css.html │ │ │ ├── min-simple-js-path.html │ │ │ ├── min-simple-js.html │ │ │ ├── min-style.css │ │ │ ├── multiple-alternative-paths.html │ │ │ ├── multiple-files.html │ │ │ ├── paths-with-querystring.html │ │ │ ├── simple-css-path.html │ │ │ ├── simple-css.html │ │ │ ├── simple-inline-css.html │ │ │ ├── simple-inline-js.html │ │ │ ├── simple-js-path.html │ │ │ ├── simple-js-removal.html │ │ │ ├── simple-js.html │ │ │ ├── single-quotes-css.html │ │ │ ├── single-quotes-inline-css.html │ │ │ ├── single-quotes-inline-js.html │ │ │ ├── single-quotes-js.html │ │ │ ├── style.css │ │ │ └── subfolder/ │ │ │ ├── app.js │ │ │ └── index.html │ │ ├── fixtures/ │ │ │ ├── alternative/ │ │ │ │ └── js/ │ │ │ │ └── util.js │ │ │ ├── array-js-attributes.html │ │ │ ├── async-less.html │ │ │ ├── build-remove-no-trailing-whitespace.html │ │ │ ├── comment-js.html │ │ │ ├── complex-path.html │ │ │ ├── complex.html │ │ │ ├── conditional-complex.html │ │ │ ├── conditional-css.html │ │ │ ├── conditional-inline-css.html │ │ │ ├── conditional-inline-js.html │ │ │ ├── conditional-js.html │ │ │ ├── css/ │ │ │ │ ├── clear.css │ │ │ │ └── main.css │ │ │ ├── css-with-media-query-error.html │ │ │ ├── css-with-media-query.html │ │ │ ├── glob-css.html │ │ │ ├── glob-inline-css.html │ │ │ ├── glob-inline-js.html │ │ │ ├── glob-js.html │ │ │ ├── js/ │ │ │ │ ├── lib.js │ │ │ │ └── main.js │ │ │ ├── js2/ │ │ │ │ ├── lib2.js │ │ │ │ └── main2.js │ │ │ ├── less/ │ │ │ │ ├── clear.less │ │ │ │ └── main.less │ │ │ ├── many-blocks-removal.html │ │ │ ├── many-blocks.html │ │ │ ├── min-html-simple-css.html │ │ │ ├── min-html-simple-js.html │ │ │ ├── min-html-simple-removal.html │ │ │ ├── multiple-alternative-paths-inline.html │ │ │ ├── multiple-alternative-paths.html │ │ │ ├── multiple-files.html │ │ │ ├── paths-with-querystring.html │ │ │ ├── simple-css-alternate-path.html │ │ │ ├── simple-css-path.html │ │ │ ├── simple-css.html │ │ │ ├── simple-inline-css.html │ │ │ ├── simple-inline-js.html │ │ │ ├── simple-js-alternate-path.html │ │ │ ├── simple-js-path.html │ │ │ ├── simple-js-removal.html │ │ │ ├── simple-js.html │ │ │ ├── single-quotes-css.html │ │ │ ├── single-quotes-inline-css.html │ │ │ ├── single-quotes-inline-js.html │ │ │ ├── single-quotes-js.html │ │ │ └── subfolder/ │ │ │ ├── index.html │ │ │ └── script.js │ │ └── main.js │ ├── htmlPathParser.js │ ├── iconFonter.js │ ├── inline.js │ ├── revReplace.js │ ├── spriter/ │ │ ├── README.md │ │ ├── index.js │ │ ├── lib/ │ │ │ ├── get-background-image-declarations.js │ │ │ ├── get-meta-info-for-declaration.js │ │ │ ├── map-over-styles-and-transform-background-image-declarations.js │ │ │ ├── spriter-util.js │ │ │ ├── transform-file-with-sprite-sheet-data.js │ │ │ └── transform-map.js │ │ └── package.json │ └── store.js ├── meta/ │ └── home/ │ ├── index.html │ ├── main.es6 │ └── main.scss ├── package.json ├── presetlib/ │ ├── jquery.js │ ├── react-0.14.6/ │ │ └── build/ │ │ ├── react-dom-server.js │ │ ├── react-dom.js │ │ ├── react-with-addons.js │ │ └── react.js │ └── react.js ├── scripts/ │ ├── gulp/ │ │ └── gulpfile.js │ ├── install.sh │ ├── package.json │ └── preinstall.sh └── test.js
SYMBOL INDEX (1033 symbols across 23 files)
FILE: index.js
function initVars (line 159) | function initVars(){
function OSInform (line 213) | function OSInform(title, _message, err){
function OSInformError (line 239) | function OSInformError(title, err, errDesc){
function getB64ImgReg (line 254) | function getB64ImgReg(){
function browserified (line 260) | function browserified(fpath, sourceDir){
function getDirFromTmpStaticToRuntimeStatic (line 330) | function getDirFromTmpStaticToRuntimeStatic(p){
function doBrowserify (line 340) | function doBrowserify(){
function getComponentsPath (line 380) | function getComponentsPath(){
function getRelevancyHandler (line 385) | function getRelevancyHandler() {
function updateTplFile (line 430) | function updateTplFile(tmpFile){
function spriteCSS (line 445) | function spriteCSS(entry) {
function storeCheck (line 479) | function storeCheck(filepath, dbType, handlerType, evtObj){
function safeClean (line 492) | function safeClean(path) {
function compile_sass (line 553) | function compile_sass(singleFile){
function fireUpdate (line 895) | function fireUpdate(type, event){
function getUpdateEvent (line 906) | function getUpdateEvent(type){
function removeUpdateEvent (line 917) | function removeUpdateEvent(type){
function htmlParseFlow (line 926) | function htmlParseFlow(b, _isRuntimeDir){
function parseRawHTML (line 968) | function parseRawHTML(b, basepath, _isRuntimeDir) {
function getRelativePathOfComponents (line 998) | function getRelativePathOfComponents(epath) {
function translatePathExtname (line 1007) | function translatePathExtname(type, _path){
function delChangedFile (line 1021) | function delChangedFile(epath, delOutDir, type){
function getRelativePathOfTarget (line 1047) | function getRelativePathOfTarget(epath, tarBaseDir){
function getAbsPathOfTarget (line 1060) | function getAbsPathOfTarget(epath, tarBaseDir){
function _checkRelevancy (line 1066) | function _checkRelevancy(filePath, event){
function getSpecificComponentsList (line 1073) | function getSpecificComponentsList() {
function updateSpecificComponentsSource (line 1080) | function updateSpecificComponentsSource() {
function setRevReplace (line 1357) | function setRevReplace(){
function updateConf (line 1673) | function updateConf(opts){
FILE: lib/assetsPathParser.js
function parseCSS (line 23) | function parseCSS(content, file){
function parseTpl (line 65) | function parseTpl(conf, contents, file){
function parseJS (line 138) | function parseJS(conf, contents, file){
function _absolutizePath (line 208) | function _absolutizePath(_opts){
FILE: lib/base64.js
constant PLUGIN_NAME (line 20) | const PLUGIN_NAME = 'Base64'
function purifyUrlPrefix (line 23) | function purifyUrlPrefix(str){
function purify (line 27) | function purify(str){
function parseSource (line 33) | function parseSource(images, file, refType, content, baseDir){
function toBase64 (line 158) | function toBase64(_opts) {
FILE: lib/cdnProxy.js
function proxyPrefix (line 17) | function proxyPrefix(obj){
FILE: lib/gmutil.js
function _log (line 13) | function _log (str, color) {
function _error (line 22) | function _error (str){
function _alert (line 27) | function _alert(str) {
function _tip (line 31) | function _tip (str){
function _warn (line 36) | function _warn (str){
function getRandomArbitrary (line 45) | function getRandomArbitrary(min, max) {
function randomNum (line 53) | function randomNum(min, max) {
function byLongestUnreved (line 58) | function byLongestUnreved(a, b) {
function pathInAssets (line 63) | function pathInAssets(_cwd, fpath, componentsDir, runStaticDir){
function validateObj (line 72) | function validateObj(obj){
function isArray (line 83) | function isArray(o) {
function convertSource (line 88) | function convertSource(rawSource, refType){
function isUrl (line 114) | function isUrl(urlType, str){
function joinUrl (line 136) | function joinUrl (a, b){
function replaceBuildBlock (line 153) | function replaceBuildBlock(content, srcPrefix) {
FILE: lib/gulp-usemin/lib/blocksBuilder.js
function getFiles (line 25) | function getFiles(content, reg, alternatePath) {
FILE: lib/gulp-usemin/lib/htmlBuilder.js
function createFile (line 10) | function createFile(name, content) {
function createHTMLAttributes (line 18) | function createHTMLAttributes(attributes, index){
function _fixUrlForRevReplace (line 46) | function _fixUrlForRevReplace(str){
function _fixFilePath (line 51) | function _fixFilePath(name, file){
FILE: lib/gulp-usemin/test/main.js
function getFile (line 14) | function getFile(filePath) {
function getFixture (line 22) | function getFixture(filePath) {
function getExpected (line 26) | function getExpected(filePath) {
function compare (line 32) | function compare(name, expectedName, done) {
function compare (line 106) | function compare(name, expectedName, done, fail) {
function compare (line 169) | function compare(name, expectedName, done) {
function compare (line 232) | function compare(fixtureName, name, expectedName, end) {
function compare (line 269) | function compare(fixtureName, expectedName, end) {
function compare (line 300) | function compare(fixtureName, name, expectedName, end) {
function compare (line 334) | function compare(fixtureName, expectedName, end) {
function compare (line 459) | function compare(assetsDir, done) {
function compare (line 483) | function compare(name, expectedName, done) {
function compare (line 519) | function compare(fixtureName, name, end) {
function compare (line 550) | function compare(name, callback) {
function compare (line 574) | function compare(fixtureName, name, end) {
function compare (line 607) | function compare(fixtureName, name, end) {
FILE: lib/htmlPathParser.js
function _dealHTML (line 16) | function _dealHTML(conf){
FILE: lib/iconFonter.js
function registerTask (line 11) | function registerTask(gulp, opts) {
FILE: lib/revReplace.js
function plugin (line 10) | function plugin(options) {
FILE: lib/spriter/index.js
constant PLUGIN_NAME (line 34) | const PLUGIN_NAME = 'gulp-css-spriter';
FILE: lib/spriter/lib/get-background-image-declarations.js
function getBackgroundImageDeclarations (line 7) | function getBackgroundImageDeclarations(styles, includeMode) {
FILE: lib/spriter/lib/get-meta-info-for-declaration.js
function getMetaInfoForDeclaration (line 4) | function getMetaInfoForDeclaration(declarations, declarationIndex) {
function parseCommentDecarationForMeta (line 42) | function parseCommentDecarationForMeta(declaration) {
FILE: lib/spriter/lib/map-over-styles-and-transform-background-image-declarations.js
function mapOverStylesAndTransformBackgroundImageDeclarations (line 9) | function mapOverStylesAndTransformBackgroundImageDeclarations(styles, in...
function shouldIncludeFactoringInMetaData (line 20) | function shouldIncludeFactoringInMetaData(meta, includeMode) {
function mapOverStylesAndTransformAllBackgroundImageDeclarations (line 35) | function mapOverStylesAndTransformAllBackgroundImageDeclarations(styles,...
function attachInfoToDeclaration (line 103) | function attachInfoToDeclaration(declarations, declarationIndex)
FILE: lib/spriter/lib/spriter-util.js
function matchBackgroundImages (line 5) | function matchBackgroundImages(declarationValue, cb) {
FILE: lib/spriter/lib/transform-file-with-sprite-sheet-data.js
function transformFileWithSpriteSheetData (line 13) | function transformFileWithSpriteSheetData(vinylFile, coordinateMap, path...
FILE: lib/spriter/lib/transform-map.js
function transformMap (line 3) | function transformMap(arr, cb) {
FILE: lib/store.js
function initStore (line 26) | function initStore(db) {
function _write (line 46) | function _write(fpath){
function _push (line 50) | function _push (sourceFile, refFile, dbType) {
function _check (line 62) | function _check(sourceAbsPath, handler, dbType, handlerType, evtObj){
function _isInList (line 96) | function _isInList(sourceFile, refFile, dbType){
function _save (line 103) | function _save (sourceFile, refFile, dbType) {
function getStore (line 124) | function getStore(){
FILE: presetlib/jquery.js
function isArraylike (line 533) | function isArraylike( obj ) {
function Sizzle (line 750) | function Sizzle( selector, context, results, seed ) {
function createCache (line 864) | function createCache() {
function markFunction (line 882) | function markFunction( fn ) {
function assert (line 891) | function assert( fn ) {
function addHandle (line 913) | function addHandle( attrs, handler ) {
function siblingCheck (line 928) | function siblingCheck( a, b ) {
function createInputPseudo (line 955) | function createInputPseudo( type ) {
function createButtonPseudo (line 966) | function createButtonPseudo( type ) {
function createPositionalPseudo (line 977) | function createPositionalPseudo( fn ) {
function testContext (line 1000) | function testContext( context ) {
function setFilters (line 2009) | function setFilters() {}
function toSelector (line 2080) | function toSelector( tokens ) {
function addCombinator (line 2090) | function addCombinator( matcher, combinator, base ) {
function elementMatcher (line 2143) | function elementMatcher( matchers ) {
function multipleContexts (line 2157) | function multipleContexts( selector, contexts, results ) {
function condense (line 2166) | function condense( unmatched, map, filter, context, xml ) {
function setMatcher (line 2187) | function setMatcher( preFilter, selector, matcher, postFilter, postFinde...
function matcherFromTokens (line 2280) | function matcherFromTokens( tokens ) {
function matcherFromGroupMatchers (line 2338) | function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
function winnow (line 2634) | function winnow( elements, qualifier, not ) {
function sibling (line 2958) | function sibling( cur, dir ) {
function createOptions (line 3036) | function createOptions( options ) {
function completed (line 3430) | function completed() {
function Data (line 3535) | function Data() {
function dataAttr (line 3726) | function dataAttr( elem, key, data ) {
function returnTrue (line 4066) | function returnTrue() {
function returnFalse (line 4070) | function returnFalse() {
function safeActiveElement (line 4074) | function safeActiveElement() {
function manipulationTarget (line 4946) | function manipulationTarget( elem, content ) {
function disableScript (line 4956) | function disableScript( elem ) {
function restoreScript (line 4960) | function restoreScript( elem ) {
function setGlobalEval (line 4973) | function setGlobalEval( elems, refElements ) {
function cloneCopyEvent (line 4984) | function cloneCopyEvent( src, dest ) {
function getAll (line 5018) | function getAll( context, tag ) {
function fixInput (line 5029) | function fixInput( src, dest ) {
function actualDisplay (line 5484) | function actualDisplay( name, doc ) {
function defaultDisplay (line 5506) | function defaultDisplay( nodeName ) {
function curCSS (line 5553) | function curCSS( elem, name, computed ) {
function addGetHookIf (line 5601) | function addGetHookIf( conditionFn, hookFn ) {
function computePixelPositionAndBoxSizingReliable (line 5641) | function computePixelPositionAndBoxSizingReliable() {
function vendorPropName (line 5746) | function vendorPropName( style, name ) {
function setPositiveNumber (line 5768) | function setPositiveNumber( elem, value, subtract ) {
function augmentWidthOrHeight (line 5776) | function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
function getWidthOrHeight (line 5815) | function getWidthOrHeight( elem, name, extra ) {
function showHide (line 5859) | function showHide( elements, show ) {
function Tween (line 6157) | function Tween( elem, options, prop, end, easing ) {
function createFxNow (line 6326) | function createFxNow() {
function genFx (line 6334) | function genFx( type, includeWidth ) {
function createTween (line 6354) | function createTween( value, prop, animation ) {
function defaultPrefilter (line 6368) | function defaultPrefilter( elem, props, opts ) {
function propFilter (line 6501) | function propFilter( props, specialEasing ) {
function Animation (line 6538) | function Animation( elem, properties, options ) {
function addToPrefiltersOrTransports (line 7586) | function addToPrefiltersOrTransports( structure ) {
function inspectPrefiltersOrTransports (line 7618) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
function ajaxExtend (line 7645) | function ajaxExtend( target, src ) {
function ajaxHandleResponses (line 7665) | function ajaxHandleResponses( s, jqXHR, responses ) {
function ajaxConvert (line 7721) | function ajaxConvert( s, response, jqXHR, isSuccess ) {
function done (line 8179) | function done( status, nativeStatusText, responses, headers ) {
function buildParams (line 8423) | function buildParams( prefix, obj, traditional, add ) {
function getWindow (line 8917) | function getWindow( elem ) {
FILE: presetlib/react-0.14.6/build/react-with-addons.js
function s (line 4) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
function isPresto (line 150) | function isPresto() {
function isKeypressCommand (line 200) | function isKeypressCommand(nativeEvent) {
function getCompositionEventType (line 212) | function getCompositionEventType(topLevelType) {
function isFallbackCompositionStart (line 231) | function isFallbackCompositionStart(topLevelType, nativeEvent) {
function isFallbackCompositionEnd (line 242) | function isFallbackCompositionEnd(topLevelType, nativeEvent) {
function getDataFromCustomEvent (line 270) | function getDataFromCustomEvent(nativeEvent) {
function extractCompositionEvent (line 288) | function extractCompositionEvent(topLevelType, topLevelTarget, topLevelT...
function getNativeBeforeInputChars (line 340) | function getNativeBeforeInputChars(topLevelType, nativeEvent) {
function getFallbackBeforeInputChars (line 394) | function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
function extractBeforeInputEvent (line 450) | function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelT...
function prefixKey (line 562) | function prefixKey(prefix, key) {
function CallbackQueue (line 854) | function CallbackQueue() {
function shouldUseChangeEvent (line 967) | function shouldUseChangeEvent(elem) {
function manualDispatchChangeEvent (line 978) | function manualDispatchChangeEvent(nativeEvent) {
function runEventInBatch (line 996) | function runEventInBatch(event) {
function startWatchingForChangeEventIE8 (line 1001) | function startWatchingForChangeEventIE8(target, targetID) {
function stopWatchingForChangeEventIE8 (line 1007) | function stopWatchingForChangeEventIE8() {
function getTargetIDForChangeEvent (line 1016) | function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLeve...
function handleEventsForChangeEventIE8 (line 1021) | function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, top...
function startWatchingForValueChange (line 1062) | function startWatchingForValueChange(target, targetID) {
function stopWatchingForValueChange (line 1078) | function stopWatchingForValueChange() {
function handlePropertyChange (line 1097) | function handlePropertyChange(nativeEvent) {
function getTargetIDForInputEvent (line 1113) | function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevel...
function handleEventsForInputEventIE (line 1122) | function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLe...
function getTargetIDForInputEventIE (line 1145) | function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLev...
function shouldUseClickEvent (line 1167) | function shouldUseClickEvent(elem) {
function getTargetIDForClickEvent (line 1174) | function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevel...
function insertChildAt (line 1295) | function insertChildAt(parentNode, childNode, index) {
function checkMask (line 1411) | function checkMask(value, bitmask) {
function isAttributeNameSafe (line 1655) | function isAttributeNameSafe(attributeName) {
function shouldIgnoreValue (line 1671) | function shouldIgnoreValue(propertyInfo, value) {
function getNodeName (line 1891) | function getNodeName(markup) {
function validateInstanceHandle (line 2310) | function validateInstanceHandle() {
function recomputePluginOrdering (line 2559) | function recomputePluginOrdering() {
function publishEventForPlugin (line 2588) | function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
function publishRegistrationName (line 2616) | function publishRegistrationName(registrationName, PluginModule, eventNa...
function isEndish (line 2788) | function isEndish(topLevelType) {
function isMoveish (line 2792) | function isMoveish(topLevelType) {
function isStartish (line 2795) | function isStartish(topLevelType) {
function executeDispatch (line 2821) | function executeDispatch(event, simulated, listener, domID) {
function executeDispatchesInOrder (line 2835) | function executeDispatchesInOrder(event, simulated) {
function executeDispatchesInOrderStopAtTrueImpl (line 2863) | function executeDispatchesInOrderStopAtTrueImpl(event) {
function executeDispatchesInOrderStopAtTrue (line 2890) | function executeDispatchesInOrderStopAtTrue(event) {
function executeDirectDispatch (line 2906) | function executeDirectDispatch(event) {
function hasDispatches (line 2923) | function hasDispatches(event) {
function listenerAtPhase (line 2980) | function listenerAtPhase(id, event, propagationPhase) {
function accumulateDirectionalDispatches (line 2991) | function accumulateDirectionalDispatches(domID, upwards, event) {
function accumulateTwoPhaseDispatchesSingle (line 3010) | function accumulateTwoPhaseDispatchesSingle(event) {
function accumulateTwoPhaseDispatchesSingleSkipTarget (line 3019) | function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
function accumulateDispatches (line 3030) | function accumulateDispatches(id, ignoredDirection, event) {
function accumulateDirectDispatchesSingle (line 3046) | function accumulateDirectDispatchesSingle(event) {
function accumulateTwoPhaseDispatches (line 3052) | function accumulateTwoPhaseDispatches(events) {
function accumulateTwoPhaseDispatchesSkipTarget (line 3056) | function accumulateTwoPhaseDispatchesSkipTarget(events) {
function accumulateEnterLeaveDispatches (line 3060) | function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
function accumulateDirectDispatches (line 3064) | function accumulateDirectDispatches(events) {
function FallbackCompositionState (line 3118) | function FallbackCompositionState(root) {
function _assertSingleLink (line 3482) | function _assertSingleLink(inputProps) {
function _assertValueLink (line 3485) | function _assertValueLink(inputProps) {
function _assertCheckedLink (line 3490) | function _assertCheckedLink(inputProps) {
function getDeclarationErrorAddendum (line 3512) | function getDeclarationErrorAddendum(owner) {
function assign (line 3602) | function assign(target, sources) {
function getListeningForDocument (line 3987) | function getListeningForDocument(mountAt) {
function createTransitionTimeoutPropValidator (line 4179) | function createTransitionTimeoutPropValidator(transitionType) {
function instantiateChild (line 4429) | function instantiateChild(childInstances, child, name) {
function escapeUserProvidedKey (line 4554) | function escapeUserProvidedKey(text) {
function ForEachBookKeeping (line 4566) | function ForEachBookKeeping(forEachFunction, forEachContext) {
function forEachSingleChild (line 4578) | function forEachSingleChild(bookKeeping, child, name) {
function forEachChildren (line 4595) | function forEachChildren(children, forEachFunc, forEachContext) {
function MapBookKeeping (line 4613) | function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
function mapSingleChildIntoContext (line 4629) | function mapSingleChildIntoContext(bookKeeping, child, childKey) {
function mapIntoWithKeyPrefixInternal (line 4649) | function mapIntoWithKeyPrefixInternal(children, array, prefix, func, con...
function mapChildren (line 4670) | function mapChildren(children, func, context) {
function forEachSingleChildDummy (line 4679) | function forEachSingleChildDummy(traverseContext, child, name) {
function countChildren (line 4690) | function countChildren(children, context) {
function toArray (line 4698) | function toArray(children) {
function warnSetProps (line 4770) | function warnSetProps() {
function validateTypeDef (line 5077) | function validateTypeDef(Constructor, typeDef, location) {
function validateMethodOverride (line 5087) | function validateMethodOverride(proto, name) {
function mixSpecIntoComponent (line 5105) | function mixSpecIntoComponent(Constructor, spec) {
function mixStaticSpecIntoComponent (line 5182) | function mixStaticSpecIntoComponent(Constructor, statics) {
function mergeIntoWithNoDuplicateKeys (line 5208) | function mergeIntoWithNoDuplicateKeys(one, two) {
function createMergedResultFunction (line 5228) | function createMergedResultFunction(one, two) {
function createChainedFunction (line 5252) | function createChainedFunction(one, two) {
function bindAutoBindMethod (line 5266) | function bindAutoBindMethod(component, method) {
function bindAutoBindMethods (line 5305) | function bindAutoBindMethods(component) {
function ReactComponent (line 5509) | function ReactComponent(props, context, updater) {
function getDeclarationErrorAddendum (line 5779) | function getDeclarationErrorAddendum(component) {
function StatelessComponent (line 5790) | function StatelessComponent(Component) {}
function getDeclarationErrorAddendum (line 6678) | function getDeclarationErrorAddendum(internalInstance) {
function legacyGetDOMNode (line 6705) | function legacyGetDOMNode() {
function legacyIsMounted (line 6713) | function legacyIsMounted() {
function legacySetStateEtc (line 6721) | function legacySetStateEtc() {
function legacySetProps (line 6728) | function legacySetProps(partialProps, callback) {
function legacyReplaceProps (line 6742) | function legacyReplaceProps(partialProps, callback) {
function friendlyStringify (line 6756) | function friendlyStringify(obj) {
function checkAndWarnForMutatedStyle (line 6782) | function checkAndWarnForMutatedStyle(style1, style2, component) {
function assertValidProps (line 6812) | function assertValidProps(component, props) {
function enqueuePutListener (line 6833) | function enqueuePutListener(id, registrationName, listener, transaction) {
function putListener (line 6851) | function putListener() {
function trapBubbledEventsLocal (line 6884) | function trapBubbledEventsLocal() {
function mountReadyInputWrapper (line 6917) | function mountReadyInputWrapper() {
function postUpdateSelectWrapper (line 6921) | function postUpdateSelectWrapper() {
function validateDangerousTag (line 6968) | function validateDangerousTag(tag) {
function processChildContextDev (line 6975) | function processChildContextDev(context, inst) {
function isCustomComponent (line 6983) | function isCustomComponent(tagName, props) {
function ReactDOMComponent (line 7001) | function ReactDOMComponent(tag) {
function createDOMFactory (line 7608) | function createDOMFactory(tag) {
function forceUpdateIfMounted (line 7898) | function forceUpdateIfMounted() {
function _handleChange (line 7977) | function _handleChange(event) {
function updateOptionsIfPendingUpdateAndMounted (line 8138) | function updateOptionsIfPendingUpdateAndMounted() {
function getDeclarationErrorAddendum (line 8151) | function getDeclarationErrorAddendum(owner) {
function checkSelectPropTypes (line 8167) | function checkSelectPropTypes(inst, props) {
function updateOptions (line 8190) | function updateOptions(inst, multiple, propValue) {
function _handleChange (line 8294) | function _handleChange(event) {
function isCollapsed (line 8328) | function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
function getIEOffsets (line 8346) | function getIEOffsets(node) {
function getModernOffsets (line 8369) | function getModernOffsets(node) {
function setIEOffsets (line 8431) | function setIEOffsets(node, offsets) {
function setModernOffsets (line 8465) | function setModernOffsets(node, offsets) {
function forceUpdateIfMounted (line 8694) | function forceUpdateIfMounted() {
function _handleChange (line 8778) | function _handleChange(event) {
function ReactDefaultBatchingStrategyTransaction (line 8820) | function ReactDefaultBatchingStrategyTransaction() {
function inject (line 8892) | function inject() {
function roundFloat (line 8974) | function roundFloat(val) {
function addValue (line 8978) | function addValue(obj, key, val) {
function getTotalTime (line 9223) | function getTotalTime(measurements) {
function getDOMSummary (line 9236) | function getDOMSummary(measurements) {
function getExclusiveSummary (line 9252) | function getExclusiveSummary(measurements) {
function getInclusiveSummary (line 9300) | function getInclusiveSummary(measurements, onlyClean) {
function getUnchangedComponents (line 9355) | function getUnchangedComponents(measurement) {
function getDeclarationErrorAddendum (line 9671) | function getDeclarationErrorAddendum() {
function validateExplicitKey (line 9700) | function validateExplicitKey(element, parentType) {
function getAddendaForKeyUse (line 9724) | function getAddendaForKeyUse(messageType, element, parentType) {
function validateChildKeys (line 9765) | function validateChildKeys(node, parentType) {
function checkPropTypes (line 9807) | function checkPropTypes(componentName, propTypes, props, location) {
function validatePropTypes (line 9841) | function validatePropTypes(element) {
function isNullComponentID (line 9996) | function isNullComponentID(id) {
function registerNullComponentID (line 10004) | function registerNullComponentID(id) {
function deregisterNullComponentID (line 10012) | function deregisterNullComponentID(id) {
function invokeGuardedCallback (line 10048) | function invokeGuardedCallback(name, func, a, b) {
function runEventQueueInBatch (line 10117) | function runEventQueueInBatch(events) {
function findParent (line 10175) | function findParent(node) {
function TopLevelCallbackBookKeeping (line 10187) | function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
function handleTopLevelImpl (line 10201) | function handleTopLevelImpl(bookKeeping) {
function handleTopLevelWithoutPath (line 10217) | function handleTopLevelWithoutPath(bookKeeping) {
function handleTopLevelWithPath (line 10238) | function handleTopLevelWithPath(bookKeeping) {
function scrollValueMonitor (line 10271) | function scrollValueMonitor(cb) {
function isInDocument (line 10476) | function isInDocument(node) {
function getReactRootIDString (line 10615) | function getReactRootIDString(index) {
function isBoundary (line 10627) | function isBoundary(id, index) {
function isValidID (line 10638) | function isValidID(id) {
function isAncestorIDOf (line 10650) | function isAncestorIDOf(ancestorID, descendantID) {
function getParentID (line 10661) | function getParentID(id) {
function getNextDescendantID (line 10674) | function getNextDescendantID(ancestorID, destinationID) {
function getFirstCommonAncestorID (line 10703) | function getFirstCommonAncestorID(oneID, twoID) {
function traverseParentPath (line 10735) | function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
function ReactLink (line 11051) | function ReactLink(value, requestChange) {
function createLinkTypeChecker (line 11064) | function createLinkTypeChecker(linkType) {
function firstDifferenceIndex (line 11190) | function firstDifferenceIndex(string1, string2) {
function getReactRootElementInContainer (line 11205) | function getReactRootElementInContainer(container) {
function getReactRootID (line 11221) | function getReactRootID(container) {
function getID (line 11236) | function getID(node) {
function internalGetID (line 11254) | function internalGetID(node) {
function setID (line 11267) | function setID(node, id) {
function getNode (line 11283) | function getNode(id) {
function getNodeFromInstance (line 11297) | function getNodeFromInstance(instance) {
function isValid (line 11318) | function isValid(node, id) {
function purgeID (line 11336) | function purgeID(id) {
function findDeepestCachedAncestorImpl (line 11341) | function findDeepestCachedAncestorImpl(ancestorID) {
function findDeepestCachedAncestor (line 11355) | function findDeepestCachedAncestor(targetID) {
function mountComponentIntoNode (line 11373) | function mountComponentIntoNode(componentInstance, rootID, container, tr...
function batchedMountComponentIntoNode (line 11402) | function batchedMountComponentIntoNode(componentInstance, rootID, contai...
function unmountComponentFromNode (line 11418) | function unmountComponentFromNode(instance, container) {
function hasNonRootReactChild (line 11441) | function hasNonRootReactChild(node) {
function findFirstReactDOMImpl (line 11450) | function findFirstReactDOMImpl(node) {
function enqueueInsertMarkup (line 12033) | function enqueueInsertMarkup(parentID, markup, toIndex) {
function enqueueMove (line 12054) | function enqueueMove(parentID, fromIndex, toIndex) {
function enqueueRemove (line 12074) | function enqueueRemove(parentID, fromIndex) {
function enqueueSetMarkup (line 12094) | function enqueueSetMarkup(parentID, markup) {
function enqueueTextContent (line 12114) | function enqueueTextContent(parentID, textContent) {
function processQueue (line 12132) | function processQueue() {
function clearQueue (line 12144) | function clearQueue() {
function getComponentClassForElement (line 12551) | function getComponentClassForElement(element) {
function createInternalComponent (line 12569) | function createInternalComponent(element) {
function createInstanceForText (line 12578) | function createInstanceForText(text) {
function isTextComponent (line 12586) | function isTextComponent(component) {
function warnTDZ (line 12615) | function warnTDZ(publicInstance, callerName) {
function _noMeasure (line 12902) | function _noMeasure(objName, fnName, func) {
function createTransferStrategy (line 12932) | function createTransferStrategy(mergeStrategy) {
function transferInto (line 12977) | function transferInto(props, newProps) {
function createChainableTypeChecker (line 13152) | function createChainableTypeChecker(validate) {
function createPrimitiveTypeChecker (line 13173) | function createPrimitiveTypeChecker(expectedType) {
function createAnyTypeChecker (line 13191) | function createAnyTypeChecker() {
function createArrayOfTypeChecker (line 13195) | function createArrayOfTypeChecker(typeChecker) {
function createElementTypeChecker (line 13214) | function createElementTypeChecker() {
function createInstanceTypeChecker (line 13225) | function createInstanceTypeChecker(expectedClass) {
function createEnumTypeChecker (line 13238) | function createEnumTypeChecker(expectedValues) {
function createObjectOfTypeChecker (line 13260) | function createObjectOfTypeChecker(typeChecker) {
function createUnionTypeChecker (line 13281) | function createUnionTypeChecker(arrayOfTypeCheckers) {
function createNodeChecker (line 13302) | function createNodeChecker() {
function createShapeTypeChecker (line 13313) | function createShapeTypeChecker(shapeTypes) {
function isNode (line 13336) | function isNode(propValue) {
function getPropType (line 13384) | function getPropType(propValue) {
function getPreciseType (line 13400) | function getPreciseType(propValue) {
function getClassName (line 13413) | function getClassName(propValue) {
function ReactReconcileTransaction (line 13527) | function ReactReconcileTransaction(forceHTML) {
function attachRefs (line 13593) | function attachRefs() {
function attachRef (line 13699) | function attachRef(ref, component, owner) {
function detachRef (line 13708) | function detachRef(ref, component, owner) {
function renderToString (line 13844) | function renderToString(element) {
function renderToStaticMarkup (line 13872) | function renderToStaticMarkup(element) {
function ReactServerRenderingTransaction (line 13946) | function ReactServerRenderingTransaction(renderToStaticMarkup) {
function createStateKeySetter (line 14038) | function createStateKeySetter(component, key) {
function Event (line 14126) | function Event(suffix) {}
function findAllInRenderedTreeInternal (line 14132) | function findAllInRenderedTreeInternal(inst, test) {
function makeSimulator (line 14467) | function makeSimulator(eventType) {
function buildSimulators (line 14498) | function buildSimulators() {
function makeNativeSimulator (line 14541) | function makeNativeSimulator(eventType) {
function getValueForKey (line 14618) | function getValueForKey(key) {
function detectEvents (line 14705) | function detectEvents() {
function addEventListener (line 14742) | function addEventListener(node, eventName, eventListener) {
function removeEventListener (line 14746) | function removeEventListener(node, eventName, eventListener) {
function enqueueUpdate (line 15003) | function enqueueUpdate(internalInstance) {
function getInternalInstanceReadyForUpdate (line 15007) | function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
function ensureInjected (line 15267) | function ensureInjected() {
function ReactUpdatesFlushTransaction (line 15301) | function ReactUpdatesFlushTransaction() {
function batchedUpdates (line 15330) | function batchedUpdates(callback, a, b, c, d, e) {
function mountOrderComparator (line 15342) | function mountOrderComparator(c1, c2) {
function runBatchedUpdates (line 15346) | function runBatchedUpdates(transaction) {
function enqueueUpdate (line 15404) | function enqueueUpdate(component) {
function asap (line 15425) | function asap(callback, context) {
function getSelection (line 15663) | function getSelection(node) {
function constructSelectEvent (line 15694) | function constructSelectEvent(nativeEvent, nativeEventTarget) {
function SyntheticClipboardEvent (line 16458) | function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeE...
function SyntheticCompositionEvent (line 16496) | function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativ...
function SyntheticDragEvent (line 16534) | function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent,...
function SyntheticEvent (line 16597) | function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nat...
function SyntheticFocusEvent (line 16750) | function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticInputEvent (line 16789) | function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticKeyboardEvent (line 16875) | function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEv...
function SyntheticMouseEvent (line 16949) | function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticTouchEvent (line 16996) | function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticUIEvent (line 17057) | function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, n...
function SyntheticWheelEvent (line 17113) | function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent...
function accumulateInto (line 17410) | function accumulateInto(current, next) {
function adler32 (line 17461) | function adler32(data) {
function cloneWithProps (line 17543) | function cloneWithProps(child, props) {
function dangerousStyleValue (line 17591) | function dangerousStyleValue(name, value) {
function deprecated (line 17647) | function deprecated(fnName, newModule, newPackage, ctx, fn) {
function escaper (line 17692) | function escaper(match) {
function escapeTextContentForBrowser (line 17702) | function escapeTextContentForBrowser(text) {
function findDOMNode (line 17735) | function findDOMNode(componentOrElement) {
function flattenSingleChildIntoContext (line 17779) | function flattenSingleChildIntoContext(traverseContext, child, name) {
function flattenChildren (line 17796) | function flattenChildren(children) {
function getEventCharCode (line 17861) | function getEventCharCode(nativeEvent) {
function getEventKey (line 17961) | function getEventKey(nativeEvent) {
function modifierStateGetter (line 18021) | function modifierStateGetter(keyArg) {
function getEventModifierState (line 18031) | function getEventModifierState(nativeEvent) {
function getEventTarget (line 18058) | function getEventTarget(nativeEvent) {
function getIteratorFn (line 18099) | function getIteratorFn(maybeIterable) {
function getLeafNode (line 18127) | function getLeafNode(node) {
function getSiblingNode (line 18141) | function getSiblingNode(node) {
function getNodeForCharacterOffset (line 18157) | function getNodeForCharacterOffset(root, offset) {
function getTextContentAccessor (line 18205) | function getTextContentAccessor() {
function getDeclarationErrorAddendum (line 18244) | function getDeclarationErrorAddendum(owner) {
function isInternalComponentType (line 18261) | function isInternalComponentType(type) {
function instantiateReactComponent (line 18272) | function instantiateReactComponent(node) {
function isEventSupported (line 18366) | function isEventSupported(eventNameSuffix, capture) {
function isTextInputElement (line 18424) | function isTextInputElement(elem) {
function onlyChild (line 18458) | function onlyChild(children) {
function quoteAttributeValueForBrowser (line 18486) | function quoteAttributeValueForBrowser(value) {
function shallowCompare (line 18660) | function shallowCompare(instance, nextProps, nextState) {
function shouldUpdateReactComponent (line 18691) | function shouldUpdateReactComponent(prevElement, nextElement) {
function userProvidedKeyEscaper (line 18749) | function userProvidedKeyEscaper(match) {
function getComponentKey (line 18760) | function getComponentKey(component, index) {
function escapeUserProvidedKey (line 18775) | function escapeUserProvidedKey(text) {
function wrapUserProvidedKey (line 18786) | function wrapUserProvidedKey(key) {
function traverseAllChildrenImpl (line 18798) | function traverseAllChildrenImpl(children, nameSoFar, callback, traverse...
function traverseAllChildren (line 18890) | function traverseAllChildren(children, callback, traverseContext) {
function shallowCopy (line 18920) | function shallowCopy(x) {
function invariantArrayCase (line 18945) | function invariantArrayCase(value, spec, command) {
function update (line 18951) | function update(value, spec) {
function camelize (line 19617) | function camelize(string) {
function camelizeStyleName (line 19660) | function camelizeStyleName(string) {
function containsNode (line 19691) | function containsNode(_x, _x2) {
function hasArrayNature (line 19753) | function hasArrayNature(obj) {
function createArrayFromMixed (line 19796) | function createArrayFromMixed(obj) {
function getNodeName (line 19846) | function getNodeName(markup) {
function createNodesFromMarkup (line 19861) | function createNodesFromMarkup(markup, handleScript) {
function makeEmptyFunction (line 19906) | function makeEmptyFunction(arg) {
function emptyFunction (line 19917) | function emptyFunction() {}
function focusNode (line 19969) | function focusNode(node) {
function getActiveElement (line 20003) | function getActiveElement() /*?DOMElement*/{
function getMarkupWrap (line 20094) | function getMarkupWrap(nodeName) {
function getUnboundedScrollPosition (line 20136) | function getUnboundedScrollPosition(scrollable) {
function hyphenate (line 20179) | function hyphenate(string) {
function hyphenateStyleName (line 20219) | function hyphenateStyleName(string) {
function invariant (line 20249) | function invariant(condition, format, a, b, c, d, e, f) {
function isNode (line 20294) | function isNode(object) {
function isTextNode (line 20320) | function isTextNode(object) {
function joinClasses (line 20347) | function joinClasses(className /*, ... */) {
function mapObject (line 20488) | function mapObject(object, callback, context) {
function memoizeStringOnly (line 20523) | function memoizeStringOnly(callback) {
function shallowEqual (line 20616) | function shallowEqual(objA, objB) {
function toArray (line 20670) | function toArray(obj) {
FILE: presetlib/react-0.14.6/build/react.js
function s (line 4) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
function isPresto (line 130) | function isPresto() {
function isKeypressCommand (line 180) | function isKeypressCommand(nativeEvent) {
function getCompositionEventType (line 192) | function getCompositionEventType(topLevelType) {
function isFallbackCompositionStart (line 211) | function isFallbackCompositionStart(topLevelType, nativeEvent) {
function isFallbackCompositionEnd (line 222) | function isFallbackCompositionEnd(topLevelType, nativeEvent) {
function getDataFromCustomEvent (line 250) | function getDataFromCustomEvent(nativeEvent) {
function extractCompositionEvent (line 268) | function extractCompositionEvent(topLevelType, topLevelTarget, topLevelT...
function getNativeBeforeInputChars (line 320) | function getNativeBeforeInputChars(topLevelType, nativeEvent) {
function getFallbackBeforeInputChars (line 374) | function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
function extractBeforeInputEvent (line 430) | function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelT...
function prefixKey (line 542) | function prefixKey(prefix, key) {
function CallbackQueue (line 834) | function CallbackQueue() {
function shouldUseChangeEvent (line 947) | function shouldUseChangeEvent(elem) {
function manualDispatchChangeEvent (line 958) | function manualDispatchChangeEvent(nativeEvent) {
function runEventInBatch (line 976) | function runEventInBatch(event) {
function startWatchingForChangeEventIE8 (line 981) | function startWatchingForChangeEventIE8(target, targetID) {
function stopWatchingForChangeEventIE8 (line 987) | function stopWatchingForChangeEventIE8() {
function getTargetIDForChangeEvent (line 996) | function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLeve...
function handleEventsForChangeEventIE8 (line 1001) | function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, top...
function startWatchingForValueChange (line 1042) | function startWatchingForValueChange(target, targetID) {
function stopWatchingForValueChange (line 1058) | function stopWatchingForValueChange() {
function handlePropertyChange (line 1077) | function handlePropertyChange(nativeEvent) {
function getTargetIDForInputEvent (line 1093) | function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevel...
function handleEventsForInputEventIE (line 1102) | function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLe...
function getTargetIDForInputEventIE (line 1125) | function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLev...
function shouldUseClickEvent (line 1147) | function shouldUseClickEvent(elem) {
function getTargetIDForClickEvent (line 1154) | function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevel...
function insertChildAt (line 1275) | function insertChildAt(parentNode, childNode, index) {
function checkMask (line 1391) | function checkMask(value, bitmask) {
function isAttributeNameSafe (line 1635) | function isAttributeNameSafe(attributeName) {
function shouldIgnoreValue (line 1651) | function shouldIgnoreValue(propertyInfo, value) {
function getNodeName (line 1871) | function getNodeName(markup) {
function validateInstanceHandle (line 2290) | function validateInstanceHandle() {
function recomputePluginOrdering (line 2539) | function recomputePluginOrdering() {
function publishEventForPlugin (line 2568) | function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
function publishRegistrationName (line 2596) | function publishRegistrationName(registrationName, PluginModule, eventNa...
function isEndish (line 2768) | function isEndish(topLevelType) {
function isMoveish (line 2772) | function isMoveish(topLevelType) {
function isStartish (line 2775) | function isStartish(topLevelType) {
function executeDispatch (line 2801) | function executeDispatch(event, simulated, listener, domID) {
function executeDispatchesInOrder (line 2815) | function executeDispatchesInOrder(event, simulated) {
function executeDispatchesInOrderStopAtTrueImpl (line 2843) | function executeDispatchesInOrderStopAtTrueImpl(event) {
function executeDispatchesInOrderStopAtTrue (line 2870) | function executeDispatchesInOrderStopAtTrue(event) {
function executeDirectDispatch (line 2886) | function executeDirectDispatch(event) {
function hasDispatches (line 2903) | function hasDispatches(event) {
function listenerAtPhase (line 2960) | function listenerAtPhase(id, event, propagationPhase) {
function accumulateDirectionalDispatches (line 2971) | function accumulateDirectionalDispatches(domID, upwards, event) {
function accumulateTwoPhaseDispatchesSingle (line 2990) | function accumulateTwoPhaseDispatchesSingle(event) {
function accumulateTwoPhaseDispatchesSingleSkipTarget (line 2999) | function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
function accumulateDispatches (line 3010) | function accumulateDispatches(id, ignoredDirection, event) {
function accumulateDirectDispatchesSingle (line 3026) | function accumulateDirectDispatchesSingle(event) {
function accumulateTwoPhaseDispatches (line 3032) | function accumulateTwoPhaseDispatches(events) {
function accumulateTwoPhaseDispatchesSkipTarget (line 3036) | function accumulateTwoPhaseDispatchesSkipTarget(events) {
function accumulateEnterLeaveDispatches (line 3040) | function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
function accumulateDirectDispatches (line 3044) | function accumulateDirectDispatches(events) {
function FallbackCompositionState (line 3098) | function FallbackCompositionState(root) {
function _assertSingleLink (line 3425) | function _assertSingleLink(inputProps) {
function _assertValueLink (line 3428) | function _assertValueLink(inputProps) {
function _assertCheckedLink (line 3433) | function _assertCheckedLink(inputProps) {
function getDeclarationErrorAddendum (line 3455) | function getDeclarationErrorAddendum(owner) {
function assign (line 3545) | function assign(target, sources) {
function getListeningForDocument (line 3889) | function getListeningForDocument(mountAt) {
function instantiateChild (line 4081) | function instantiateChild(childInstances, child, name) {
function escapeUserProvidedKey (line 4206) | function escapeUserProvidedKey(text) {
function ForEachBookKeeping (line 4218) | function ForEachBookKeeping(forEachFunction, forEachContext) {
function forEachSingleChild (line 4230) | function forEachSingleChild(bookKeeping, child, name) {
function forEachChildren (line 4247) | function forEachChildren(children, forEachFunc, forEachContext) {
function MapBookKeeping (line 4265) | function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
function mapSingleChildIntoContext (line 4281) | function mapSingleChildIntoContext(bookKeeping, child, childKey) {
function mapIntoWithKeyPrefixInternal (line 4301) | function mapIntoWithKeyPrefixInternal(children, array, prefix, func, con...
function mapChildren (line 4322) | function mapChildren(children, func, context) {
function forEachSingleChildDummy (line 4331) | function forEachSingleChildDummy(traverseContext, child, name) {
function countChildren (line 4342) | function countChildren(children, context) {
function toArray (line 4350) | function toArray(children) {
function warnSetProps (line 4422) | function warnSetProps() {
function validateTypeDef (line 4729) | function validateTypeDef(Constructor, typeDef, location) {
function validateMethodOverride (line 4739) | function validateMethodOverride(proto, name) {
function mixSpecIntoComponent (line 4757) | function mixSpecIntoComponent(Constructor, spec) {
function mixStaticSpecIntoComponent (line 4834) | function mixStaticSpecIntoComponent(Constructor, statics) {
function mergeIntoWithNoDuplicateKeys (line 4860) | function mergeIntoWithNoDuplicateKeys(one, two) {
function createMergedResultFunction (line 4880) | function createMergedResultFunction(one, two) {
function createChainedFunction (line 4904) | function createChainedFunction(one, two) {
function bindAutoBindMethod (line 4918) | function bindAutoBindMethod(component, method) {
function bindAutoBindMethods (line 4957) | function bindAutoBindMethods(component) {
function ReactComponent (line 5161) | function ReactComponent(props, context, updater) {
function getDeclarationErrorAddendum (line 5384) | function getDeclarationErrorAddendum(component) {
function StatelessComponent (line 5395) | function StatelessComponent(Component) {}
function getDeclarationErrorAddendum (line 6283) | function getDeclarationErrorAddendum(internalInstance) {
function legacyGetDOMNode (line 6310) | function legacyGetDOMNode() {
function legacyIsMounted (line 6318) | function legacyIsMounted() {
function legacySetStateEtc (line 6326) | function legacySetStateEtc() {
function legacySetProps (line 6333) | function legacySetProps(partialProps, callback) {
function legacyReplaceProps (line 6347) | function legacyReplaceProps(partialProps, callback) {
function friendlyStringify (line 6361) | function friendlyStringify(obj) {
function checkAndWarnForMutatedStyle (line 6387) | function checkAndWarnForMutatedStyle(style1, style2, component) {
function assertValidProps (line 6417) | function assertValidProps(component, props) {
function enqueuePutListener (line 6438) | function enqueuePutListener(id, registrationName, listener, transaction) {
function putListener (line 6456) | function putListener() {
function trapBubbledEventsLocal (line 6489) | function trapBubbledEventsLocal() {
function mountReadyInputWrapper (line 6522) | function mountReadyInputWrapper() {
function postUpdateSelectWrapper (line 6526) | function postUpdateSelectWrapper() {
function validateDangerousTag (line 6573) | function validateDangerousTag(tag) {
function processChildContextDev (line 6580) | function processChildContextDev(context, inst) {
function isCustomComponent (line 6588) | function isCustomComponent(tagName, props) {
function ReactDOMComponent (line 6606) | function ReactDOMComponent(tag) {
function createDOMFactory (line 7213) | function createDOMFactory(tag) {
function forceUpdateIfMounted (line 7503) | function forceUpdateIfMounted() {
function _handleChange (line 7582) | function _handleChange(event) {
function updateOptionsIfPendingUpdateAndMounted (line 7743) | function updateOptionsIfPendingUpdateAndMounted() {
function getDeclarationErrorAddendum (line 7756) | function getDeclarationErrorAddendum(owner) {
function checkSelectPropTypes (line 7772) | function checkSelectPropTypes(inst, props) {
function updateOptions (line 7795) | function updateOptions(inst, multiple, propValue) {
function _handleChange (line 7899) | function _handleChange(event) {
function isCollapsed (line 7933) | function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
function getIEOffsets (line 7951) | function getIEOffsets(node) {
function getModernOffsets (line 7974) | function getModernOffsets(node) {
function setIEOffsets (line 8036) | function setIEOffsets(node, offsets) {
function setModernOffsets (line 8070) | function setModernOffsets(node, offsets) {
function forceUpdateIfMounted (line 8299) | function forceUpdateIfMounted() {
function _handleChange (line 8383) | function _handleChange(event) {
function ReactDefaultBatchingStrategyTransaction (line 8425) | function ReactDefaultBatchingStrategyTransaction() {
function inject (line 8497) | function inject() {
function roundFloat (line 8579) | function roundFloat(val) {
function addValue (line 8583) | function addValue(obj, key, val) {
function getTotalTime (line 8828) | function getTotalTime(measurements) {
function getDOMSummary (line 8841) | function getDOMSummary(measurements) {
function getExclusiveSummary (line 8857) | function getExclusiveSummary(measurements) {
function getInclusiveSummary (line 8905) | function getInclusiveSummary(measurements, onlyClean) {
function getUnchangedComponents (line 8960) | function getUnchangedComponents(measurement) {
function getDeclarationErrorAddendum (line 9276) | function getDeclarationErrorAddendum() {
function validateExplicitKey (line 9305) | function validateExplicitKey(element, parentType) {
function getAddendaForKeyUse (line 9329) | function getAddendaForKeyUse(messageType, element, parentType) {
function validateChildKeys (line 9370) | function validateChildKeys(node, parentType) {
function checkPropTypes (line 9412) | function checkPropTypes(componentName, propTypes, props, location) {
function validatePropTypes (line 9446) | function validatePropTypes(element) {
function isNullComponentID (line 9601) | function isNullComponentID(id) {
function registerNullComponentID (line 9609) | function registerNullComponentID(id) {
function deregisterNullComponentID (line 9617) | function deregisterNullComponentID(id) {
function invokeGuardedCallback (line 9653) | function invokeGuardedCallback(name, func, a, b) {
function runEventQueueInBatch (line 9722) | function runEventQueueInBatch(events) {
function findParent (line 9780) | function findParent(node) {
function TopLevelCallbackBookKeeping (line 9792) | function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
function handleTopLevelImpl (line 9806) | function handleTopLevelImpl(bookKeeping) {
function handleTopLevelWithoutPath (line 9822) | function handleTopLevelWithoutPath(bookKeeping) {
function handleTopLevelWithPath (line 9843) | function handleTopLevelWithPath(bookKeeping) {
function scrollValueMonitor (line 9876) | function scrollValueMonitor(cb) {
function isInDocument (line 10016) | function isInDocument(node) {
function getReactRootIDString (line 10155) | function getReactRootIDString(index) {
function isBoundary (line 10167) | function isBoundary(id, index) {
function isValidID (line 10178) | function isValidID(id) {
function isAncestorIDOf (line 10190) | function isAncestorIDOf(ancestorID, descendantID) {
function getParentID (line 10201) | function getParentID(id) {
function getNextDescendantID (line 10214) | function getNextDescendantID(ancestorID, destinationID) {
function getFirstCommonAncestorID (line 10243) | function getFirstCommonAncestorID(oneID, twoID) {
function traverseParentPath (line 10275) | function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
function firstDifferenceIndex (line 10660) | function firstDifferenceIndex(string1, string2) {
function getReactRootElementInContainer (line 10675) | function getReactRootElementInContainer(container) {
function getReactRootID (line 10691) | function getReactRootID(container) {
function getID (line 10706) | function getID(node) {
function internalGetID (line 10724) | function internalGetID(node) {
function setID (line 10737) | function setID(node, id) {
function getNode (line 10753) | function getNode(id) {
function getNodeFromInstance (line 10767) | function getNodeFromInstance(instance) {
function isValid (line 10788) | function isValid(node, id) {
function purgeID (line 10806) | function purgeID(id) {
function findDeepestCachedAncestorImpl (line 10811) | function findDeepestCachedAncestorImpl(ancestorID) {
function findDeepestCachedAncestor (line 10825) | function findDeepestCachedAncestor(targetID) {
function mountComponentIntoNode (line 10843) | function mountComponentIntoNode(componentInstance, rootID, container, tr...
function batchedMountComponentIntoNode (line 10872) | function batchedMountComponentIntoNode(componentInstance, rootID, contai...
function unmountComponentFromNode (line 10888) | function unmountComponentFromNode(instance, container) {
function hasNonRootReactChild (line 10911) | function hasNonRootReactChild(node) {
function findFirstReactDOMImpl (line 10920) | function findFirstReactDOMImpl(node) {
function enqueueInsertMarkup (line 11503) | function enqueueInsertMarkup(parentID, markup, toIndex) {
function enqueueMove (line 11524) | function enqueueMove(parentID, fromIndex, toIndex) {
function enqueueRemove (line 11544) | function enqueueRemove(parentID, fromIndex) {
function enqueueSetMarkup (line 11564) | function enqueueSetMarkup(parentID, markup) {
function enqueueTextContent (line 11584) | function enqueueTextContent(parentID, textContent) {
function processQueue (line 11602) | function processQueue() {
function clearQueue (line 11614) | function clearQueue() {
function getComponentClassForElement (line 12021) | function getComponentClassForElement(element) {
function createInternalComponent (line 12039) | function createInternalComponent(element) {
function createInstanceForText (line 12048) | function createInstanceForText(text) {
function isTextComponent (line 12056) | function isTextComponent(component) {
function warnTDZ (line 12085) | function warnTDZ(publicInstance, callerName) {
function _noMeasure (line 12372) | function _noMeasure(objName, fnName, func) {
function createChainableTypeChecker (line 12513) | function createChainableTypeChecker(validate) {
function createPrimitiveTypeChecker (line 12534) | function createPrimitiveTypeChecker(expectedType) {
function createAnyTypeChecker (line 12552) | function createAnyTypeChecker() {
function createArrayOfTypeChecker (line 12556) | function createArrayOfTypeChecker(typeChecker) {
function createElementTypeChecker (line 12575) | function createElementTypeChecker() {
function createInstanceTypeChecker (line 12586) | function createInstanceTypeChecker(expectedClass) {
function createEnumTypeChecker (line 12599) | function createEnumTypeChecker(expectedValues) {
function createObjectOfTypeChecker (line 12621) | function createObjectOfTypeChecker(typeChecker) {
function createUnionTypeChecker (line 12642) | function createUnionTypeChecker(arrayOfTypeCheckers) {
function createNodeChecker (line 12663) | function createNodeChecker() {
function createShapeTypeChecker (line 12674) | function createShapeTypeChecker(shapeTypes) {
function isNode (line 12697) | function isNode(propValue) {
function getPropType (line 12745) | function getPropType(propValue) {
function getPreciseType (line 12761) | function getPreciseType(propValue) {
function getClassName (line 12774) | function getClassName(propValue) {
function ReactReconcileTransaction (line 12888) | function ReactReconcileTransaction(forceHTML) {
function attachRefs (line 12954) | function attachRefs() {
function attachRef (line 13060) | function attachRef(ref, component, owner) {
function detachRef (line 13069) | function detachRef(ref, component, owner) {
function renderToString (line 13205) | function renderToString(element) {
function renderToStaticMarkup (line 13233) | function renderToStaticMarkup(element) {
function ReactServerRenderingTransaction (line 13307) | function ReactServerRenderingTransaction(renderToStaticMarkup) {
function enqueueUpdate (line 13370) | function enqueueUpdate(internalInstance) {
function getInternalInstanceReadyForUpdate (line 13374) | function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
function ensureInjected (line 13634) | function ensureInjected() {
function ReactUpdatesFlushTransaction (line 13668) | function ReactUpdatesFlushTransaction() {
function batchedUpdates (line 13697) | function batchedUpdates(callback, a, b, c, d, e) {
function mountOrderComparator (line 13709) | function mountOrderComparator(c1, c2) {
function runBatchedUpdates (line 13713) | function runBatchedUpdates(transaction) {
function enqueueUpdate (line 13771) | function enqueueUpdate(component) {
function asap (line 13792) | function asap(callback, context) {
function getSelection (line 14030) | function getSelection(node) {
function constructSelectEvent (line 14061) | function constructSelectEvent(nativeEvent, nativeEventTarget) {
function SyntheticClipboardEvent (line 14825) | function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeE...
function SyntheticCompositionEvent (line 14863) | function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativ...
function SyntheticDragEvent (line 14901) | function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent,...
function SyntheticEvent (line 14964) | function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nat...
function SyntheticFocusEvent (line 15117) | function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticInputEvent (line 15156) | function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticKeyboardEvent (line 15242) | function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEv...
function SyntheticMouseEvent (line 15316) | function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticTouchEvent (line 15363) | function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticUIEvent (line 15424) | function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, n...
function SyntheticWheelEvent (line 15480) | function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent...
function accumulateInto (line 15777) | function accumulateInto(current, next) {
function adler32 (line 15828) | function adler32(data) {
function dangerousStyleValue (line 15903) | function dangerousStyleValue(name, value) {
function deprecated (line 15959) | function deprecated(fnName, newModule, newPackage, ctx, fn) {
function escaper (line 16004) | function escaper(match) {
function escapeTextContentForBrowser (line 16014) | function escapeTextContentForBrowser(text) {
function findDOMNode (line 16047) | function findDOMNode(componentOrElement) {
function flattenSingleChildIntoContext (line 16091) | function flattenSingleChildIntoContext(traverseContext, child, name) {
function flattenChildren (line 16108) | function flattenChildren(children) {
function getEventCharCode (line 16173) | function getEventCharCode(nativeEvent) {
function getEventKey (line 16273) | function getEventKey(nativeEvent) {
function modifierStateGetter (line 16333) | function modifierStateGetter(keyArg) {
function getEventModifierState (line 16343) | function getEventModifierState(nativeEvent) {
function getEventTarget (line 16370) | function getEventTarget(nativeEvent) {
function getIteratorFn (line 16411) | function getIteratorFn(maybeIterable) {
function getLeafNode (line 16439) | function getLeafNode(node) {
function getSiblingNode (line 16453) | function getSiblingNode(node) {
function getNodeForCharacterOffset (line 16469) | function getNodeForCharacterOffset(root, offset) {
function getTextContentAccessor (line 16517) | function getTextContentAccessor() {
function getDeclarationErrorAddendum (line 16556) | function getDeclarationErrorAddendum(owner) {
function isInternalComponentType (line 16573) | function isInternalComponentType(type) {
function instantiateReactComponent (line 16584) | function instantiateReactComponent(node) {
function isEventSupported (line 16678) | function isEventSupported(eventNameSuffix, capture) {
function isTextInputElement (line 16736) | function isTextInputElement(elem) {
function onlyChild (line 16770) | function onlyChild(children) {
function quoteAttributeValueForBrowser (line 16798) | function quoteAttributeValueForBrowser(value) {
function shouldUpdateReactComponent (line 16978) | function shouldUpdateReactComponent(prevElement, nextElement) {
function userProvidedKeyEscaper (line 17036) | function userProvidedKeyEscaper(match) {
function getComponentKey (line 17047) | function getComponentKey(component, index) {
function escapeUserProvidedKey (line 17062) | function escapeUserProvidedKey(text) {
function wrapUserProvidedKey (line 17073) | function wrapUserProvidedKey(key) {
function traverseAllChildrenImpl (line 17085) | function traverseAllChildrenImpl(children, nameSoFar, callback, traverse...
function traverseAllChildren (line 17177) | function traverseAllChildren(children, callback, traverseContext) {
function camelize (line 17698) | function camelize(string) {
function camelizeStyleName (line 17741) | function camelizeStyleName(string) {
function containsNode (line 17772) | function containsNode(_x, _x2) {
function hasArrayNature (line 17834) | function hasArrayNature(obj) {
function createArrayFromMixed (line 17877) | function createArrayFromMixed(obj) {
function getNodeName (line 17927) | function getNodeName(markup) {
function createNodesFromMarkup (line 17942) | function createNodesFromMarkup(markup, handleScript) {
function makeEmptyFunction (line 17987) | function makeEmptyFunction(arg) {
function emptyFunction (line 17998) | function emptyFunction() {}
function focusNode (line 18050) | function focusNode(node) {
function getActiveElement (line 18084) | function getActiveElement() /*?DOMElement*/{
function getMarkupWrap (line 18175) | function getMarkupWrap(nodeName) {
function getUnboundedScrollPosition (line 18217) | function getUnboundedScrollPosition(scrollable) {
function hyphenate (line 18260) | function hyphenate(string) {
function hyphenateStyleName (line 18300) | function hyphenateStyleName(string) {
function invariant (line 18330) | function invariant(condition, format, a, b, c, d, e, f) {
function isNode (line 18375) | function isNode(object) {
function isTextNode (line 18401) | function isTextNode(object) {
function mapObject (line 18529) | function mapObject(object, callback, context) {
function memoizeStringOnly (line 18564) | function memoizeStringOnly(callback) {
function shallowEqual (line 18657) | function shallowEqual(objA, objB) {
function toArray (line 18711) | function toArray(obj) {
FILE: presetlib/react.js
function s (line 4) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
function isPresto (line 136) | function isPresto() {
function isKeypressCommand (line 186) | function isKeypressCommand(nativeEvent) {
function getCompositionEventType (line 198) | function getCompositionEventType(topLevelType) {
function isFallbackCompositionStart (line 217) | function isFallbackCompositionStart(topLevelType, nativeEvent) {
function isFallbackCompositionEnd (line 228) | function isFallbackCompositionEnd(topLevelType, nativeEvent) {
function getDataFromCustomEvent (line 256) | function getDataFromCustomEvent(nativeEvent) {
function extractCompositionEvent (line 274) | function extractCompositionEvent(topLevelType, topLevelTarget, topLevelT...
function getNativeBeforeInputChars (line 326) | function getNativeBeforeInputChars(topLevelType, nativeEvent) {
function getFallbackBeforeInputChars (line 380) | function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
function extractBeforeInputEvent (line 436) | function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelT...
function prefixKey (line 548) | function prefixKey(prefix, key) {
function CallbackQueue (line 840) | function CallbackQueue() {
function shouldUseChangeEvent (line 953) | function shouldUseChangeEvent(elem) {
function manualDispatchChangeEvent (line 964) | function manualDispatchChangeEvent(nativeEvent) {
function runEventInBatch (line 982) | function runEventInBatch(event) {
function startWatchingForChangeEventIE8 (line 987) | function startWatchingForChangeEventIE8(target, targetID) {
function stopWatchingForChangeEventIE8 (line 993) | function stopWatchingForChangeEventIE8() {
function getTargetIDForChangeEvent (line 1002) | function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLeve...
function handleEventsForChangeEventIE8 (line 1007) | function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, top...
function startWatchingForValueChange (line 1048) | function startWatchingForValueChange(target, targetID) {
function stopWatchingForValueChange (line 1064) | function stopWatchingForValueChange() {
function handlePropertyChange (line 1083) | function handlePropertyChange(nativeEvent) {
function getTargetIDForInputEvent (line 1099) | function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevel...
function handleEventsForInputEventIE (line 1108) | function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLe...
function getTargetIDForInputEventIE (line 1131) | function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLev...
function shouldUseClickEvent (line 1153) | function shouldUseClickEvent(elem) {
function getTargetIDForClickEvent (line 1160) | function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevel...
function insertChildAt (line 1281) | function insertChildAt(parentNode, childNode, index) {
function checkMask (line 1397) | function checkMask(value, bitmask) {
function isAttributeNameSafe (line 1641) | function isAttributeNameSafe(attributeName) {
function shouldIgnoreValue (line 1657) | function shouldIgnoreValue(propertyInfo, value) {
function getNodeName (line 1877) | function getNodeName(markup) {
function validateInstanceHandle (line 2296) | function validateInstanceHandle() {
function recomputePluginOrdering (line 2545) | function recomputePluginOrdering() {
function publishEventForPlugin (line 2574) | function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
function publishRegistrationName (line 2602) | function publishRegistrationName(registrationName, PluginModule, eventNa...
function isEndish (line 2774) | function isEndish(topLevelType) {
function isMoveish (line 2778) | function isMoveish(topLevelType) {
function isStartish (line 2781) | function isStartish(topLevelType) {
function executeDispatch (line 2807) | function executeDispatch(event, simulated, listener, domID) {
function executeDispatchesInOrder (line 2821) | function executeDispatchesInOrder(event, simulated) {
function executeDispatchesInOrderStopAtTrueImpl (line 2849) | function executeDispatchesInOrderStopAtTrueImpl(event) {
function executeDispatchesInOrderStopAtTrue (line 2876) | function executeDispatchesInOrderStopAtTrue(event) {
function executeDirectDispatch (line 2892) | function executeDirectDispatch(event) {
function hasDispatches (line 2909) | function hasDispatches(event) {
function listenerAtPhase (line 2966) | function listenerAtPhase(id, event, propagationPhase) {
function accumulateDirectionalDispatches (line 2977) | function accumulateDirectionalDispatches(domID, upwards, event) {
function accumulateTwoPhaseDispatchesSingle (line 2996) | function accumulateTwoPhaseDispatchesSingle(event) {
function accumulateTwoPhaseDispatchesSingleSkipTarget (line 3005) | function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
function accumulateDispatches (line 3016) | function accumulateDispatches(id, ignoredDirection, event) {
function accumulateDirectDispatchesSingle (line 3032) | function accumulateDirectDispatchesSingle(event) {
function accumulateTwoPhaseDispatches (line 3038) | function accumulateTwoPhaseDispatches(events) {
function accumulateTwoPhaseDispatchesSkipTarget (line 3042) | function accumulateTwoPhaseDispatchesSkipTarget(events) {
function accumulateEnterLeaveDispatches (line 3046) | function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
function accumulateDirectDispatches (line 3050) | function accumulateDirectDispatches(events) {
function FallbackCompositionState (line 3104) | function FallbackCompositionState(root) {
function _assertSingleLink (line 3431) | function _assertSingleLink(inputProps) {
function _assertValueLink (line 3434) | function _assertValueLink(inputProps) {
function _assertCheckedLink (line 3439) | function _assertCheckedLink(inputProps) {
function getDeclarationErrorAddendum (line 3461) | function getDeclarationErrorAddendum(owner) {
function assign (line 3551) | function assign(target, sources) {
function getListeningForDocument (line 3895) | function getListeningForDocument(mountAt) {
function instantiateChild (line 4087) | function instantiateChild(childInstances, child, name) {
function escapeUserProvidedKey (line 4212) | function escapeUserProvidedKey(text) {
function ForEachBookKeeping (line 4224) | function ForEachBookKeeping(forEachFunction, forEachContext) {
function forEachSingleChild (line 4236) | function forEachSingleChild(bookKeeping, child, name) {
function forEachChildren (line 4253) | function forEachChildren(children, forEachFunc, forEachContext) {
function MapBookKeeping (line 4271) | function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
function mapSingleChildIntoContext (line 4287) | function mapSingleChildIntoContext(bookKeeping, child, childKey) {
function mapIntoWithKeyPrefixInternal (line 4307) | function mapIntoWithKeyPrefixInternal(children, array, prefix, func, con...
function mapChildren (line 4328) | function mapChildren(children, func, context) {
function forEachSingleChildDummy (line 4337) | function forEachSingleChildDummy(traverseContext, child, name) {
function countChildren (line 4348) | function countChildren(children, context) {
function toArray (line 4356) | function toArray(children) {
function warnSetProps (line 4428) | function warnSetProps() {
function validateTypeDef (line 4735) | function validateTypeDef(Constructor, typeDef, location) {
function validateMethodOverride (line 4745) | function validateMethodOverride(proto, name) {
function mixSpecIntoComponent (line 4763) | function mixSpecIntoComponent(Constructor, spec) {
function mixStaticSpecIntoComponent (line 4840) | function mixStaticSpecIntoComponent(Constructor, statics) {
function mergeIntoWithNoDuplicateKeys (line 4866) | function mergeIntoWithNoDuplicateKeys(one, two) {
function createMergedResultFunction (line 4886) | function createMergedResultFunction(one, two) {
function createChainedFunction (line 4910) | function createChainedFunction(one, two) {
function bindAutoBindMethod (line 4924) | function bindAutoBindMethod(component, method) {
function bindAutoBindMethods (line 4963) | function bindAutoBindMethods(component) {
function ReactComponent (line 5167) | function ReactComponent(props, context, updater) {
function getDeclarationErrorAddendum (line 5390) | function getDeclarationErrorAddendum(component) {
function StatelessComponent (line 5401) | function StatelessComponent(Component) {}
function getDeclarationErrorAddendum (line 6289) | function getDeclarationErrorAddendum(internalInstance) {
function legacyGetDOMNode (line 6316) | function legacyGetDOMNode() {
function legacyIsMounted (line 6324) | function legacyIsMounted() {
function legacySetStateEtc (line 6332) | function legacySetStateEtc() {
function legacySetProps (line 6339) | function legacySetProps(partialProps, callback) {
function legacyReplaceProps (line 6353) | function legacyReplaceProps(partialProps, callback) {
function friendlyStringify (line 6367) | function friendlyStringify(obj) {
function checkAndWarnForMutatedStyle (line 6393) | function checkAndWarnForMutatedStyle(style1, style2, component) {
function assertValidProps (line 6423) | function assertValidProps(component, props) {
function enqueuePutListener (line 6444) | function enqueuePutListener(id, registrationName, listener, transaction) {
function putListener (line 6462) | function putListener() {
function trapBubbledEventsLocal (line 6495) | function trapBubbledEventsLocal() {
function mountReadyInputWrapper (line 6528) | function mountReadyInputWrapper() {
function postUpdateSelectWrapper (line 6532) | function postUpdateSelectWrapper() {
function validateDangerousTag (line 6579) | function validateDangerousTag(tag) {
function processChildContextDev (line 6586) | function processChildContextDev(context, inst) {
function isCustomComponent (line 6594) | function isCustomComponent(tagName, props) {
function ReactDOMComponent (line 6612) | function ReactDOMComponent(tag) {
function createDOMFactory (line 7219) | function createDOMFactory(tag) {
function forceUpdateIfMounted (line 7509) | function forceUpdateIfMounted() {
function _handleChange (line 7588) | function _handleChange(event) {
function updateOptionsIfPendingUpdateAndMounted (line 7749) | function updateOptionsIfPendingUpdateAndMounted() {
function getDeclarationErrorAddendum (line 7762) | function getDeclarationErrorAddendum(owner) {
function checkSelectPropTypes (line 7778) | function checkSelectPropTypes(inst, props) {
function updateOptions (line 7801) | function updateOptions(inst, multiple, propValue) {
function _handleChange (line 7905) | function _handleChange(event) {
function isCollapsed (line 7939) | function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
function getIEOffsets (line 7957) | function getIEOffsets(node) {
function getModernOffsets (line 7980) | function getModernOffsets(node) {
function setIEOffsets (line 8042) | function setIEOffsets(node, offsets) {
function setModernOffsets (line 8076) | function setModernOffsets(node, offsets) {
function forceUpdateIfMounted (line 8305) | function forceUpdateIfMounted() {
function _handleChange (line 8389) | function _handleChange(event) {
function ReactDefaultBatchingStrategyTransaction (line 8431) | function ReactDefaultBatchingStrategyTransaction() {
function inject (line 8503) | function inject() {
function roundFloat (line 8585) | function roundFloat(val) {
function addValue (line 8589) | function addValue(obj, key, val) {
function getTotalTime (line 8834) | function getTotalTime(measurements) {
function getDOMSummary (line 8847) | function getDOMSummary(measurements) {
function getExclusiveSummary (line 8863) | function getExclusiveSummary(measurements) {
function getInclusiveSummary (line 8911) | function getInclusiveSummary(measurements, onlyClean) {
function getUnchangedComponents (line 8966) | function getUnchangedComponents(measurement) {
function getDeclarationErrorAddendum (line 9282) | function getDeclarationErrorAddendum() {
function validateExplicitKey (line 9311) | function validateExplicitKey(element, parentType) {
function getAddendaForKeyUse (line 9335) | function getAddendaForKeyUse(messageType, element, parentType) {
function validateChildKeys (line 9376) | function validateChildKeys(node, parentType) {
function checkPropTypes (line 9418) | function checkPropTypes(componentName, propTypes, props, location) {
function validatePropTypes (line 9452) | function validatePropTypes(element) {
function isNullComponentID (line 9607) | function isNullComponentID(id) {
function registerNullComponentID (line 9615) | function registerNullComponentID(id) {
function deregisterNullComponentID (line 9623) | function deregisterNullComponentID(id) {
function invokeGuardedCallback (line 9659) | function invokeGuardedCallback(name, func, a, b) {
function runEventQueueInBatch (line 9728) | function runEventQueueInBatch(events) {
function findParent (line 9786) | function findParent(node) {
function TopLevelCallbackBookKeeping (line 9798) | function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
function handleTopLevelImpl (line 9812) | function handleTopLevelImpl(bookKeeping) {
function handleTopLevelWithoutPath (line 9828) | function handleTopLevelWithoutPath(bookKeeping) {
function handleTopLevelWithPath (line 9849) | function handleTopLevelWithPath(bookKeeping) {
function scrollValueMonitor (line 9882) | function scrollValueMonitor(cb) {
function isInDocument (line 10022) | function isInDocument(node) {
function getReactRootIDString (line 10161) | function getReactRootIDString(index) {
function isBoundary (line 10173) | function isBoundary(id, index) {
function isValidID (line 10184) | function isValidID(id) {
function isAncestorIDOf (line 10196) | function isAncestorIDOf(ancestorID, descendantID) {
function getParentID (line 10207) | function getParentID(id) {
function getNextDescendantID (line 10220) | function getNextDescendantID(ancestorID, destinationID) {
function getFirstCommonAncestorID (line 10249) | function getFirstCommonAncestorID(oneID, twoID) {
function traverseParentPath (line 10281) | function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
function firstDifferenceIndex (line 10666) | function firstDifferenceIndex(string1, string2) {
function getReactRootElementInContainer (line 10681) | function getReactRootElementInContainer(container) {
function getReactRootID (line 10697) | function getReactRootID(container) {
function getID (line 10712) | function getID(node) {
function internalGetID (line 10730) | function internalGetID(node) {
function setID (line 10743) | function setID(node, id) {
function getNode (line 10759) | function getNode(id) {
function getNodeFromInstance (line 10773) | function getNodeFromInstance(instance) {
function isValid (line 10794) | function isValid(node, id) {
function purgeID (line 10812) | function purgeID(id) {
function findDeepestCachedAncestorImpl (line 10817) | function findDeepestCachedAncestorImpl(ancestorID) {
function findDeepestCachedAncestor (line 10831) | function findDeepestCachedAncestor(targetID) {
function mountComponentIntoNode (line 10849) | function mountComponentIntoNode(componentInstance, rootID, container, tr...
function batchedMountComponentIntoNode (line 10878) | function batchedMountComponentIntoNode(componentInstance, rootID, contai...
function unmountComponentFromNode (line 10894) | function unmountComponentFromNode(instance, container) {
function hasNonRootReactChild (line 10917) | function hasNonRootReactChild(node) {
function findFirstReactDOMImpl (line 10926) | function findFirstReactDOMImpl(node) {
function enqueueInsertMarkup (line 11509) | function enqueueInsertMarkup(parentID, markup, toIndex) {
function enqueueMove (line 11530) | function enqueueMove(parentID, fromIndex, toIndex) {
function enqueueRemove (line 11550) | function enqueueRemove(parentID, fromIndex) {
function enqueueSetMarkup (line 11570) | function enqueueSetMarkup(parentID, markup) {
function enqueueTextContent (line 11590) | function enqueueTextContent(parentID, textContent) {
function processQueue (line 11608) | function processQueue() {
function clearQueue (line 11620) | function clearQueue() {
function getComponentClassForElement (line 12027) | function getComponentClassForElement(element) {
function createInternalComponent (line 12045) | function createInternalComponent(element) {
function createInstanceForText (line 12054) | function createInstanceForText(text) {
function isTextComponent (line 12062) | function isTextComponent(component) {
function warnTDZ (line 12091) | function warnTDZ(publicInstance, callerName) {
function _noMeasure (line 12378) | function _noMeasure(objName, fnName, func) {
function createChainableTypeChecker (line 12519) | function createChainableTypeChecker(validate) {
function createPrimitiveTypeChecker (line 12540) | function createPrimitiveTypeChecker(expectedType) {
function createAnyTypeChecker (line 12558) | function createAnyTypeChecker() {
function createArrayOfTypeChecker (line 12562) | function createArrayOfTypeChecker(typeChecker) {
function createElementTypeChecker (line 12581) | function createElementTypeChecker() {
function createInstanceTypeChecker (line 12592) | function createInstanceTypeChecker(expectedClass) {
function createEnumTypeChecker (line 12605) | function createEnumTypeChecker(expectedValues) {
function createObjectOfTypeChecker (line 12627) | function createObjectOfTypeChecker(typeChecker) {
function createUnionTypeChecker (line 12648) | function createUnionTypeChecker(arrayOfTypeCheckers) {
function createNodeChecker (line 12669) | function createNodeChecker() {
function createShapeTypeChecker (line 12680) | function createShapeTypeChecker(shapeTypes) {
function isNode (line 12703) | function isNode(propValue) {
function getPropType (line 12751) | function getPropType(propValue) {
function getPreciseType (line 12767) | function getPreciseType(propValue) {
function getClassName (line 12780) | function getClassName(propValue) {
function ReactReconcileTransaction (line 12894) | function ReactReconcileTransaction(forceHTML) {
function attachRefs (line 12960) | function attachRefs() {
function attachRef (line 13066) | function attachRef(ref, component, owner) {
function detachRef (line 13075) | function detachRef(ref, component, owner) {
function renderToString (line 13211) | function renderToString(element) {
function renderToStaticMarkup (line 13239) | function renderToStaticMarkup(element) {
function ReactServerRenderingTransaction (line 13313) | function ReactServerRenderingTransaction(renderToStaticMarkup) {
function enqueueUpdate (line 13376) | function enqueueUpdate(internalInstance) {
function getInternalInstanceReadyForUpdate (line 13380) | function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
function ensureInjected (line 13640) | function ensureInjected() {
function ReactUpdatesFlushTransaction (line 13674) | function ReactUpdatesFlushTransaction() {
function batchedUpdates (line 13703) | function batchedUpdates(callback, a, b, c, d, e) {
function mountOrderComparator (line 13715) | function mountOrderComparator(c1, c2) {
function runBatchedUpdates (line 13719) | function runBatchedUpdates(transaction) {
function enqueueUpdate (line 13777) | function enqueueUpdate(component) {
function asap (line 13798) | function asap(callback, context) {
function getSelection (line 14036) | function getSelection(node) {
function constructSelectEvent (line 14067) | function constructSelectEvent(nativeEvent, nativeEventTarget) {
function SyntheticClipboardEvent (line 14831) | function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeE...
function SyntheticCompositionEvent (line 14869) | function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativ...
function SyntheticDragEvent (line 14907) | function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent,...
function SyntheticEvent (line 14970) | function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nat...
function SyntheticFocusEvent (line 15123) | function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticInputEvent (line 15162) | function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticKeyboardEvent (line 15248) | function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEv...
function SyntheticMouseEvent (line 15322) | function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticTouchEvent (line 15369) | function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent...
function SyntheticUIEvent (line 15430) | function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, n...
function SyntheticWheelEvent (line 15486) | function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent...
function accumulateInto (line 15783) | function accumulateInto(current, next) {
function adler32 (line 15834) | function adler32(data) {
function dangerousStyleValue (line 15909) | function dangerousStyleValue(name, value) {
function deprecated (line 15965) | function deprecated(fnName, newModule, newPackage, ctx, fn) {
function escaper (line 16010) | function escaper(match) {
function escapeTextContentForBrowser (line 16020) | function escapeTextContentForBrowser(text) {
function findDOMNode (line 16053) | function findDOMNode(componentOrElement) {
function flattenSingleChildIntoContext (line 16097) | function flattenSingleChildIntoContext(traverseContext, child, name) {
function flattenChildren (line 16114) | function flattenChildren(children) {
function getEventCharCode (line 16179) | function getEventCharCode(nativeEvent) {
function getEventKey (line 16279) | function getEventKey(nativeEvent) {
function modifierStateGetter (line 16339) | function modifierStateGetter(keyArg) {
function getEventModifierState (line 16349) | function getEventModifierState(nativeEvent) {
function getEventTarget (line 16376) | function getEventTarget(nativeEvent) {
function getIteratorFn (line 16417) | function getIteratorFn(maybeIterable) {
function getLeafNode (line 16445) | function getLeafNode(node) {
function getSiblingNode (line 16459) | function getSiblingNode(node) {
function getNodeForCharacterOffset (line 16475) | function getNodeForCharacterOffset(root, offset) {
function getTextContentAccessor (line 16523) | function getTextContentAccessor() {
function getDeclarationErrorAddendum (line 16562) | function getDeclarationErrorAddendum(owner) {
function isInternalComponentType (line 16579) | function isInternalComponentType(type) {
function instantiateReactComponent (line 16590) | function instantiateReactComponent(node) {
function isEventSupported (line 16684) | function isEventSupported(eventNameSuffix, capture) {
function isTextInputElement (line 16742) | function isTextInputElement(elem) {
function onlyChild (line 16776) | function onlyChild(children) {
function quoteAttributeValueForBrowser (line 16804) | function quoteAttributeValueForBrowser(value) {
function shouldUpdateReactComponent (line 16984) | function shouldUpdateReactComponent(prevElement, nextElement) {
function userProvidedKeyEscaper (line 17042) | function userProvidedKeyEscaper(match) {
function getComponentKey (line 17053) | function getComponentKey(component, index) {
function escapeUserProvidedKey (line 17068) | function escapeUserProvidedKey(text) {
function wrapUserProvidedKey (line 17079) | function wrapUserProvidedKey(key) {
function traverseAllChildrenImpl (line 17091) | function traverseAllChildrenImpl(children, nameSoFar, callback, traverse...
function traverseAllChildren (line 17183) | function traverseAllChildren(children, callback, traverseContext) {
function camelize (line 17704) | function camelize(string) {
function camelizeStyleName (line 17747) | function camelizeStyleName(string) {
function containsNode (line 17778) | function containsNode(_x, _x2) {
function hasArrayNature (line 17840) | function hasArrayNature(obj) {
function createArrayFromMixed (line 17883) | function createArrayFromMixed(obj) {
function getNodeName (line 17933) | function getNodeName(markup) {
function createNodesFromMarkup (line 17948) | function createNodesFromMarkup(markup, handleScript) {
function makeEmptyFunction (line 17993) | function makeEmptyFunction(arg) {
function emptyFunction (line 18004) | function emptyFunction() {}
function focusNode (line 18056) | function focusNode(node) {
function getActiveElement (line 18090) | function getActiveElement() /*?DOMElement*/{
function getMarkupWrap (line 18181) | function getMarkupWrap(nodeName) {
function getUnboundedScrollPosition (line 18223) | function getUnboundedScrollPosition(scrollable) {
function hyphenate (line 18266) | function hyphenate(string) {
function hyphenateStyleName (line 18306) | function hyphenateStyleName(string) {
function invariant (line 18336) | function invariant(condition, format, a, b, c, d, e, f) {
function isNode (line 18381) | function isNode(object) {
function isTextNode (line 18407) | function isTextNode(object) {
function mapObject (line 18535) | function mapObject(object, callback, context) {
function memoizeStringOnly (line 18570) | function memoizeStringOnly(callback) {
function shallowEqual (line 18663) | function shallowEqual(objA, objB) {
function toArray (line 18717) | function toArray(obj) {
Condensed preview — 149 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,573K chars).
[
{
"path": ".gitignore",
"chars": 24,
"preview": "\nnode_modules\n.npm\n.bin\n"
},
{
"path": "LICENSE",
"chars": 1093,
"preview": "The MIT License (MIT)\n\nCopyright Lucas, Inc. and other contributors.\n\nPermission is hereby granted, free of charge, to a"
},
{
"path": "README.md",
"chars": 12412,
"preview": "\n[](http://karat.cc/article/5"
},
{
"path": "README_zh-CN.md",
"chars": 10209,
"preview": "\n[](http://karat.cc/article/5"
},
{
"path": "assets/.babelrc",
"chars": 47,
"preview": "{\n \"presets\": [\"es2015\", \"react\", \"stage-3\"]\n}"
},
{
"path": "index.js",
"chars": 43928,
"preview": "/**\n * Gulpman\n * FOR MODULAR FRONT-END SOURCE COMPILE SYSTEM\n */\n\n// =======================================\n\n\n'use str"
},
{
"path": "karma/karma.conf.js",
"chars": 1396,
"preview": "var stringify = require('stringify');\n\nvar ignore_files = '**/lib/**',\n spec_files = '**/spec/**',\n tpl_files = '*"
},
{
"path": "lib/assetsPathParser.js",
"chars": 6647,
"preview": "/**\n * For path replace into abs path\n */\n\n'use strict'\n\n\nvar through = require('through2'),\n\tpath = require('path'),\n\tj"
},
{
"path": "lib/base64.js",
"chars": 4784,
"preview": "/**\n * FOR BASE 64 UTILS\n */\n\nvar path = require('path'),\n j = path.join,\n fs = require('fs'),\n gutil = require"
},
{
"path": "lib/cdnProxy.js",
"chars": 1610,
"preview": "\n/**\n * FOR CDN PREFIX CONFIG\n *\n * FIX gulp-rev-all and revReplace about `prefix`\n */\n\n/**\n * Another Proxy code in rev"
},
{
"path": "lib/gmutil.js",
"chars": 6447,
"preview": "/**\n * FOR UTILS\n */\n\n'use strict'\n\n\nvar colors = require('colors'),\n path = require('path'),\n j = path.join\n\n\nfun"
},
{
"path": "lib/gulp-usemin/.npmignore",
"chars": 31,
"preview": "/node_modules\n/*.log\n.idea/\n*~\n"
},
{
"path": "lib/gulp-usemin/.travis.yml",
"chars": 73,
"preview": "language: node_js\r\nnode_js:\r\n - \"4.0\"\r\nbefore_script:\r\n - npm install\r\n"
},
{
"path": "lib/gulp-usemin/LICENSE",
"chars": 1082,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2014 Alexander Zonov\n\nPermission is hereby granted, free of charge, to any person o"
},
{
"path": "lib/gulp-usemin/README.md",
"chars": 7873,
"preview": "[](https://travis-ci.org/zont/gulp-usemin)\n\n# g"
},
{
"path": "lib/gulp-usemin/gulpfile.js",
"chars": 312,
"preview": "/* jshint node:true */\n\n'use strict';\n\nvar gulp = require('gulp');\nvar jshint = require('gulp-jshint');\nvar mocha = requ"
},
{
"path": "lib/gulp-usemin/index.js",
"chars": 747,
"preview": "module.exports = function(options) {\n var through = require('through2');\n var gutil = require('gulp-util');\n var bloc"
},
{
"path": "lib/gulp-usemin/lib/blocksBuilder.js",
"chars": 4897,
"preview": "var fs = require('fs');\nvar glob = require('globby');\nvar path = require('path');\nvar gutil = require('gulp-util');\n\nmod"
},
{
"path": "lib/gulp-usemin/lib/htmlBuilder.js",
"chars": 4212,
"preview": "module.exports = function(file, blocks, options, push, callback) {\n var path = require('path');\n var gutil = require('"
},
{
"path": "lib/gulp-usemin/lib/pipeline.js",
"chars": 820,
"preview": "module.exports = function(name, files, tasks, push) {\n var through = require('through2');\n var concat = require('gulp-"
},
{
"path": "lib/gulp-usemin/package.json",
"chars": 2105,
"preview": "{\n \"name\": \"gulp-usemin\",\n \"version\": \"0.3.23\",\n \"description\": \"Replaces references to non-optimized scripts or styl"
},
{
"path": "lib/gulp-usemin/test/expected/app.js",
"chars": 38,
"preview": "var sample = 111;\nconsole.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/array-js-attributes.html",
"chars": 246,
"preview": "<script src=\"/dist/index.js\" seq=\"1\" color=\"blue\"></script>\n\n<script src=\"/dist/index1.js\" seq=\"2\" color=\"red\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/build-remove-no-trailing-whitespace.html",
"chars": 11,
"preview": "<div></div>"
},
{
"path": "lib/gulp-usemin/test/expected/complex-path.html",
"chars": 91,
"preview": "<link rel=\"stylesheet\" href=\"data/css/style.css\"/>\n\n<script src=\"/data/js/app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/complex.html",
"chars": 73,
"preview": "<link rel=\"stylesheet\" href=\"style.css\"/>\n\n<script src=\"app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/conditional-complex.html",
"chars": 128,
"preview": "<!--[if IE 8]><link rel=\"stylesheet\" href=\"style.css\"/><![endif]-->\n\n<!--[if lt IE 9]><script src=\"app.js\"></script><![e"
},
{
"path": "lib/gulp-usemin/test/expected/conditional-css.html",
"chars": 71,
"preview": "<!--[if lt IE 9]><link rel=\"stylesheet\" href=\"/style.css\"/><![endif]-->"
},
{
"path": "lib/gulp-usemin/test/expected/conditional-inline-css.html",
"chars": 99,
"preview": "<!--[if lt IE 9]><style>* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}</style><![endif]-->\n"
},
{
"path": "lib/gulp-usemin/test/expected/conditional-inline-js.html",
"chars": 85,
"preview": "<!--[if lt IE 9]><script>var sample = 111;\nconsole.log(sample);</script><![endif]-->\n"
},
{
"path": "lib/gulp-usemin/test/expected/conditional-js.html",
"chars": 59,
"preview": "<!--[if lt IE 9]><script src=\"app.js\"></script><![endif]-->"
},
{
"path": "lib/gulp-usemin/test/expected/data/css/min-style.css",
"chars": 38,
"preview": "*{margin:0;padding:0}body{margin:10px}"
},
{
"path": "lib/gulp-usemin/test/expected/data/css/style.css",
"chars": 54,
"preview": "* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}"
},
{
"path": "lib/gulp-usemin/test/expected/data/js/app.js",
"chars": 38,
"preview": "var sample = 111;\nconsole.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/data/js/app_min_concat.js",
"chars": 36,
"preview": "var sample=111;\nconsole.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/data/js/min-app.js",
"chars": 35,
"preview": "var sample=111;console.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/glob-inline-css.html",
"chars": 70,
"preview": "<style>* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}</style>\n"
},
{
"path": "lib/gulp-usemin/test/expected/glob-inline-js.html",
"chars": 56,
"preview": "<script>var sample = 111;\nconsole.log(sample);</script>\n"
},
{
"path": "lib/gulp-usemin/test/expected/many-blocks-removal.html",
"chars": 89,
"preview": "<link rel=\"stylesheet\" href=\"data/css/style.css\"><script src=\"/data/js/app1.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-app.js",
"chars": 35,
"preview": "var sample=111;console.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/min-complex-path.html",
"chars": 82,
"preview": "<link rel=stylesheet href=data/css/style.css><script src=/data/js/app.js></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-complex.html",
"chars": 64,
"preview": "<link rel=stylesheet href=style.css><script src=app.js></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-css-with-media-query.html",
"chars": 50,
"preview": "<link rel=stylesheet href=/style.css media=screen>"
},
{
"path": "lib/gulp-usemin/test/expected/min-html-simple-css.html",
"chars": 42,
"preview": "<link rel=\"stylesheet\" href=\"/style.css\"/>"
},
{
"path": "lib/gulp-usemin/test/expected/min-html-simple-js.html",
"chars": 30,
"preview": "<script src=\"app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-html-simple-removal.html",
"chars": 0,
"preview": ""
},
{
"path": "lib/gulp-usemin/test/expected/min-paths-with-querystring.html",
"chars": 64,
"preview": "<link rel=stylesheet href=style.css><script src=app.js></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-simple-css-path.html",
"chars": 45,
"preview": "<link rel=stylesheet href=data/css/style.css>"
},
{
"path": "lib/gulp-usemin/test/expected/min-simple-css.html",
"chars": 37,
"preview": "<link rel=stylesheet href=/style.css>"
},
{
"path": "lib/gulp-usemin/test/expected/min-simple-js-path.html",
"chars": 36,
"preview": "<script src=data/js/app.js></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-simple-js.html",
"chars": 28,
"preview": "<script src=app.js></script>"
},
{
"path": "lib/gulp-usemin/test/expected/min-style.css",
"chars": 38,
"preview": "*{margin:0;padding:0}body{margin:10px}"
},
{
"path": "lib/gulp-usemin/test/expected/multiple-alternative-paths.html",
"chars": 39,
"preview": "<script src=\"data/js/app.js\"></script>\n"
},
{
"path": "lib/gulp-usemin/test/expected/multiple-files.html",
"chars": 181,
"preview": "<link rel=\"stylesheet\" href=\"data/css/style.css\"/><link rel=\"stylesheet\" href=\"data/css/style.css\"/>\n\n<script src=\"/data"
},
{
"path": "lib/gulp-usemin/test/expected/paths-with-querystring.html",
"chars": 73,
"preview": "<link rel=\"stylesheet\" href=\"style.css\"/>\n\n<script src=\"app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/simple-css-path.html",
"chars": 50,
"preview": "<link rel=\"stylesheet\" href=\"data/css/style.css\"/>"
},
{
"path": "lib/gulp-usemin/test/expected/simple-css.html",
"chars": 42,
"preview": "<link rel=\"stylesheet\" href=\"/style.css\"/>"
},
{
"path": "lib/gulp-usemin/test/expected/simple-inline-css.html",
"chars": 70,
"preview": "<style>* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}</style>\n"
},
{
"path": "lib/gulp-usemin/test/expected/simple-inline-js.html",
"chars": 56,
"preview": "<script>var sample = 111;\nconsole.log(sample);</script>\n"
},
{
"path": "lib/gulp-usemin/test/expected/simple-js-path.html",
"chars": 38,
"preview": "<script src=\"data/js/app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/simple-js-removal.html",
"chars": 22,
"preview": "<div></div><div></div>"
},
{
"path": "lib/gulp-usemin/test/expected/simple-js.html",
"chars": 30,
"preview": "<script src=\"app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/single-quotes-css.html",
"chars": 50,
"preview": "<link rel=\"stylesheet\" href=\"data/css/style.css\"/>"
},
{
"path": "lib/gulp-usemin/test/expected/single-quotes-inline-css.html",
"chars": 70,
"preview": "<style>* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}</style>\n"
},
{
"path": "lib/gulp-usemin/test/expected/single-quotes-inline-js.html",
"chars": 56,
"preview": "<script>var sample = 111;\nconsole.log(sample);</script>\n"
},
{
"path": "lib/gulp-usemin/test/expected/single-quotes-js.html",
"chars": 38,
"preview": "<script src=\"data/js/app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/expected/style.css",
"chars": 54,
"preview": "* {\n\tmargin: 0;\n\tpadding: 0;\n}\nbody {\n\tmargin: 10px;\n}"
},
{
"path": "lib/gulp-usemin/test/expected/subfolder/app.js",
"chars": 20,
"preview": "console.log(sample);"
},
{
"path": "lib/gulp-usemin/test/expected/subfolder/index.html",
"chars": 30,
"preview": "<script src=\"app.js\"></script>"
},
{
"path": "lib/gulp-usemin/test/fixtures/alternative/js/util.js",
"chars": 10,
"preview": "alert(1);\n"
},
{
"path": "lib/gulp-usemin/test/fixtures/array-js-attributes.html",
"chars": 342,
"preview": "<!--build:js /dist/index.js -->\n<script src=\"js/lib.js\"></script>\n<!--endbuild-->\n\n<!--build:js1 /dist/index1.js -->\n<sc"
},
{
"path": "lib/gulp-usemin/test/fixtures/async-less.html",
"chars": 143,
"preview": "<!-- build:less /style.css -->\n<link rel=\"stylesheet\" href=\"less/clear.less\"/>\n<link rel=\"stylesheet\" href=\"less/main.le"
},
{
"path": "lib/gulp-usemin/test/fixtures/build-remove-no-trailing-whitespace.html",
"chars": 347,
"preview": "<div>\n <!-- build:remove-->\n <p>lorem ipsum</p>\n <p>lorem ipsum</p>\n <!-- endbuild-->\n <!-- build:remove -->\n <p>l"
},
{
"path": "lib/gulp-usemin/test/fixtures/comment-js.html",
"chars": 84,
"preview": "<!-- build:js app.js -->\n<!--\n<script src=\"js/*.js\"></script>\n-->\n<!-- endbuild -->\n"
},
{
"path": "lib/gulp-usemin/test/fixtures/complex-path.html",
"chars": 268,
"preview": "<!-- build:css data/css/style.css -->\n<link rel=\"stylesheet\" href=\"css/clear.css\"/>\n<link rel=\"stylesheet\" href=\"css/mai"
},
{
"path": "lib/gulp-usemin/test/fixtures/complex.html",
"chars": 250,
"preview": "<!-- build:css style.css -->\n<link rel=\"stylesheet\" href=\"css/clear.css\"/>\n<link rel=\"stylesheet\" href=\"css/main.css\"/>\n"
},
{
"path": "lib/gulp-usemin/test/fixtures/conditional-complex.html",
"chars": 309,
"preview": "<!-- build:css style.css -->\n<!--[if IE 8]>\n<link rel=\"stylesheet\" href=\"css/clear.css\"/>\n<link rel=\"stylesheet\" href=\"c"
},
{
"path": "lib/gulp-usemin/test/fixtures/conditional-css.html",
"chars": 169,
"preview": "<!-- build:css /style.css -->\n<!--[if lt IE 9]>\n<link rel=\"stylesheet\" href=\"css/clear.css\"/>\n<link rel=\"stylesheet\" hre"
},
{
"path": "lib/gulp-usemin/test/fixtures/conditional-inline-css.html",
"chars": 166,
"preview": "<!-- build:inlinecss -->\n<!--[if lt IE 9]>\n<link rel=\"stylesheet\" href=\"css/clear.css\"/>\n<link rel=\"stylesheet\" href=\"c"
},
{
"path": "lib/gulp-usemin/test/fixtures/conditional-inline-js.html",
"chars": 142,
"preview": "<!-- build:inlinejs -->\n<!--[if lt IE 9]>\n<script src=\"js/lib.js\"></script>\n<script src=\"js/main.js\"></script>\n<![endif]"
},
{
"path": "lib/gulp-usemin/test/fixtures/conditional-js.html",
"chars": 142,
"preview": "<!-- build:js app.js -->\n<!--[if lt IE 9]>\n<script src=\"js/lib.js\"></script>\n<script src=\"js/main.js\"></script>\n<](http://badge.fury.io/js/gulp-css-spriter)\r\n\r\n# gulp-css-"
},
{
"path": "lib/spriter/index.js",
"chars": 10422,
"preview": "// gulp-css-spriter: https://www.npmjs.com/package/gulp-css-spriter\r\n// Sprite Sheet Generation from CSS source files.\r\n"
},
{
"path": "lib/spriter/lib/get-background-image-declarations.js",
"chars": 693,
"preview": "\r\nvar mapOverStylesAndTransformBackgroundImageDeclarations = require('./map-over-styles-and-transform-background-image-d"
},
{
"path": "lib/spriter/lib/get-meta-info-for-declaration.js",
"chars": 2036,
"preview": "var extend = require('extend');\r\n\r\n\r\nfunction getMetaInfoForDeclaration(declarations, declarationIndex) {\r\n\tvar resultan"
},
{
"path": "lib/spriter/lib/map-over-styles-and-transform-background-image-declarations.js",
"chars": 4600,
"preview": "var extend = require('extend');\r\n\r\nvar spriterUtil = require('./spriter-util');\r\nvar getMetaInfoForDeclaration = require"
},
{
"path": "lib/spriter/lib/spriter-util.js",
"chars": 529,
"preview": "\r\nvar backgroundURLRegex = (/(.*?url\\([\"\\']?)(.*?\\.(?:png|jpg|gif))([\"\\']?\\).*?;?)/i);\r\n\r\n\r\nfunction matchBackgroundImag"
},
{
"path": "lib/spriter/lib/transform-file-with-sprite-sheet-data.js",
"chars": 2444,
"preview": "var path = require('path');\r\nvar extend = require('extend');\r\n\r\nvar css = require('css');\r\n\r\nvar spriterUtil = require('"
},
{
"path": "lib/spriter/lib/transform-map.js",
"chars": 1153,
"preview": "var extend = require('extend');\r\n\r\nfunction transformMap(arr, cb) {\r\n\tvar resultantArray = extend(true, [], arr);\r\n\r\n\tfo"
},
{
"path": "lib/spriter/package.json",
"chars": 1785,
"preview": "{\n \"name\": \"gulp-css-spriter\",\n \"version\": \"0.3.3\",\n \"description\": \"Sprite Sheet Generation from CSS source files. T"
},
{
"path": "lib/store.js",
"chars": 2731,
"preview": "/**\n * For create JSON file\n */\n\nvar fs = require('fs'),\n path = require('path'),\n j = path.join\n\n\nvar gmutil = re"
},
{
"path": "meta/home/index.html",
"chars": 1819,
"preview": "<!DOCTYPE html>\n<html lang=\"zh\" >\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>HOME"
},
{
"path": "meta/home/main.es6",
"chars": 396,
"preview": "/**\n * FOR HOME\n */\n\nimport 'react'\n\nlet HelloMessage = React.createClass({\n render () {\n return <div>The Cont"
},
{
"path": "meta/home/main.scss",
"chars": 970,
"preview": "/**\n * FOR HOME\n */\n\n\n.logo {\n background: url(./img/logo.png) no-repeat;\n}\n\n// for sprite demo\n.demo-sprite {\n ba"
},
{
"path": "package.json",
"chars": 1613,
"preview": "{\n \"name\": \"gulpman\",\n \"version\": \"2.0.0\",\n \"description\": \"Create Modular Front-End Build System. Based on gulp, ver"
},
{
"path": "presetlib/jquery.js",
"chars": 247605,
"preview": "/*!\n * jQuery JavaScript Library v2.1.4\n * http://jquery.com/\n *\n * Includes Sizzle.js\n * http://sizzlejs.com/\n *\n * Cop"
},
{
"path": "presetlib/react-0.14.6/build/react-dom-server.js",
"chars": 1189,
"preview": "/**\n * ReactDOMServer v0.14.6\n *\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code i"
},
{
"path": "presetlib/react-0.14.6/build/react-dom.js",
"chars": 1170,
"preview": "/**\n * ReactDOM v0.14.6\n *\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is lice"
},
{
"path": "presetlib/react-0.14.6/build/react-with-addons.js",
"chars": 707589,
"preview": " /**\n * React (with addons) v0.14.6\n */\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module"
},
{
"path": "presetlib/react-0.14.6/build/react.js",
"chars": 641479,
"preview": " /**\n * React v0.14.6\n */\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}e"
},
{
"path": "presetlib/react.js",
"chars": 641570,
"preview": " /**\n * React v0.14.6\n */\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}e"
},
{
"path": "scripts/gulp/gulpfile.js",
"chars": 1256,
"preview": "/**\n * Gulpman demo gulpfile.js\n * Config the gulpman by yourself\n */\n\n\nvar gulp = require('gulp'),\n gulpman = requir"
},
{
"path": "scripts/install.sh",
"chars": 1690,
"preview": "#!/bin/sh\n\n# @author: Lucas\n# @mail: xwlxyjk@gmail.com\n\n\n# init the package.json if not existed\npackageFile=\"../../packa"
},
{
"path": "scripts/package.json",
"chars": 451,
"preview": "{\n \"name\": \"Project\",\n \"version\": \"1.0.0\",\n \"description\": \"Project build by Gulpman, update this description\",\n \"en"
},
{
"path": "scripts/preinstall.sh",
"chars": 1383,
"preview": "#!/bin/sh\n\n# init the package.json if not existed\npackageFile=\"../../package.json\"\nInstall_Type=1\n\nif [ ! -f \"$packageFi"
},
{
"path": "test.js",
"chars": 0,
"preview": ""
}
]
About this extraction
This page contains the full source code of the xunuoi/gulpman GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 149 files (2.3 MB), approximately 618.9k tokens, and a symbol index with 1033 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.