刚接触 webpack 不久,到目前为止,我所知道的 webpack 是用来开发组件的。
但是在项目开发中,或多组件共用模块时,应该怎么操作?
比如 a、b 两个组件都引用了 jQuery 和 handlebars
// a.js
var $ = require('jquery');
var Handlebars = require('handlebars');
//...
// b.js
var $ = require('jquery');
var Handlebars = require('handlebars');
//...
当我有个应用同时使用了这两个组件,就会有多余代码了。
于是,我在打包 a、b 组件的时候不想把 jQuery 和 handlebars 打包进去
同时,又有个问题,jQuery 和 handlebars 是有区别的。(仅拿他们两个做代表)
jQuery
使用范围太广了,我想让它做为全局的变量。
即在页面中直接 script 标签引入。也是为了多页共用缓存。
window.$ = window.jQuery = jQuery;
此时 a、b 组件该怎么引入 jQuery ?
而 handlebars
仅在两个组件内复用。
一个可能的场景是,直到用户操作了 a、b 组件,handlebars 文件才从缓存中或网络中下载下来。
此时 a、b 组件又该怎么引入 handlebars ?
因为我用 seajs
实现了上述功能,所以对 webpack
有此一问。
提取公共项 => http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
外部引用 => http://webpack.github.io/docs/library-and-externals.html
更一般的说明 => http://webpack.github.io/docs/code-splitting.html
下面有大量example