Webpack 开发和部署

Thanks to Webpack 傻瓜指南

启用 Source Map

在 webpack.config.js 中添加字段

devtool: 'eval-source-map',
`</pre>

这样出错后会采用 sourceMap 直接显示出错位置

### 配置 webpack-dev-server

在 webpack.config.js 中添加字段

<pre>`devServer: {
  historyApiFallback: true,
  hot: true,
  inline: true,
  progress: true,
}
`</pre>

### 使用 preLoaders 和 postLoaders

preLoaders 在 loaders 之前执行, 总体顺序是 preLoader -> loaders -> postLoaders

#### 安装 jshint

<pre>`npm install --save-dev jshint-loader
`</pre>

在 config 中配置

<pre>`module:{
  preloaders:[
    {
      test: /\.jsx$/,
      loader:'jshint-loader'
    }
  ]
}
jshint:{
  'esnext':true
}
`</pre>

### 部署上线

项目开发完成后需要部署上线, 此时应该创建一个新的 config, 因为部署上线使用的 webpack 不需要 dev-tools, dev-server, jshint 等

复制现有的 config 文件, 命名为 webpack.production.config.js, 将里面与开发有关的东西删除, 在 package.json 中添加

<pre>`"scripts":{
  "build": "webpack --progress --profile  --colors --config webpack.production.config.js"
},
`</pre>

上线的时候运行

<pre>`npm run build
`</pre>

### 分离第三方库

如果第三方库很多, 会导致最后 bundle 文件很大, 减慢加载速度, 因此需要把第三方库和 app 本身的代码分开

#### 修改 entry 入口文件

<pre>`entry:{
  app: path.resolve(APP_PATH, 'index.js'),
  //添加要打包在 vendors 里面的库
  vendors: ['jquery', [moment]]
},
`</pre>

#### 添加 CommonsChunkPlugin

<pre>`plugins: [
  //使用 uglifyJs 压缩 js 代码
  new webpack.optimize.UglifyJsPlugin({minimize: true}),
  //把入口文件里的数组打包成 vendors.js
  new webpack.optimize.CommonsChunkPlugin('vendors','vendors.js'),
  new HtmlWebpackPlugin({title: 'Welcome'})
]
`</pre>

运行 build 后会生成 vendor.js

### 生成多页面

假设需求是生成两个页面, 一个叫 index.html, 需要引用 app.js 和 vendors.js 两个文件; 另一个是 mobile.html, 需要应用 mobie.js 和 vendor.js 这两个文件

首先新建一个叫 mobile.js 的文件入口, 比 app.js 简单一些

<pre>`import './main.scss';
import $ from 'jquery';
import 'imports?jQuery=jQuery!./plugin.js';

$(document).ready(function(){
  let app = document.createElement('div');
  app.innerHTML = '&lt;h1&gt;Hello World&lt;/h1&gt;';
  document.body.appendChild(app);
  $('h1').greenify();
});
`</pre>

在 config 修改入口文件和输出配置

<pre>`entry:{
  // 三个入口文件: app, mobile, vendors
  app: path.resolve(APP_PATH, 'index.js'),
  mobile: path.resolve(APP_PATH, 'mobile.js'),
  vendors: ['jquery','moment']
},
output:{
   path: DIST_PATH,
   filename: '[name].js'
},
`</pre>

为 html-webpack-plugin 设置模板, 并保存于 templates

<pre>`// index.html
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;{%= o.htmlWebpackPlugin.options.title %}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h3&gt;Welcome to Index&lt;/h3&gt;
  &lt;/body&gt;
&lt;/html&gt;

//mobile.html
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;{%= o.HtmlWebpackPlugin.options.title %}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h3&gt;Welcome to Mobile&lt;/h3&gt;
  &lt;/body&gt;
&lt;/html&gt;
`</pre>

继续配置 config.js, 让 HtmlWebpackPlugin 可以生成多个文件

<pre>`//Templates 的文件夹路径
var TEM_PATH = path.resolve(ROOT_PATE, 'templates');
...
plugins:[
  //创建两个 HtmlWebpackPlugin 的实例, 生成两个页面
  new HtmlWebpackPlugin({
    title: 'Hello World App',
    template: path.resolve(TEM_PATH, 'index.html'),
    filename: 'index.html'
    //chunks 这个参数告诉插件要引用 chunks 中的那几个入口
    chunks: ['app','vendors'],
    //scripts 要插入的位置
    inject: 'body'
  }),
  new HtmlWebpackPlugin({
    title: 'Hello Mobile App',
    template: path.resolve(TEM_PATH, 'mobile.html'),
    filename: 'mobile.html',
    chunks: ['mobile','vendors'],
    inject: 'body'
  })
]

生成 hash 名称的 script 来防止缓存

