安装
前提:已经安装了nodejs & npm
有了 npm 后安装非常的方便,不论是在windows还是mac下, 只需要一句1
npm install webpack -g
就可以把 webpack 安装在全局环境下,然后就可以在terminal 或者是 cmd 里直接使用 webpack 了。一般在项目的目录下使用的时候会加上 –save-dev 这个参数1
npm install webpack --save-dev
打包
假设目录下有一个 app.js 文件1
2
3function helloworld () {
alert('hello world!');
}
在命令行中输入:1
webpack ./app.js ./bundle.js
发现目录下已经生成了一个 bundle.js 文件,并且伴随着一个 webpack 任务的完成信息的输出
输出的信息:
- 这次打包的MD5(Hash)
- Webpack 的版本号(Version)
- 还有打包花费的时间(Time)
随后会看到一个列表:
- 打包后的文件名称 Asset
- 包大小 Size
- 代码块编号 Chunks
- 代码块名称 Chunk Names
打开bundle.js 会看到已经生成了的文件, 下面的代码为了方便阅读去掉了不必要的注释:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36(function(modules) {
// webpackBootstrap
// The module cache
var installedModules = {};
// The require function
function __webpack_require__(moduleId) {
// Check if module is in cache
if(installedModules[moduleId])
return installedModules[moduleId].exports;
// Create a new module (and put it into the cache)
var module = installedModules[moduleId] = {
exports: {},
id: moduleId,
loaded: false
};
// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
// Flag the module as loaded
module.loaded = true;
// Return the exports of the module
return module.exports;
}
// expose the modules object (__webpack_modules__)
__webpack_require__.m = modules;
// expose the module cache
__webpack_require__.c = installedModules;
// __webpack_public_path__
__webpack_require__.p = "";
// Load entry module and return exports
return __webpack_require__(0);
})([
/* 0 */function(module, exports) {
function helloworld () {
alert('hello world!');
}
}]);
为了更了解webpack打包的工作原理以及打包后的代码在浏览器中的如何运行,阅读了一下生成后的代码
整个代码是一个自运行函数,分两部分:
- 第一部分可以理解是webpack启动架,其中定义了一个空对象(installedModules)来存放 webpack modules,定义了webpack 运行环境下的require函数(’webpack_require‘),最后这一句:webpackrequire(0) 是把作为参数传入的实际代码通过require函数执行了一遍
- 第二部分是 app.js里的实际代码,前面的注释是webpack 给实际代码模块的 moduleId ,在app.js 的实际代码外面多了一个匿名函数,把参数module,export,webpack_require传了进来,方便实际 app.js里的代码使用。
模块化
webpack 支持多种js模块方案的打包:
- ES6 modules
- Commonjs
- AMD
假设有两个js 文件,一个是 app.js, 另一个 util.js,utils里的内容如下:
1 | // CommonJs 规范的模块化 |
app.js 加入对util的引用
1 | var util = require(./util.js); |
打包完的代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14([
/* 0 */function(module, exports, __webpack_require__) {
var util = __webpack_require__(1)
function helloworld () {
util.say('hello world!');
}
},
/* 1 */function(module, exports) {
module.exports = {
say: function (word) {
alert(word);
}
};
}]);
发现在bundle.js 里,app里引用的util.js的地址已经变为webpack的moduleId了,require也被替换为webpack的启动架中定义的webpack_require方法。每个模块都被编号,app.js 为 0, util.js 为 1。在代码中使用了require 方法的,外面匿名函数传入的参数也增加了webpack_require。