-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
49 lines (40 loc) · 1.12 KB
/
index.js
File metadata and controls
49 lines (40 loc) · 1.12 KB
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
const fs = require('fs')
const cheerio = require('cheerio')
const tags = {
script: 'src',
'link[rel="stylesheet"]': 'href',
}
function replaceRootSyntaxWithAbsolutePath(bundle) {
if (bundle.type === 'html') {
const filePath = bundle.name
const content = fs.readFileSync(filePath, 'utf8')
const $ = cheerio.load(content)
let shouldUpdate = false
Object.entries(tags).forEach(([tag, attribute]) => {
$(tag).each((i, el) => {
const $el = $(el)
const prop = $el.attr(attribute)
if (prop && prop.startsWith('#')) {
$el.attr(attribute, prop.replace(/^#/, ''))
shouldUpdate = true
}
})
if (shouldUpdate) {
fs.writeFileSync(filePath, $.html())
}
})
}
}
function forEachBundle(fn, bundle) {
fn(bundle)
if (bundle.childBundles && bundle.childBundles.size) {
for (let childBundle of bundle.childBundles) { // eslint-disable-line no-restricted-syntax
fn(childBundle)
}
}
}
module.exports = function (bundler) {
bundler.on('bundled', (bundle) => {
forEachBundle(replaceRootSyntaxWithAbsolutePath, bundle)
})
}