-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdate-meta-tag.js
67 lines (59 loc) · 1.69 KB
/
update-meta-tag.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
const fs = require('fs'),
seo = require('./config/seo.config.json'),
indexPath = './src/index.html',
names = [
'description',
'twitter:card',
'twitter:title',
'twitter:description',
'twitter:image',
],
properties = [
'og:url',
'og:type',
'og:title',
'og:description',
'og:image',
'twitter:domain',
'twitter:url',
];
fs.readFile(indexPath, 'utf-8', (err, data) => {
console.log('Start update meta tags seo');
if (err) {
console.error(`Error read ${indexPath}: `, err);
process.exit(1);
}
let updatedData = data;
const title = seo?.['title']
if (title)
updatedData = data.replace(/<title>(.*?)<\/title>/gi, `<title>${title}</title>`)
const metaTagsList = data.match(/<meta\b[^>]*>/gi);
if (metaTagsList) {
metaTagsList.forEach((meta) => {
const metaCleaned = meta.replace(/\n/g, '').replace(/\s+/g, ' ');
let attribute =
names.find((name) => metaCleaned.includes(`name="${name}"`)) ||
properties.find((property) =>
metaCleaned.includes(`property="${property}"`)
);
if (attribute) {
attribute = (attribute.replace(/^[^:]+:/, ''))
if (attribute in seo) {
const updatedMeta = metaCleaned.replace(
/content="([^"]*)"/,
`content="${seo[attribute.replace(/^[^:]+:/, '')]}"`
);
updatedData = updatedData.replace(meta, updatedMeta);
}
}
});
fs.writeFile(indexPath, updatedData, 'utf-8', (writeErr) => {
if (writeErr) {
console.error(`Error write ${indexPath}: `, err);
process.exit(1);
}
console.log('End update meta tag seo');
process.exit(0);
});
}
});