forked from loo-y/iPhoneOrder.2023
-
Notifications
You must be signed in to change notification settings - Fork 6
/
buildAfter.js
86 lines (71 loc) · 2.62 KB
/
buildAfter.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 extensionNextConfig = require('./extension.next.config')
const fs = require('fs')
const path = require('path')
const _ = require('lodash')
const cheerio = require('cheerio')
function getAllHtmlFiles(folderPath) {
// 获取文件夹下所有文件和文件夹的名称
const fileNames = fs.readdirSync(folderPath)
// 过滤出所有 HTML 文件
const htmlFiles = []
_.map(fileNames, fileName => {
const filePath = path.join(folderPath, fileName)
const stats = fs.statSync(filePath)
if (stats.isFile() && path.extname(filePath) === '.html') {
htmlFiles.push({
fileName: fileName.replace(/\.html$/, ''),
filePath: filePath,
})
}
})
// 递归处理所有子文件夹
const subFolders = fileNames.filter(fileName => {
const filePath = path.join(folderPath, fileName)
const stats = fs.statSync(filePath)
return stats.isDirectory()
})
_.each(subFolders, subFolder => {
const subFolderPath = path.join(folderPath, subFolder)
const subFolderHtmlFiles = getAllHtmlFiles(subFolderPath)
htmlFiles.push(...subFolderHtmlFiles)
})
return htmlFiles
}
function extractInlineScripts(htmlFilePath, outputFilePath) {
// 读取 HTML 文件内容
const html = fs.readFileSync(htmlFilePath, 'utf-8')
// 使用 cheerio 加载 HTML
const $ = cheerio.load(html)
// 获取所有的 inline script 标签
const inlineScripts = $('script').filter(function () {
return !$(this).attr('src')
})
// 提取 inline script 的内容并拼接到一起
const inlineScriptContent = inlineScripts
.map(function () {
return $(this).html()
})
.get()
.join('\n\n')
// 移除所有的 inline script 标签
inlineScripts.remove()
// 将 inline script 内容写入到指定的文件中
fs.writeFileSync(outputFilePath, inlineScriptContent)
// 将拼接后的 JS 文件引入到 HTML 中
const jsFileName = path.basename(outputFilePath)
$('body').append(`<script src="${jsFileName}"></script>`)
// 将修改后的 HTML 内容写回到原文件中
fs.writeFileSync(htmlFilePath, $.html())
}
const buildAfter = () => {
// get build path
const distDir = extensionNextConfig.distDir
const htmlFiles = getAllHtmlFiles(distDir)
if (_.isEmpty(htmlFiles)) return
_.map(htmlFiles, htmlFile => {
const { fileName, filePath } = htmlFile
const outputFilePath = path.join(filePath, '../', `${fileName}.js`)
extractInlineScripts(filePath, outputFilePath)
})
}
buildAfter()