-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
92 lines (74 loc) · 2.49 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* enhance of HtmlWebpackPlugin,
* fix reference of js/css when build multi-entry files
*/
function HtmlWebpackPluginAssetsFix(options) {
options = options || {}
this.fixAssets = options.fixAssets
}
const TRIM_ARGS = [/^\.\//, /^\s*/, /\s*$/, /\/$/]
// clear path
function trim(path) {
return TRIM_ARGS.reduce((ret, arg) => {
ret = ret.replace(arg, '')
return ret
}, path)
}
function fixPath(assetPath, htmlPath) {
assetPath = trim(assetPath)
htmlPath = trim(htmlPath)
//if asset is from cdn, ignore it
if (assetPath.startsWith('//')) {
return assetPath
}
if (assetPath.charAt(0) === '/') {
assetPath = assetPath.substring(1)
}
let assetSegs = assetPath.split('/')
const htmlSegs = htmlPath.split('/')
let dupNum = 0
for (let i = 0, len = htmlSegs.length; i < len; i++) {
if (htmlSegs[i] === assetSegs[i]) {
++dupNum
} else {
break
}
}
if (dupNum) {
htmlSegs.splice(0, dupNum)
assetSegs.splice(0, dupNum)
}
const htmlSize = htmlSegs.length
if (htmlSize > 1) {
const lpad = new Array(htmlSize - 1)
lpad.fill('..')
assetSegs = [...lpad, ...assetSegs]
}
return assetSegs.join('/')
}
HtmlWebpackPluginAssetsFix.prototype.apply = function(compiler) {
const self = this
compiler.plugin('compilation', function(compilation) {
compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, possiblyCallback) {
const promise = new Promise((resolve, reject) => {
const callback = possiblyCallback || ((err, res) => err ? reject(err) : resolve(res));
if (!self.fixAssets) {
callback(null, htmlPluginData)
return;
}
const outputName = htmlPluginData.outputName
const assets = htmlPluginData.assets
const publicPath = assets.publicPath
assets.js = assets.js.map(assetfile => {
return fixPath(assetfile.replace(publicPath, ''), outputName)
})
assets.css = assets.css.map(assetfile => {
return fixPath(assetfile.replace(publicPath, ''), outputName)
})
callback(null, htmlPluginData)
});
return possiblyCallback ? undefined : promise;
})
})
}
module.exports = HtmlWebpackPluginAssetsFix