forked from un-ts/eslint-plugin-import-x
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdynamic-import-chunkname.ts
245 lines (220 loc) · 7.06 KB
/
dynamic-import-chunkname.ts
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import vm from 'node:vm'
import type { TSESTree } from '@typescript-eslint/utils'
import type { RuleFixer } from '@typescript-eslint/utils/ts-eslint'
import { createRule } from '../utils'
type Options = {
allowEmpty?: boolean
importFunctions?: readonly string[]
webpackChunknameFormat?: string
}
type MessageId =
| 'leadingComment'
| 'blockComment'
| 'paddedSpaces'
| 'webpackComment'
| 'chunknameFormat'
| 'webpackEagerModeNoChunkName'
| 'webpackRemoveEagerMode'
| 'webpackRemoveChunkName'
export = createRule<[Options?], MessageId>({
name: 'dynamic-import-chunkname',
meta: {
type: 'suggestion',
docs: {
category: 'Style guide',
description:
'Enforce a leading comment with the webpackChunkName for dynamic imports.',
},
hasSuggestions: true,
schema: [
{
type: 'object',
properties: {
importFunctions: {
type: 'array',
uniqueItems: true,
items: {
type: 'string',
},
},
allowEmpty: {
type: 'boolean',
},
webpackChunknameFormat: {
type: 'string',
},
},
},
],
messages: {
leadingComment:
'dynamic imports require a leading comment with the webpack chunkname',
blockComment:
'dynamic imports require a /* foo */ style comment, not a // foo comment',
paddedSpaces:
'dynamic imports require a block comment padded with spaces - /* foo */',
webpackComment:
'dynamic imports require a "webpack" comment with valid syntax',
chunknameFormat:
'dynamic imports require a leading comment in the form /* {{format}} */',
webpackEagerModeNoChunkName:
'dynamic imports using eager mode do not need a webpackChunkName',
webpackRemoveEagerMode: 'Remove webpackMode',
webpackRemoveChunkName: 'Remove webpackChunkName',
},
},
defaultOptions: [],
create(context) {
const {
importFunctions = [],
allowEmpty = false,
webpackChunknameFormat = '([0-9a-zA-Z-_/.]|\\[(request|index)\\])+',
} = context.options[0] || {}
const paddedCommentRegex = /^ (\S[\S\s]+\S) $/
const commentStyleRegex =
/^( (((webpackChunkName|webpackFetchPriority): .+)|((webpackPrefetch|webpackPreload): (true|false|-?\d+))|(webpackIgnore: (true|false))|((webpackInclude|webpackExclude): \/.+\/)|(webpackMode: ["'](lazy|lazy-once|eager|weak)["'])|(webpackExports: (["']\w+["']|\[(["']\w+["'], *)+(["']\w+["']*)]))),?)+ $/
const chunkSubstrFormat = `webpackChunkName: ["']${webpackChunknameFormat}["'],?`
const chunkSubstrRegex = new RegExp(chunkSubstrFormat)
const eagerModeFormat = `webpackMode: ["']eager["'],?`
const eagerModeRegex = new RegExp(eagerModeFormat)
function run(node: TSESTree.Node, arg: TSESTree.Node) {
const { sourceCode } = context
const leadingComments = sourceCode.getCommentsBefore(arg)
if ((!leadingComments || leadingComments.length === 0) && !allowEmpty) {
context.report({
node,
messageId: 'leadingComment',
})
return
}
let isChunknamePresent = false
let isEagerModePresent = false
for (const comment of leadingComments) {
if (comment.type !== 'Block') {
context.report({
node,
messageId: 'blockComment',
})
return
}
if (!paddedCommentRegex.test(comment.value)) {
context.report({
node,
messageId: 'paddedSpaces',
})
return
}
try {
// just like webpack itself does
vm.runInNewContext(`(function() {return {${comment.value}}})()`)
} catch {
context.report({
node,
messageId: 'webpackComment',
})
return
}
if (!commentStyleRegex.test(comment.value)) {
context.report({
node,
messageId: 'webpackComment',
})
return
}
if (eagerModeRegex.test(comment.value)) {
isEagerModePresent = true
}
if (chunkSubstrRegex.test(comment.value)) {
isChunknamePresent = true
}
}
const removeCommentsAndLeadingSpaces = (
fixer: RuleFixer,
comment: TSESTree.Comment,
) => {
const leftToken = sourceCode.getTokenBefore(comment)
const leftComments = sourceCode.getCommentsBefore(comment)
if (leftToken) {
if (leftComments.length > 0) {
return fixer.removeRange([
Math.max(
leftToken.range[1],
leftComments[leftComments.length - 1].range[1],
),
comment.range[1],
])
}
return fixer.removeRange([leftToken.range[1], comment.range[1]])
}
return fixer.remove(comment)
}
if (isChunknamePresent && isEagerModePresent) {
context.report({
node,
messageId: 'webpackEagerModeNoChunkName',
suggest: [
{
messageId: 'webpackRemoveChunkName',
fix(fixer) {
for (const comment of leadingComments) {
if (chunkSubstrRegex.test(comment.value)) {
const replacement = comment.value
.replace(chunkSubstrRegex, '')
.trim()
.replace(/,$/, '')
return replacement === ''
? removeCommentsAndLeadingSpaces(fixer, comment)
: fixer.replaceText(comment, `/* ${replacement} */`)
}
}
return null
},
},
{
messageId: 'webpackRemoveEagerMode',
fix(fixer) {
for (const comment of leadingComments) {
if (eagerModeRegex.test(comment.value)) {
const replacement = comment.value
.replace(eagerModeRegex, '')
.trim()
.replace(/,$/, '')
return replacement === ''
? removeCommentsAndLeadingSpaces(fixer, comment)
: fixer.replaceText(comment, `/* ${replacement} */`)
}
}
return null
},
},
],
})
}
if (!isChunknamePresent && !allowEmpty && !isEagerModePresent) {
context.report({
node,
messageId: 'chunknameFormat',
data: {
format: chunkSubstrFormat,
},
})
}
}
return {
ImportExpression(node) {
run(node, node.source)
},
CallExpression(node) {
if (
// @ts-expect-error - legacy parser type
node.callee.type !== 'Import' &&
'name' in node.callee &&
!importFunctions.includes(node.callee.name)
) {
return
}
run(node, node.arguments[0])
},
}
},
})