-
Notifications
You must be signed in to change notification settings - Fork 867
/
buildAppJSPlugin.js
86 lines (81 loc) · 2.42 KB
/
buildAppJSPlugin.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
78
79
80
81
82
83
84
85
86
const cdnDependencies = require("./dependencies-cdn");
// 引入文件的 cdn 链接
const cdn = {
css: cdnDependencies.map((e) => e.css).filter((e) => e),
js: cdnDependencies.map((e) => e.js).filter((e) => e),
};
class BuildAppJSPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync(
"BuildAppJSPlugin",
(compilation, callback) => {
const isProd = process.env.NODE_ENV === "production"
let cssarr = [];
let jsarr = [];
let reg = "";
if (isProd) {
reg = "(app|chunk-vendors)\\.";
}
// 遍历所有编译过的资源文件
for (let filename in compilation.assets) {
if (filename.match(reg + ".*\\.js$")) {
if (isProd) {
filename = (process.env.VUE_APP_CDN_PATH || "/") + filename;
} else {
filename = "/" + filename;
}
jsarr.push(filename);
}
if (filename.match(reg + ".*\\.css$")) {
cssarr.push(filename);
}
}
cssarr = cssarr.sort(function (a) {
return a.indexOf("app.");
});
var cdnjs = "";
if (isProd) {
cssarr = cdn.css.concat(cssarr);
cdnjs = `var cdnjs = ${JSON.stringify(cdn.js)};
cdnjs.forEach((item) => {
document.write('<script src="' + item + '"></script>');
});`;
} else {
cssarr = cssarr.concat(
cdnDependencies.filter((e) => e.name === "").map((e) => e.css)
);
}
let content = `
var scripts = ${JSON.stringify(jsarr)};
${cdnjs}
scripts.forEach((item) => {
document.write('<script src="' + item + '"></script>');
});
`;
let cssContent = "";
cssarr.forEach((item) => {
cssContent += `@import url(${item});\n`;
});
// 将这个列表作为一个新的文件资源,插入到 webpack 构建中:
compilation.assets["app.js"] = {
source: function () {
return content;
},
size: function () {
return jsarr.length;
},
};
compilation.assets["style.css"] = {
source: function () {
return cssContent;
},
size: function () {
return cssarr.length;
},
};
callback();
}
);
}
}
module.exports = BuildAppJSPlugin;