-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertToReducer.ts
More file actions
42 lines (37 loc) · 1.34 KB
/
insertToReducer.ts
File metadata and controls
42 lines (37 loc) · 1.34 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
import fs from 'fs/promises'
type PayloadType = {
name: string
pathToReducersList: string
regexp: string
pathForImportReducers: string
}
export const insertToReducer = async ({
name,
pathToReducersList,
regexp,
pathForImportReducers,
}: PayloadType) => {
try {
// Чтение содержимого файла
const data = await fs.readFile(pathToReducersList, 'utf-8')
// Замена строки // insert hook here
const reducerPlaceholder = new RegExp(`${regexp}`)
const reducerInsertion = `${name},`
const updatedDataWithReducer = data.replace(
reducerPlaceholder,
match => `${match}\n${reducerInsertion}`
)
// Добавление строки import после последней строки import
const lastImportRegex = /^import.*;?$\n(?!import)/m
const importInsertion = `import { Reducer as ${name} } from '${pathForImportReducers}${name}'\n`
const updatedDataWithImport = updatedDataWithReducer.replace(
lastImportRegex,
match => `${match}${importInsertion}`
)
// Запись изменений обратно в файл
await fs.writeFile(pathToReducersList, updatedDataWithImport, 'utf-8')
console.log('\x1b[36m', `ReducersList updated with ${name}`, '\x1b[0m')
} catch (err) {
console.error(`Error while updating ReducersList: ${err}`)
}
}