-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
77 lines (72 loc) · 2.41 KB
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// vendor.js 文本替换
// g = (function() {
// return this;
// })();
// g = (function() {
// return typeof global !== 'undefined' ? global : this;
// })();
// 支付宝环境中,每个模块打包后在模块内部global会被强制赋值undefined,可以挂载到$global中
// Component变量只有在项目中通过json配置声明组件后,打包的时候才会声明赋值,否则访问不到
// windows 0.27版本的调试工具与macOS不同,这里需要向前兼容
const banner = `
if (!global) {
var globalModule = {};
try {
globalModule = require('global');
}
catch (e) {
globalModule = require('core-js').global;
}
var Component = Component ? Component : globalModule.AFAppX.WorkerComponent;
var global = globalModule.AFAppX.$global || {};
}
`;
function mpvueVendorPlugin(options) {
this.options = options || {};
}
mpvueVendorPlugin.prototype.apply = function(compiler) {
const isAlipay = this.options.platform && this.options.platform === 'my';
if (isAlipay) {
compiler.plugin("emit", (compilation, callback) => {
const regExp = /\.js$/;
const filesName = Object.keys(compilation.assets).filter(name =>
name.match(regExp)
);
filesName.forEach(name => {
let asset = compilation.assets[name];
let fileContent = asset.source();
compilation.assets[name] = {
source: () => {
return banner + "\n" + fileContent;
},
size: () => {
return Buffer.byteLength(fileContent, "utf8");
}
};
});
callback();
});
}
compiler.plugin('compilation', (compilation) => {
compilation.plugin('additional-chunk-assets', () => {
const fileName = 'common/vendor.js';
const asset = compilation.assets[fileName];
if (asset) {
let fileContent = asset.source();
compilation.assets[fileName] = Object.assign(asset, {
source: () => {
let from = /g\s=\s\(function\(\)\s\{\r?\n?\s+return\sthis;\r?\n?\s*\}\)\(\)\;/;
let to = `g = (function() { return typeof global !== 'undefined' ? global : this; })();`
fileContent = fileContent.replace(from, to)
return fileContent;
},
size: () => {
return Buffer.byteLength(fileContent, 'utf8');
},
sourceAndMap: false
})
}
});
});
};
module.exports = mpvueVendorPlugin;