經常我們會希望通過script方式引入庫,如CDN方式的jquery,我們在使用的時候依舊用require方式,但是卻不希望webpack將他編譯到文件中。
1
|
<script src=
"http://code.jquery.com/jquery-1.12.0.min.js"
></script>
|
因為模塊化開發,杜絕一切全局變量,我們想這樣去使用他:
1
2
|
const $ = require(
"jquery"
);
$(
"#content"
).html(
"<h1>hello world</h1>"
);
|
這時,我們需要配置externals
1
2
3
4
5
6
7
8
9
|
module.exports = {
output: {
libraryTarget:
"umd"
},
externals: {
jquery:
"jQuery"
},
...
}
|
看看編譯后什么變化
1
2
3
4
5
6
7
|
({ 0:
function
(...) {
var
jQuery = require(1);
}, 1:
function
(...) {
module.exports = jQuery;
// 這里是把window.jQuery賦值給了module.exports
// 因此可以使用require來引入
},
/* ... */
})
|
實際寫個例子,我們經常會有自己處理業務數據的工具庫tools.js,傳統的方法沒有提供UMD的那些功能,只能從window或者global暴露方法
1
2
3
|
window.Tools = {
add:
function
(num1, num2) {
return
num1 + num2 },
}
|
然后script方式引入
1
|
<script src=
"http://xxx/tools.min.js"
></script>
|
使用如下
1
|
const res = Tools.add(1,2);
|
配置externals改造成模塊化開發方式
1
2
3
4
5
6
7
8
9
|
module.exports = {
output: {
libraryTarget:
"umd"
},
externals: {
jquery:
"jQuery"
},
...
}
|
此時使用方式
1
2
|
const tools = require(
"myTools"
);
const res = tools.add(1,2);
|
externals的配置
1.首先是libraryTarget的配置,我們使用umd方式,這樣便可以用任何一種引入方式,即支持cmd,amd,及全局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
(
function
(root, factory) {
if
(
typeof
define ===
'function'
&& define.amd) {
// AMD
define([
'jquery'
], factory);
}
else
if
(
typeof
exports ===
'object'
) {
// Node, CommonJS之類的
module.exports = factory(require(
'jquery'
));
}
else
{
// 瀏覽器全局變量(root 即 window)
root.returnExports = factory(root.jQuery);
}
}(
this
,
function
($) {
// 方法
function
myFunc(){};
// 暴露公共方法
return
myFunc;
}));
|
2.library和libraryTarget的使用
有時我們想開發一個庫,如lodash,underscore這些工具庫,這些庫既可以用commonjs和amd方式使用也可以用script方式引入。
這時候我們需要借助library和libraryTarget,我們只需要用ES6來編寫代碼,編譯成通用的UMD就交給webpack了。
例如上面的tools
1
2
3
4
5
|
exports
default
{
add:
function
(num1, num2) {
return
num1 + num2;
}
}
|
接下來配置webpack
1
2
3
4
5
6
7
8
9
10
11
12
|
module.exports = {
entry: {
myTools:
"./src/tools.js"
},
output: {
path: path.resolve(_dirname,
"build"
),
filename: [name].js,
chunkFilename: [name].min.js,
libraryTarget:
"umd"
,
library:
"tools"
}
}
|
library指定的是你require時候的模塊名。