-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsCss2JsonPlugin.js
175 lines (166 loc) · 6.65 KB
/
JsCss2JsonPlugin.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const fs = require('fs');
const path = require('path');
const minify = require('html-minifier').minify;
class JsCss2JsonPlugin {
constructor() {
this.distPath = '';
this.publicPath = '';
this.assets = {
js: [],
css: []
};
}
/**
* 获取js和css文件路径
* @param {*} compilation
* @param {*} entryNames
*/
JsCss2JsonPluginAssets(compilation, entryNames) {
const compilationHash = compilation.hash;
const webpackPublicPath = compilation.mainTemplate.getPublicPath({ hash: compilationHash });
const isPublicPathDefined = webpackPublicPath.trim() !== '';
this.publicPath = isPublicPathDefined
// If a hard coded public path exists use it
? webpackPublicPath
// If no public path was set get a relative url path
: path.relative(path.resolve(compilation.options.output.path), compilation.options.output.path)
.split(path.sep).join('/');
if (this.publicPath.length && this.publicPath.substr(-1, 1) !== '/') {
this.publicPath += '/';
}
// Extract paths to .js, .mjs and .css files from the current compilation
const entryPointPublicPathMap = {};
const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
for (let i = 0; i < entryNames.length; i++) {
const entryName = entryNames[i];
const entryPointFiles = compilation.entrypoints.get(entryName).getFiles();
// Prepend the publicPath and append the hash depending on the
// webpack.output.publicPath and hashOptions
// E.g. bundle.js -> /bundle.js?hash
const entryPointPublicPaths = entryPointFiles
.map(chunkFile => this.publicPath + chunkFile);
entryPointPublicPaths.forEach((entryPointPublicPath) => {
const extMatch = extensionRegexp.exec(entryPointPublicPath);
// Skip if the public path is not a .css, .mjs or .js file
if (!extMatch) {
return;
}
// Skip if this file is already known
// (e.g. because of common chunk optimizations)
if (entryPointPublicPathMap[entryPointPublicPath]) {
return;
}
entryPointPublicPathMap[entryPointPublicPath] = true;
// ext will contain .js or .css, because .mjs recognizes as .js
const ext = extMatch[1] === 'mjs' ? 'js' : extMatch[1];
this.assets[ext].push(entryPointPublicPath);
});
}
}
saveJson() {
if (this.distPath.length && this.distPath.substr(-1, 1) !== '/') {
this.distPath += '/';
}
fs.writeFileSync(`${this.distPath}index.json`, JSON.stringify(this.assets, null, 4));
const templatePath = `${this.distPath}template.html`;
if (fs.existsSync(templatePath)) {
console.log('exist');
fs.unlinkSync(templatePath);
}
}
/**
* 注入js
* @param {*} distPath
* @param {*} assets
*/
injectJs() {
if (this.distPath.length && this.distPath.substr(-1, 1) !== '/') {
this.distPath += '/';
}
const htmlPath = this.distPath + 'index.html';
let content = fs.readFileSync(htmlPath, 'utf-8');
const scriptContent = `
<script>
var loadAssetsList = function (type, list, callback) {
var loaded = 0;
loadCallcack = function() {
loaded++;
if (loaded >= list.length) {
callback();
} else {
loadNext();
}
}
var loadNext = function() {
if (type === 'script') {
loadScript(list[loaded], loadCallcack)
} else if (type === 'css') {
loadCss(list[loaded], loadCallcack)
} else {
loadNext();
}
};
loadNext();
};
var loadScript = function(src, callback) {
var s = document.createElement('script');
s.async = false;
s.src = src;
s.addEventListener('load', function() {
s.removeEventListener('load', arguments.callee, false);
callback();
}, false);
document.body.appendChild(s);
};
var loadCss = function(url, callback) {
var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
link.addEventListener('load', function () {
link.removeEventListener('load', arguments.callee, false);
callback();
}, false);
document.body.appendChild(link);
}
var xhr = new XMLHttpRequest();
xhr.open('GET', '${this.publicPath}index.json?v=' + Math.random(), true);
xhr.addEventListener("load", function () {
var assets = JSON.parse(xhr.response);
loadAssetsList('css', assets.css, function () {
// 这里是css加载完,正常是不需要处理的
});
loadAssetsList('script', assets.js, function () {
// 这里是js加载完
});
});
xhr.send(null);
</script>`;
fs.writeFileSync(htmlPath, minify(
content.replace('<noscript>jscss2jsonplugin inject js</noscript>', scriptContent),
{
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
));
}
apply(compiler) {
compiler.hooks.afterEmit.tapAsync('JsCss2JsonPlugin', (compilation, callback)=> {
const entryNames = Array.from(compilation.entrypoints.keys());
this.JsCss2JsonPluginAssets(compilation, entryNames);
this.distPath = compilation.mainTemplate.outputOptions.path;
this.saveJson();
this.injectJs();
callback();
});
}
}
module.exports = JsCss2JsonPlugin;