webpack 基于 md5 可以生成 hash 名称
`
output:{
path: DIST_Path,
filename: ‘[name].[hash].js’
},

Event

In computing, an event is an action or occurrence recognized by software that may be handled by the software. Computer events can be generated or triggered by the system, by the user or in other ways. Typically, events are handled synchronously with the program flow, that is, the software may have one or more dedicated places where events are handled, frequently an event loop. A source of events includes the user, who may interact with the software by way of, for example, keystroke on the keyboard. Another source is a hardware device such as a timer. Software can be trigger its own set of events into the event loop, e.g. to communicate the completion of a task. Software that changes its behavior in response to events is said to be event-driven, often with the goal of being inactive.

Event handler

In computer programming, an event handler is a callback subroutine that handles inputs received in a program(called a listener in Java and JavaScript). Each event is a piece of application-level information from the underlying framework, typically the GUI Toolkit. GUI events including key presses, mouse movement, action selections, and timer expiring.

DOM Events

DOM(Document Object Model) events allow event-driven programming language like JavaScript, JScript, ECMAScript, VBScript and Java to register various event handler/listener on the element nodes inside a DOM tree, e.g. HTML, XHTML, XUL, and SVG documents.

Events

HTML Events

There is a huge collection of events that can be generated by most element nodes:

  • Mouse events;
  • Keyboard events;
  • HTML frame/object events;
  • HTML form events;
  • User interface events;
  • Mutation events(notification of any changes to the structure of a document);
  • Progress events(used by XMLHttpResponse, File API, …)

Mouse:
click, dblclick, mousedown, mouseover, mousemove, mouseout, dragstart, drag, dragenter, dragleave, dragover, drop, dragend

  • Click: The sequence of click: mousedown, mouseup, click
  • Mouseover: Fires when the pointing device is moved onto an element
  • Mouseover: Fires when the pointing device is moved while it is over an element
  • Dragstart: Fired on an element when a drag is started
  • Dragend: The source of the drag will receive a dragend event when the drag operation is complete, whether it was sucessful or not,

Keyboard:
keydown, keypress, keyup

HTML frame/object:
load, unload, abort, error, resize, scroll

  • Load: Fires when the user agent finishes loading all content within a document, including window, frames, objects, and images.
  • Unlaod: Fires when the user agent removes all content from a window or frame.
  • Abort: Fires when an object/image is stopped from loading before completely loaded.
  • Error: Fires when an object/image/frame/ cannot be loaded properly.
  • Resize: Fires when a document view is resized.
  • Scroll: Fires when an element or document view is scrolled

HTML form:
select, change, submit, reset, focus, blur

  • Select: Fires when a user selects some text in a text field, including input and textarea.
  • Change: Fires when a control loses the input focus and its value has been modified since gaining focus.
  • Submit: Fires when a form is submitted.
  • Reset: Fires when a form is reset.
  • Focus: Fires when an element receives focus either via the pointing device or by tab navigation.
  • Blur: Fires when an element loses focus.

User Interface:
focusin, focusout, DOMActivate

Mutation:
DOMSubtreeModified, DOMNodeInserted, DOMNodeRemoved, DOMNodeRemovedFromDocument, DOMNodeInsertedIntoDocument, DOMAttrModified, DOMCharacterDataModified

Progress:
loadstart, progress, error, abort, load, loadnd

Touch Events

Web broswer running on touch-enabled devices will generate additional events

Touch:
touchstart, touchend, touchmove, touchenter, touchleave, touchcancel

  • Touchstart: Fires when a finger is placed on the touch surface/screen.
  • Touchend: Fires when a finger is removed from the touch surface/screen.
  • Touchenter: Fires when a touch point moves onto the interactive area defined by a DOM Element
  • Touchcancel: A user-agent must dispatch this event type to indicate when a TouchPoint has been disrupted in an implementation-specific manner, such as by moving outside the bounds of the UA window.

In the W3C draft recommendation, a TouchEvent delivers a TouchList of Touch location, the modifier keys that were active, a TouchList of Touch locations within the targeted DOM element, and a TouchList of Touch lcoations that have changed since the previous TouchEvent.

Internet Explorer-specific events

In addition to the common/W3C events, two major types of events are added by Internet Explorer. Some of the events have been implemented as de facto standards by other browsers.

Clipbord:
cut, copy, paste, beforecut, beforecopy, beforepaste

Data binding:
afterupdate, beforeupdate, cellchange, dataavailable, datasetchagned, datasetcomplete, errorudpate, rowenter, rowexit, rowsdelete, rowinserted

  • Afterupdate: Fires immediately after a databound object has been updated.
  • Beforeupdate: Fires before a data source has changed.
  • Cellchange: Fires when a data source has change.
  • Dataavailable: Fires when new data from a data source become available.
  • Rowenter: Fires whena new row of data from the data source is available.

Mouse:
contextmenu, selectstart

  • Contentmenu: Fires when the context menu is shown.
  • Selectstart: Fires when the user starts to select text.

Keyboard:
help

  • Help: Fires when the user initiates help.

HTML frame/object:
beforeunload, stop

  • Beforeunload: Fires before a document is unloaded.
  • Stop: Fires when the user stop loading the object. (unlike abort, stop event can be attached to document).

理解伪元素:Before 和 :After

本篇中的”伪元素”特指”:before”和”:after”

语法和浏览器支持

早起的伪元素是使用一个冒号声明的”:”, 在 CSS3中修订后伪元素的声明使用两个冒号”::”, 但是为了目前的兼容性考虑(IE8), 建议使用”:”声明.

伪元素会在内容元素的前后插入额外的元素, 技术上等同于

&lt;p&gt;
&lt;span&gt;:before&lt;/span&gt;
This is the main content.
&lt;span&gt;:after&lt;/span&gt;

当然, 这些元素无法在文档的源码中找到

CFB MindMap

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×