This repository was archived by the owner on Jul 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
194 lines (171 loc) · 5.07 KB
/
index.js
File metadata and controls
194 lines (171 loc) · 5.07 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* The following code is modified based on
* https://github.com/seek-oss/css-modules-typescript-loader
*
* only generator .d.ts for css modules file
*
* MIT Licensed
* Author mattcompiles
* Copyright 2018 SEEK
* https://github.com/seek-oss/css-modules-typescript-loader/blob/master/LICENSE
*/
const path = require('path')
const fs = require('fs')
const lineDiff = require('line-diff')
const bannerMessage = `
/**
* This file is automatically generated.
* Please do not change this file!
* 该文件根据*.module.less自动生成,修改无效
*/
`
const cssModuleExport = 'export const cssExports: CssExports;\nexport default cssExports;\n'
/**
*
* @param {NodeJS.ErrnoException} err
* @returns {boolean}
*/
const isFileNotFound = (err) => err && err.code === 'ENOENT'
const enforceLFLineSeparators = (text) => {
if (text) {
return text.replace(/\r\n/g, '\n')
} else {
return text
}
}
const compareText = (contentA, contentB) => {
return enforceLFLineSeparators(contentA) === enforceLFLineSeparators(contentB)
}
/**
* 返回类型声明文件的路径
* @param {string} filename
* @returns {string}
*/
const interfaceFilename = (filename) => {
return path.join(path.dirname(filename), `${path.basename(filename)}.d.ts`)
}
/**
*
* @param {fs.PathOrFileDescriptor} filename
* @returns {{read:(handler:(err: NodeJS.ErrnoException | null, data: string) => void)=>void}}
*/
const makeFileHandlers = (filename) => {
return {
read: (handler) => fs.readFile(filename, { encoding: 'utf-8' }, handler),
write: (content, handler) => fs.writeFile(filename, content, { encoding: 'utf-8' }, handler),
}
}
const makeDoneHandler = (callback, content, rest) => {
return {
reject: (err) => callback(err),
resolve: () => callback(null, content, ...rest),
}
}
/**
* 用于拼装 interface
* @param {string[]} className
* @returns string
*/
const cssModuleToInterface = (className) => {
const interfaceFields = className
.sort()
.map((key) => ` '${key}':string;`)
.join('\n')
return `interface CssExports {\n${interfaceFields}\n}`
}
const getFilename = (path, scope = 'module') => {
if (scope === 'module') {
if (path.includes('module')) {
return path
}
} else {
return path
}
}
/**
* Generated type declaration does not exist。
* 类型文件声明文件不存在。
* @param {{filename:string}} filename
* @returns { Error }
*/
const throwNotFoundFilError = ({ filename }) =>
new Error(`Generated type declaration does not exist. Run rspack and commit the type declaration for '${filename}'`)
/**
*
* @param {{filename:string,expected:string,actual:string}} param - 参数描述
* - `filename`:文件名
* - `expected`: 预期的文件
* - `actual`: 实际的文件
* @returns { Error }
*/
const getTypeMismatchError = ({ filename, expected, actual }) => {
const diff = new lineDiff(enforceLFLineSeparators(actual), expected).toString()
return new Error(
`Generated type declaration file is outdated. Run webpack and commit the updated type declaration for '${filename}'\n\n${diff}`
)
}
module.exports = function (source, ...rest) {
/** @type {import('./index').Options} */
const options = this.getOptions()
const { scope = 'module', mode = 'emit', banner = '' } = options
/** @type {string} type - description */
const filename =
scope === 'module' ? (this.resourcePath.includes('module') ? this.resourcePath : '') : this.resourcePath
const { resolve, reject } = makeDoneHandler(this.async(), source, rest)
if (!filename) {
return resolve()
}
const cssModuleInterfaceFilename = interfaceFilename(filename)
const { read, write } = makeFileHandlers(cssModuleInterfaceFilename)
const regex = /(?<=\}\s*|^)(\.[a-zA-Z0-9_-]+)(?=\s*{)/g
/** @type {string} type - 通过正则捕获的类名 */
let match
/** @type {string[]} type - less文件里的类目*/
const classNames = []
while ((match = regex.exec(source))) {
if (classNames.indexOf(match[1]) < 0) {
classNames.push(match[1].replace('.', ''))
}
}
/** @type {string} type - 生成的类型文件 */
const interfaceFile = `${banner || bannerMessage}\n${cssModuleToInterface(classNames)}\n${cssModuleExport}`
if (mode === 'verify') {
read((err, fileContent) => {
// 没有目录或文件
if (isFileNotFound(err)) {
return reject(
throwNotFoundFilError({
filename: cssModuleInterfaceFilename,
})
)
}
if (err) {
return reject(err)
}
if (!compareText(interfaceFile, fileContent)) {
return reject(
getTypeMismatchError({
filename: cssModuleInterfaceFilename,
expected: interfaceFile,
actual: fileContent,
})
)
}
return resolve()
})
} else {
read((_, fileContent) => {
if (!compareText(interfaceFile, fileContent)) {
write(interfaceFile, (err) => {
if (err) {
return reject(err)
} else {
return resolve()
}
})
} else {
return resolve()
}
})
}
}