Skip to content

Commit 1851baf

Browse files
committed
fix(regex): [dynamic] ignore matches in string literals
- https://regex101.com/r/PTPAvU/27 Signed-off-by: Lexus Drumgold <unicornware@flexdevelopment.llc>
1 parent b0d854b commit 1851baf

File tree

2 files changed

+25
-16
lines changed

2 files changed

+25
-16
lines changed

src/__tests__/import-dynamic.spec.ts

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,32 @@ describe('unit:DYNAMIC_IMPORT_REGEX', () => {
1212
TEST_SUBJECT.lastIndex = 0
1313
})
1414

15-
describe('comments', () => {
16-
it('should ignore import in multi-line comment', () => {
17-
// Arrange
18-
const code = dedent`
19-
/**
20-
* @example
21-
* const { readPackage } = await import('read-pkg')
22-
*/
23-
`
15+
it('should ignore match in multi-line comment', () => {
16+
// Arrange
17+
const code = dedent`
18+
/**
19+
* @example
20+
* const { readPackage } = await import('read-pkg')
21+
*/
22+
`
23+
24+
// Act + Expect
25+
expect(TEST_SUBJECT.test(code)).to.be.false
26+
})
2427

25-
// Act + Expect
26-
expect(TEST_SUBJECT.test(code)).to.be.false
27-
})
28+
it('should ignore match in single-line comment', () => {
29+
expect(TEST_SUBJECT.test('// await import("./init.mjs")')).to.be.false
30+
})
2831

29-
it('should ignore import in single-line comment', () => {
30-
expect(TEST_SUBJECT.test('// await import("./init.mjs")')).to.be.false
31-
})
32+
it('should ignore match in string literal', () => {
33+
// Arrange
34+
const code = dedent`
35+
const str1 = 'await import("foo")'
36+
const str2 = "await import('foo')"
37+
`
38+
39+
// Act + Expect
40+
expect(TEST_SUBJECT.test(code)).to.be.false
3241
})
3342

3443
describe('conditional imports', () => {

src/import-dynamic.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,6 @@
7676
* @const {RegExp} DYNAMIC_IMPORT_REGEX
7777
*/
7878
const DYNAMIC_IMPORT_REGEX: RegExp =
79-
/(?<=^|[\s;])(?:(?:const\s*|let\s*|var\s*)?(?<imports>(?:[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)|(?<=const\s*|let\s*|var\s*)(?:[\w\t\n\r "$'*,./:{}-]+?))\s*=\s*)?(?:await\s+)?(?<expression>import\((?<specifier>[\S\t\n\r]+?)(?:,\s*(?<options>\{\s*assert:.+[\w\t\n\r "':]+\}\s*\}))?\))(?<!(?:\/\/|\*).*)/gu
79+
/(?<=^|[\n;](?:[\t ]*(?:\w+ )?)?)(?:(?:const\s*|let\s*|var\s*)?(?<imports>(?:[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)|(?<=const\s*|let\s*|var\s*)(?:[\w\t\n\r "$'*,./:{}-]+?))\s*=\s*)?(?:await\s+)?(?<expression>import\((?<specifier>[\S\t\n\r]+?)(?:,\s*(?<options>\{\s*assert:.+[\w\t\n\r "':]+\}\s*\}))?\))/gu
8080

8181
export default DYNAMIC_IMPORT_REGEX

0 commit comments

Comments
 (0)