Skip to content

Commit e299b77

Browse files
committed
batch-handle-resource
1 parent e163869 commit e299b77

File tree

8 files changed

+245
-56
lines changed

8 files changed

+245
-56
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22

33
用于批量处理资源。
44

5-
- transformImage 图片转换等操作
6-
- replaceFileContent 文件内容
5+
- transformImage 批量图片转换
6+
- replaceFileContent 批量文件替换内容

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"main": "src/index.ts",
66
"scripts": {
77
"start": "tsx src/index.ts",
8-
"test": "echo \"Error: no test specified\" && exit 1"
8+
"test": "tsx test/index.ts"
99
},
1010
"keywords": [],
1111
"author": "CoderHXL",

src/index.ts

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,78 @@ import sharp from 'sharp'
44
import transformImage from './transformImage'
55
import replaceFileContent from './replaceFileContent'
66

7+
const BASE_PATH = 'D:/CoderHXL/Project/spyx-next-web'
8+
const ENTER_PATH = BASE_PATH + '/public'
9+
const OUTPUT_PATH = BASE_PATH + '/public'
10+
const FILE_ENTER_PATH = BASE_PATH + '/src'
11+
const LOG_FILE_PATH = 'D:/CoderHXL/性能优化/图片优化'
12+
13+
const errorList: { path: string; message: string }[] = []
14+
15+
function start() {
16+
async function imageFormatWebp(entryPath: string, outputPath: string) {
17+
try {
18+
const buffer = await sharp(entryPath).toFormat('webp').toBuffer()
19+
await fs.promises.writeFile(outputPath, buffer)
20+
await fs.promises.unlink(entryPath)
21+
22+
return buffer
23+
} catch (error: any) {
24+
errorList.push({ path: entryPath, message: error.message })
25+
}
26+
}
27+
28+
transformImage({
29+
entry: ENTER_PATH,
30+
output: OUTPUT_PATH,
31+
32+
mkdir: true,
33+
logFileGeneratePath: LOG_FILE_PATH,
34+
35+
useFile: { dir: FILE_ENTER_PATH, imageInFileAlias: { [ENTER_PATH]: '' } },
36+
37+
rules: [
38+
{
39+
name: 'png',
40+
format: [
41+
{
42+
name: 'webp',
43+
handle: ({ entryPath, outputPath }) =>
44+
imageFormatWebp(entryPath, outputPath)
45+
}
46+
]
47+
},
48+
{
49+
name: 'jpg',
50+
format: [
51+
{
52+
name: 'webp',
53+
handle: ({ entryPath, outputPath }) =>
54+
imageFormatWebp(entryPath, outputPath)
55+
}
56+
]
57+
}
58+
]
59+
}).then(async (pathInfoList) => {
60+
if (errorList.length) {
61+
console.log(`Error: list: ${errorList} - length: ${errorList.length} `)
62+
}
63+
64+
const replaceInfo = pathInfoList.map((item) => ({
65+
searchValue: item.entryPath.replace(OUTPUT_PATH, ''),
66+
replaceValue: item.outputPath.replace(OUTPUT_PATH, '')
67+
}))
68+
69+
// 更新文件内图片资源的 URL
70+
await replaceFileContent({
71+
entry: FILE_ENTER_PATH,
72+
list: replaceInfo,
73+
74+
logFileGeneratePath: LOG_FILE_PATH
75+
})
76+
77+
console.log('完成 - 图片转换以及更新路径')
78+
})
79+
}
80+
81+
start()

src/replaceFileContent.ts

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,60 @@
11
import fs from 'node:fs'
2-
import { getAllDirFileContentAndPath } from './shared'
2+
import { getAllDirFileContentAndPath, LogFileGenerate } from './shared'
3+
4+
const logFileGenerate = new LogFileGenerate(
5+
'文件内图片 URL 更新',
6+
'# 文件内图片 URL 更新',
7+
['次数', '位置']
8+
)
39

410
interface ReplaceFileContent {
511
entry: string
6-
712
list: { searchValue: string; replaceValue: string }[]
13+
14+
logFileGeneratePath?: string
15+
itemLog?: boolean
816
}
917

1018
export default async function replaceFileContent(config: ReplaceFileContent) {
11-
const { entry, list } = config
19+
const { entry, list, itemLog = true, logFileGeneratePath } = config
1220
const startTime = Date.now()
1321

14-
console.log('替换任务开始')
22+
console.log('替换文件内容任务开始')
1523

16-
const fileInfo = await getAllDirFileContentAndPath(entry)
24+
const fileInfoList = await getAllDirFileContentAndPath(entry)
1725

26+
const replaceQueue: { path: string; content: string }[] = []
1827
for (const item of list) {
1928
const { searchValue, replaceValue } = item
2029

21-
for (const cItem of fileInfo) {
22-
const { path, content } = cItem
30+
for (const fileInfo of fileInfoList) {
31+
const { content } = fileInfo
2332
if (!content.includes(searchValue)) continue
2433

25-
console.log('正在处理: ', path)
34+
fileInfo.content = content.replaceAll(searchValue, replaceValue)
35+
36+
replaceQueue.push(fileInfo)
37+
}
38+
}
39+
40+
console.log(`文件数量: ${replaceQueue.length}`)
41+
42+
// 替换文件内容
43+
let i = 0
44+
for (const fileInfo of replaceQueue) {
45+
const { path, content } = fileInfo
2646

27-
const newContent = content.replaceAll(searchValue, replaceValue)
47+
if (itemLog) console.log('正在替换: ', path)
2848

29-
await fs.promises.writeFile(path, newContent)
49+
if (!logFileGenerate.content.includes(path)) {
50+
logFileGenerate.addRow([++i, path])
3051
}
52+
53+
await fs.promises.writeFile(path, content)
3154
}
3255

56+
logFileGenerate.generate(logFileGeneratePath)
57+
3358
const endTime = Date.now()
34-
console.log(`替换任务结束 耗时: ${(endTime - startTime) / 1000}s`)
59+
console.log(`替换文件内容任务结束 耗时: ${(endTime - startTime) / 1000}s`)
3560
}

src/shared/file.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ export function getFilePath(
88
const transformToPaths = dirs.reduce((prev, v) => {
99
if (v.isDirectory()) return prev
1010

11-
let path = `${v.parentPath}/${v.name}`
11+
let filePath = `${v.parentPath}/${v.name}`
1212

13-
if (path.includes('\\')) {
14-
path = `${path.replaceAll('\\', '/')}`
13+
if (filePath.includes('\\')) {
14+
filePath = filePath.replaceAll('\\', '/')
1515
}
1616

17-
if (filter && !filter(path)) return prev
17+
if (filter && !filter(filePath)) return prev
1818

19-
prev.push(path)
19+
prev.push(filePath)
2020

2121
return prev
2222
}, [] as string[])

src/shared/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './general'
22
export * from './file'
3+
export * from './logFileGenerate'

src/shared/logFileGenerate.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import fs from 'node:fs'
2+
3+
export class LogFileGenerate {
4+
private name: string
5+
content = ''
6+
7+
constructor(name: string, title: string, header: string[]) {
8+
this.name = name
9+
10+
this.content += `${title}\n`
11+
12+
this.content += `| ${header.join(' | ')} |\n`
13+
this.content += `| ${header.map((v) => '-----').join(' | ')} |\n`
14+
}
15+
16+
addRow(row: (string | number)[]) {
17+
this.content += `| ${row.join(' | ')} |\n`
18+
}
19+
20+
async generate(path?: string) {
21+
await fs.promises.writeFile(
22+
`${path}/${this.name}-${Date.now()}.md`,
23+
this.content
24+
)
25+
}
26+
}

0 commit comments

Comments
 (0)